diff --git a/README.md b/README.md index 5334679..9ee8149 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ jobs: - name: Checkout uses: actions/checkout@v2 - - name: WebPageTest - uses: WPO-Foundation/webpagetest-github-action@main + - name: WebPageTest + uses: catchpoint/WebPageTest.github-action@main with: apiKey: ${{ secrets.WPT_API_KEY }} urls: | @@ -62,7 +62,7 @@ The tests will be run with the following WebPageTest settings: However, WebPageTest is capable of going _very_ deep, and the GitHub Action provides a number of configuration settings to help fine-tune your tests and even fail a pull request if performance budgets aren't met. ### Setting performance budgets -WebPageTest's GitHub Action uses the [WebPageTest API Wrapper for NodeJS](https://github.com/marcelduran/webpagetest-api) under the hood. The wrapper provides [test specs](https://github.com/marcelduran/webpagetest-api/wiki/Test-Specs) functionality that lets you set budgets on any of the metrics returned by the WebPageTest API. +WebPageTest's GitHub Action uses the [WebPageTest API Wrapper for NodeJS](https://github.com/catchpoint/WebPageTest.api-nodejs) under the hood. The wrapper provides [test specs](https://github.com/catchpoint/WebPageTest.api-nodejs/wiki/Test-Specs) functionality that lets you set budgets on any of the metrics returned by the WebPageTest API. The GitHub Action lets you provide a path to a specs JSON file using the `budget` input. If a specs file is included, WebPageTest's GitHub Action will test the results against the budgets you've defined. If any budget isn't met, the tests will fail and you'll be provided with links to dig into the full WebPageTest results to see what was slowing things down. @@ -80,7 +80,7 @@ jobs: uses: actions/checkout@v2 - name: WebPageTest - uses: WPO-Foundation/webpagetest-github-action@main + uses: catchpoint/WebPageTest.github-action@main with: apiKey: ${{ secrets.WPT_API_KEY }} urls: | @@ -106,7 +106,7 @@ WebPageTest would test each run's First Contentful Paint. If the First Contentfu ![Example of a WPT action failing the PR if a budget is exceeded](/images/wpt-action-fail-pr.png) -The specs format provides tremendous flexiblity in which metrics you want to budget against. For more information, check out [the official documentation](https://github.com/marcelduran/webpagetest-api/wiki/Test-Specs). +The specs format provides tremendous flexiblity in which metrics you want to budget against. For more information, check out [the official documentation](https://github.com/catchpoint/WebPageTest.api-nodejs/wiki/Test-Specs). ### Testing against a deployment URL If you are going to set and enforce performance budgets, **make sure to pass a preview URL** to test against to make sure that you're testing against the latest changes, not against a prior version of your site. @@ -131,7 +131,7 @@ jobs: site_name: 'your-netlify-site-name' - name: WebPageTest - uses: WPO-Foundation/webpagetest-github-action@main + uses: catchpoint/WebPageTest.github-action@main with: apiKey: ${{ secrets.WPT_API_KEY }} urls: | @@ -149,7 +149,7 @@ _If you are testing against a Netlify deployment preview, it's important to note ``` ### Customizing your WebPageTest tests -There are a _lot_ of [options available in WebPageTest](https://github.com/marcelduran/webpagetest-api#test-works-for-runtest-method-only) to customize your test results, record custom metrics, or do advanced scripting and multi-page flows. +There are a _lot_ of [options available in WebPageTest](https://github.com/catchpoint/WebPageTest.api-nodejs#test-works-for-runtest-method-only) to customize your test results, record custom metrics, or do advanced scripting and multi-page flows. To give you the ability to customize you tests, the WebPageTest GitHub Action let's you provide the path to a JSON object with your test options, using the `wptOptions` input. @@ -167,7 +167,7 @@ jobs: uses: actions/checkout@v2 - name: WebPageTest - uses: WPO-Foundation/webpagetest-github-action@main + uses: catchpoint/WebPageTest.github-action@main with: apiKey: ${{ secrets.WPT_API_KEY }} urls: | diff --git a/action.yml b/action.yml index b8cc2ae..1cd527d 100644 --- a/action.yml +++ b/action.yml @@ -1,28 +1,28 @@ -name: 'WebPageTest GitHub Action' -author: 'WebPageTest' -description: 'Automatically test code changes in WebPageTest and enforce performance budgets' +name: "WebPageTest GitHub Action" +author: "WebPageTest" +description: "Automatically test code changes in WebPageTest and enforce performance budgets" inputs: apiKey: - description: 'WebPageTest API Token' + description: "WebPageTest API Token" required: true urls: - description: 'List of URL(s) to test' + description: "List of URL(s) to test" required: true budget: - description: 'Path to WebPageTest testspecs.json file' + description: "Path to WebPageTest testspecs.json file" required: false label: - description: 'Label for test (shows up in WebPageTest)' + description: "Label for test (shows up in WebPageTest)" required: false wptOptions: - description: 'Path to JSON file with WebPageTest test options (see https://github.com/marcelduran/webpagetest-api#test-works-for-runtest-method-only)' + description: "Path to JSON file with WebPageTest test options (see https://github.com/marcelduran/webpagetest-api#test-works-for-runtest-method-only)" required: false GITHUB_TOKEN: - description: 'Secret GitHub Token (automatically provided by GitHub)' + description: "Secret GitHub Token (automatically provided by GitHub)" default: ${{ github.token }} runs: - using: 'node12' - main: 'index.js' + using: "node12" + main: "index.js" branding: - icon: 'bar-chart-2' - color: 'blue' \ No newline at end of file + icon: "bar-chart-2" + color: "blue" diff --git a/node_modules/.bin/_mocha b/node_modules/.bin/_mocha deleted file mode 120000 index f2a54ff..0000000 --- a/node_modules/.bin/_mocha +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/_mocha \ No newline at end of file diff --git a/node_modules/.bin/_mocha b/node_modules/.bin/_mocha new file mode 100644 index 0000000..47a3b10 --- /dev/null +++ b/node_modules/.bin/_mocha @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mocha/bin/_mocha" "$@" +else + exec node "$basedir/../mocha/bin/_mocha" "$@" +fi diff --git a/node_modules/.bin/ejs b/node_modules/.bin/ejs deleted file mode 120000 index 88e80d0..0000000 --- a/node_modules/.bin/ejs +++ /dev/null @@ -1 +0,0 @@ -../ejs/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/ejs b/node_modules/.bin/ejs new file mode 100644 index 0000000..002d2ac --- /dev/null +++ b/node_modules/.bin/ejs @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../ejs/bin/cli.js" "$@" +else + exec node "$basedir/../ejs/bin/cli.js" "$@" +fi diff --git a/node_modules/.bin/flat b/node_modules/.bin/flat deleted file mode 120000 index 5fed16b..0000000 --- a/node_modules/.bin/flat +++ /dev/null @@ -1 +0,0 @@ -../flat/cli.js \ No newline at end of file diff --git a/node_modules/.bin/flat b/node_modules/.bin/flat new file mode 100644 index 0000000..50faba1 --- /dev/null +++ b/node_modules/.bin/flat @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../flat/cli.js" "$@" +else + exec node "$basedir/../flat/cli.js" "$@" +fi diff --git a/node_modules/.bin/he b/node_modules/.bin/he deleted file mode 120000 index 2a8eb5e..0000000 --- a/node_modules/.bin/he +++ /dev/null @@ -1 +0,0 @@ -../he/bin/he \ No newline at end of file diff --git a/node_modules/.bin/he b/node_modules/.bin/he new file mode 100644 index 0000000..70e18de --- /dev/null +++ b/node_modules/.bin/he @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../he/bin/he" "$@" +else + exec node "$basedir/../he/bin/he" "$@" +fi diff --git a/node_modules/.bin/jake b/node_modules/.bin/jake deleted file mode 120000 index 3626745..0000000 --- a/node_modules/.bin/jake +++ /dev/null @@ -1 +0,0 @@ -../jake/bin/cli.js \ No newline at end of file diff --git a/node_modules/.bin/jake b/node_modules/.bin/jake new file mode 100644 index 0000000..8580efe --- /dev/null +++ b/node_modules/.bin/jake @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../jake/bin/cli.js" "$@" +else + exec node "$basedir/../jake/bin/cli.js" "$@" +fi diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml deleted file mode 120000 index 9dbd010..0000000 --- a/node_modules/.bin/js-yaml +++ /dev/null @@ -1 +0,0 @@ -../js-yaml/bin/js-yaml.js \ No newline at end of file diff --git a/node_modules/.bin/js-yaml b/node_modules/.bin/js-yaml new file mode 100644 index 0000000..ed78a86 --- /dev/null +++ b/node_modules/.bin/js-yaml @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@" +else + exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@" +fi diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha deleted file mode 120000 index 43c668d..0000000 --- a/node_modules/.bin/mocha +++ /dev/null @@ -1 +0,0 @@ -../mocha/bin/mocha \ No newline at end of file diff --git a/node_modules/.bin/mocha b/node_modules/.bin/mocha new file mode 100644 index 0000000..89dd21b --- /dev/null +++ b/node_modules/.bin/mocha @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../mocha/bin/mocha.js" "$@" +else + exec node "$basedir/../mocha/bin/mocha.js" "$@" +fi diff --git a/node_modules/.bin/mocha.cmd b/node_modules/.bin/mocha.cmd index 53ac420..b328ae9 100644 --- a/node_modules/.bin/mocha.cmd +++ b/node_modules/.bin/mocha.cmd @@ -14,4 +14,4 @@ IF EXIST "%dp0%\node.exe" ( SET PATHEXT=%PATHEXT:;.JS;=;% ) -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mocha\bin\mocha" %* +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mocha\bin\mocha.js" %* diff --git a/node_modules/.bin/mocha.ps1 b/node_modules/.bin/mocha.ps1 index 84ef044..5f83501 100644 --- a/node_modules/.bin/mocha.ps1 +++ b/node_modules/.bin/mocha.ps1 @@ -11,17 +11,17 @@ $ret=0 if (Test-Path "$basedir/node$exe") { # Support pipeline input if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../mocha/bin/mocha" $args + $input | & "$basedir/node$exe" "$basedir/../mocha/bin/mocha.js" $args } else { - & "$basedir/node$exe" "$basedir/../mocha/bin/mocha" $args + & "$basedir/node$exe" "$basedir/../mocha/bin/mocha.js" $args } $ret=$LASTEXITCODE } else { # Support pipeline input if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../mocha/bin/mocha" $args + $input | & "node$exe" "$basedir/../mocha/bin/mocha.js" $args } else { - & "node$exe" "$basedir/../mocha/bin/mocha" $args + & "node$exe" "$basedir/../mocha/bin/mocha.js" $args } $ret=$LASTEXITCODE } diff --git a/node_modules/.bin/nanoid b/node_modules/.bin/nanoid deleted file mode 120000 index e2be547..0000000 --- a/node_modules/.bin/nanoid +++ /dev/null @@ -1 +0,0 @@ -../nanoid/bin/nanoid.cjs \ No newline at end of file diff --git a/node_modules/.bin/nanoid.cmd b/node_modules/.bin/nanoid.cmd deleted file mode 100644 index 9c40107..0000000 --- a/node_modules/.bin/nanoid.cmd +++ /dev/null @@ -1,17 +0,0 @@ -@ECHO off -GOTO start -:find_dp0 -SET dp0=%~dp0 -EXIT /b -:start -SETLOCAL -CALL :find_dp0 - -IF EXIST "%dp0%\node.exe" ( - SET "_prog=%dp0%\node.exe" -) ELSE ( - SET "_prog=node" - SET PATHEXT=%PATHEXT:;.JS;=;% -) - -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\nanoid\bin\nanoid.cjs" %* diff --git a/node_modules/.bin/nanoid.ps1 b/node_modules/.bin/nanoid.ps1 deleted file mode 100644 index d8a4d7a..0000000 --- a/node_modules/.bin/nanoid.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" -} -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } else { - & "$basedir/node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } else { - & "node$exe" "$basedir/../nanoid/bin/nanoid.cjs" $args - } - $ret=$LASTEXITCODE -} -exit $ret diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which deleted file mode 120000 index 6f8415e..0000000 --- a/node_modules/.bin/node-which +++ /dev/null @@ -1 +0,0 @@ -../which/bin/node-which \ No newline at end of file diff --git a/node_modules/.bin/node-which.cmd b/node_modules/.bin/node-which.cmd deleted file mode 100644 index 8738aed..0000000 --- a/node_modules/.bin/node-which.cmd +++ /dev/null @@ -1,17 +0,0 @@ -@ECHO off -GOTO start -:find_dp0 -SET dp0=%~dp0 -EXIT /b -:start -SETLOCAL -CALL :find_dp0 - -IF EXIST "%dp0%\node.exe" ( - SET "_prog=%dp0%\node.exe" -) ELSE ( - SET "_prog=node" - SET PATHEXT=%PATHEXT:;.JS;=;% -) - -endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %* diff --git a/node_modules/.bin/node-which.ps1 b/node_modules/.bin/node-which.ps1 deleted file mode 100644 index cfb09e8..0000000 --- a/node_modules/.bin/node-which.ps1 +++ /dev/null @@ -1,28 +0,0 @@ -#!/usr/bin/env pwsh -$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent - -$exe="" -if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { - # Fix case when both the Windows and Linux builds of Node - # are installed in the same directory - $exe=".exe" -} -$ret=0 -if (Test-Path "$basedir/node$exe") { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args - } else { - & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args - } - $ret=$LASTEXITCODE -} else { - # Support pipeline input - if ($MyInvocation.ExpectingInput) { - $input | & "node$exe" "$basedir/../which/bin/node-which" $args - } else { - & "node$exe" "$basedir/../which/bin/node-which" $args - } - $ret=$LASTEXITCODE -} -exit $ret diff --git a/node_modules/.bin/webpagetest b/node_modules/.bin/webpagetest deleted file mode 120000 index bfddec4..0000000 --- a/node_modules/.bin/webpagetest +++ /dev/null @@ -1 +0,0 @@ -../webpagetest/bin/webpagetest \ No newline at end of file diff --git a/node_modules/.bin/webpagetest b/node_modules/.bin/webpagetest new file mode 100644 index 0000000..9d316bd --- /dev/null +++ b/node_modules/.bin/webpagetest @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../webpagetest/bin/webpagetest" "$@" +else + exec node "$basedir/../webpagetest/bin/webpagetest" "$@" +fi diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index fec359e..a4ab6ef 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,22 +1,22 @@ { "name": "webpagetest-github-action", "version": "1.0.0", - "lockfileVersion": 2, + "lockfileVersion": 3, "requires": true, "packages": { "node_modules/@actions/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.9.1.tgz", - "integrity": "sha512-5ad+U2YGrmmiw6du20AQW5XuWo7UKN2052FjSV7MX+Wfjf8sCqcsZe62NfgHys4QI4/Y+vQvLKYL8jWtA1ZBTA==", + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.10.1.tgz", + "integrity": "sha512-3lBR9EDAY+iYIpTnTIXmWcNbX3T2kCkAEQGIQx4NVQ0575nk2k3GRZDTPQG+vVtS2izSLmINlxXf0uLtnrTP+g==", "dependencies": { "@actions/http-client": "^2.0.1", "uuid": "^8.3.2" } }, "node_modules/@actions/github": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/@actions/github/-/github-5.0.3.tgz", - "integrity": "sha512-myjA/pdLQfhUGLtRZC/J4L1RXOG4o6aYdiEq+zr5wVVKljzbFld+xv10k1FX6IkIJtNxbAq44BdwSNpQ015P0A==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/@actions/github/-/github-5.1.1.tgz", + "integrity": "sha512-Nk59rMDoJaV+mHCOJPXuvB1zIbomlKS0dmSIqPGxd0enAXBnOfn4VWF+CGtRCwXZG9Epa54tZA7VIRlJDS8A6g==", "dependencies": { "@actions/http-client": "^2.0.1", "@octokit/core": "^3.6.0", @@ -25,11 +25,20 @@ } }, "node_modules/@actions/http-client": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.0.1.tgz", - "integrity": "sha512-PIXiMVtz6VvyaRsGY268qvj57hXQEpsYogYOu2nrQhlf+XCGmZstmuZBbAybUl1nQGnvS1k1eEsQ69ZoD7xlSw==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@actions/http-client/-/http-client-2.2.1.tgz", + "integrity": "sha512-KhC/cZsq7f8I4LfZSJKgCvEwfkE8o1538VoBeoGzokVLLnbFDEAdFD3UhoMklxo2un9NJVBdANOresx7vTHlHw==", "dependencies": { - "tunnel": "^0.0.6" + "tunnel": "^0.0.6", + "undici": "^5.25.4" + } + }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", + "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", + "engines": { + "node": ">=14" } }, "node_modules/@octokit/auth-token": { @@ -133,11 +142,6 @@ "@octokit/openapi-types": "^12.11.0" } }, - "node_modules/@ungap/promise-all-settled": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@ungap/promise-all-settled/-/promise-all-settled-1.1.2.tgz", - "integrity": "sha512-sL/cEvJWAnClXw0wHk85/2L0G6Sj8UB0Ctc1TEMbKSsmpRosqhwj9gWgFRZSrBr2f9tiXISwNhCPmlfqUqyb9Q==" - }, "node_modules/ansi-colors": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", @@ -147,11 +151,11 @@ } }, "node_modules/ansi-regex": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-3.0.1.tgz", - "integrity": "sha512-+O9Jct8wf++lXxxFc4hc8LsjaSq0HFzzL7cVsw8pRDIPdjKD2mT4ytDZlLuSBZ4cLKZFXIrMGO7DbQCtMJJMKw==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/ansi-styles": { @@ -169,9 +173,9 @@ } }, "node_modules/anymatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.2.tgz", - "integrity": "sha512-P43ePfOAIupkguHUycrc4qJ9kz8ZiuOUijaETwX7THt0Y/GNK7v0aa8rY816xWjZ7rJdA5XdMcpVFTKMq+RvWg==", + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", "dependencies": { "normalize-path": "^3.0.0", "picomatch": "^2.0.4" @@ -186,9 +190,9 @@ "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, "node_modules/async": { - "version": "3.2.4", - "resolved": "https://registry.npmjs.org/async/-/async-3.2.4.tgz", - "integrity": "sha512-iAB+JbDEGXhyIUavoDl9WP/Jj106Kz9DEn1DPgYw5ruDn0e3Wgi3sKFm55sASdGBNOQB8F59d9qQ7deqrHA8wQ==" + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.5.tgz", + "integrity": "sha512-baNZyqaaLhyLVKm/DlvdW051MSgO6b8eVfIezl9E5PqWxFgzLm/wQntEW4zOytVburDEr0JlALEpdOFwvErLsg==" }, "node_modules/balanced-match": { "version": "1.0.2", @@ -196,16 +200,19 @@ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, "node_modules/before-after-hook": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.2.tgz", - "integrity": "sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==" + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz", + "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==" }, "node_modules/binary-extensions": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", - "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", "engines": { "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/brace-expansion": { @@ -260,23 +267,29 @@ } }, "node_modules/chokidar": { - "version": "3.5.1", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.1.tgz", - "integrity": "sha512-9+s+Od+W0VJJzawDma/gvBNQqkTiqYTWLuZoyAsivsI4AaWTCzHG06/TMjsf1cYe9Cb97UCEhjz7HvnPk2p/tw==", + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], "dependencies": { - "anymatch": "~3.1.1", + "anymatch": "~3.1.2", "braces": "~3.0.2", - "glob-parent": "~5.1.0", + "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", - "readdirp": "~3.5.0" + "readdirp": "~3.6.0" }, "engines": { "node": ">= 8.10.0" }, "optionalDependencies": { - "fsevents": "~2.3.1" + "fsevents": "~2.3.2" } }, "node_modules/cliui": { @@ -289,46 +302,6 @@ "wrap-ansi": "^7.0.0" } }, - "node_modules/cliui/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/cliui/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -359,38 +332,38 @@ "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" }, "node_modules/csv": { - "version": "5.5.3", - "resolved": "https://registry.npmjs.org/csv/-/csv-5.5.3.tgz", - "integrity": "sha512-QTaY0XjjhTQOdguARF0lGKm5/mEq9PD9/VhZZegHDIBq2tQwgNpHc3dneD4mGo2iJs+fTKv5Bp0fZ+BRuY3Z0g==", + "version": "6.3.8", + "resolved": "https://registry.npmjs.org/csv/-/csv-6.3.8.tgz", + "integrity": "sha512-gRh3yiT9bHBA5ka2yOpyFqAVu/ZpwWzajMUR/es0ljevAE88WyHBuMUy7jzd2o5j6LYQesEO/AyhbQ9BhbDXUA==", "dependencies": { - "csv-generate": "^3.4.3", - "csv-parse": "^4.16.3", - "csv-stringify": "^5.6.5", - "stream-transform": "^2.1.3" + "csv-generate": "^4.4.0", + "csv-parse": "^5.5.5", + "csv-stringify": "^6.4.6", + "stream-transform": "^3.3.1" }, "engines": { "node": ">= 0.1.90" } }, "node_modules/csv-generate": { - "version": "3.4.3", - "resolved": "https://registry.npmjs.org/csv-generate/-/csv-generate-3.4.3.tgz", - "integrity": "sha512-w/T+rqR0vwvHqWs/1ZyMDWtHHSJaN06klRqJXBEpDJaM/+dZkso0OKh1VcuuYvK3XM53KysVNq8Ko/epCK8wOw==" + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/csv-generate/-/csv-generate-4.4.0.tgz", + "integrity": "sha512-geM01acNPZ0wr4/9sKev5fCzFG/tsc/NbuFWrhLc47M1zQyUdEJH65+cxTLIVafEwhBjIYwQ7fdOL9roBqVltQ==" }, "node_modules/csv-parse": { - "version": "4.16.3", - "resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-4.16.3.tgz", - "integrity": "sha512-cO1I/zmz4w2dcKHVvpCr7JVRu8/FymG5OEpmvsZYlccYolPBLoVGKUHgNoc4ZGkFeFlWGEDmMyBM+TTqRdW/wg==" + "version": "5.5.5", + "resolved": "https://registry.npmjs.org/csv-parse/-/csv-parse-5.5.5.tgz", + "integrity": "sha512-erCk7tyU3yLWAhk6wvKxnyPtftuy/6Ak622gOO7BCJ05+TYffnPCJF905wmOQm+BpkX54OdAl8pveJwUdpnCXQ==" }, "node_modules/csv-stringify": { - "version": "5.6.5", - "resolved": "https://registry.npmjs.org/csv-stringify/-/csv-stringify-5.6.5.tgz", - "integrity": "sha512-PjiQ659aQ+fUTQqSrd1XEDnOr52jh30RBurfzkscaE2tPaFsDH5wOAHJiw8XAHphRknCwMUE9KRayc4K/NbO8A==" + "version": "6.4.6", + "resolved": "https://registry.npmjs.org/csv-stringify/-/csv-stringify-6.4.6.tgz", + "integrity": "sha512-h2V2XZ3uOTLilF5dPIptgUfN/o2ia/80Ie0Lly18LAnw5s8Eb7kt8rfxSUy24AztJZas9f6DPZpVlzDUtFt/ag==" }, "node_modules/debug": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.1.tgz", - "integrity": "sha512-doEwdvm4PCeK4K3RQN2ZC2BYUBaxwLARCqZmMjtF8a51J2Rb0xpVloFRnCODwqjpwnAoao4pelN8l3RJdv3gRQ==", + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", "dependencies": { "ms": "2.1.2" }, @@ -433,9 +406,9 @@ } }, "node_modules/ejs": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.8.tgz", - "integrity": "sha512-/sXZeMlhS0ArkfX2Aw780gJzXSMPnKjtspYZv+f3NiKLlubezAHDU5+9xz6gd3/NhG3txQCo6xlglmTS+oTGEQ==", + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", "dependencies": { "jake": "^10.8.5" }, @@ -452,17 +425,20 @@ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" }, "node_modules/entities": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz", - "integrity": "sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A==", + "version": "4.5.0", + "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", + "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", + "engines": { + "node": ">=0.12" + }, "funding": { "url": "https://github.com/fb55/entities?sponsor=1" } }, "node_modules/escalade": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", - "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", "engines": { "node": ">=6" } @@ -495,9 +471,9 @@ } }, "node_modules/filelist/node_modules/minimatch": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz", - "integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==", + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", "dependencies": { "brace-expansion": "^2.0.1" }, @@ -544,19 +520,6 @@ "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" }, - "node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "hasInstallScript": true, - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -566,19 +529,18 @@ } }, "node_modules/glob": { - "version": "7.1.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.6.tgz", - "integrity": "sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-8.1.0.tgz", + "integrity": "sha512-r8hpEjiQEYlF2QU0df3dS+nxxSIreXQS1qRhMJM0Q5NDdR386C7jb7Hwwod8Fgiuex+k0GFjgft18yvxm5XoCQ==", "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "minimatch": "^5.0.1", + "once": "^1.3.0" }, "engines": { - "node": "*" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -595,12 +557,23 @@ "node": ">= 6" } }, - "node_modules/growl": { - "version": "1.10.5", - "resolved": "https://registry.npmjs.org/growl/-/growl-1.10.5.tgz", - "integrity": "sha512-qBr4OuELkhPenW6goKVXiv47US3clb3/IbuWF9KNKEijAy9oeHxU9IgzjvJhHkUzhaj7rOUD7+YGWqUjLp5oSA==", + "node_modules/glob/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/glob/node_modules/minimatch": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", + "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, "engines": { - "node": ">=4.x" + "node": ">=10" } }, "node_modules/has-flag": { @@ -653,11 +626,11 @@ } }, "node_modules/is-fullwidth-code-point": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz", - "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/is-glob": { @@ -695,20 +668,26 @@ "node": ">=0.10.0" } }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } }, "node_modules/jake": { - "version": "10.8.5", - "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.5.tgz", - "integrity": "sha512-sVpxYeuAhWt0OTWITwT98oyV0GsXyMlXCF+3L1SuafBVUIr/uILGRB+NqwkzhgXKvoJpDIpQvqkUALgdmQsQxw==", + "version": "10.8.7", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.8.7.tgz", + "integrity": "sha512-ZDi3aP+fG/LchyBzUM804VjddnwfSfsdeYkwt8NcbKRvo4rFkjhs456iLFn3k2ZUWvNe4i48WACDbza8fhq2+w==", "dependencies": { "async": "^3.2.3", "chalk": "^4.0.2", - "filelist": "^1.0.1", - "minimatch": "^3.0.4" + "filelist": "^1.0.4", + "minimatch": "^3.1.2" }, "bin": { "jake": "bin/cli.js" @@ -718,9 +697,9 @@ } }, "node_modules/js-yaml": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.0.0.tgz", - "integrity": "sha512-pqon0s+4ScYUvX30wxQi3PogGFAlUyH0awepWvwkj4jD4v+ova3RiYw8bmA6x2rDrEaj8i/oWKoRxpVNW+Re8Q==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", "dependencies": { "argparse": "^2.0.1" }, @@ -743,14 +722,18 @@ } }, "node_modules/log-symbols": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.0.0.tgz", - "integrity": "sha512-FN8JBzLx6CzeMrB0tg6pqlGU1wCrXW+ZXGH481kfsBqer0hToTIiHdjH4Mq8xJUbvATujKCvaREGWpGUionraA==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", "dependencies": { - "chalk": "^4.0.0" + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" }, "engines": { "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/minimatch": { @@ -764,66 +747,57 @@ "node": "*" } }, - "node_modules/mixme": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/mixme/-/mixme-0.5.4.tgz", - "integrity": "sha512-3KYa4m4Vlqx98GPdOHghxSdNtTvcP8E0kkaJ5Dlh+h2DRzF7zpuVVcA8B0QpKd11YJeP9QQ7ASkKzOeu195Wzw==", - "engines": { - "node": ">= 8.0.0" - } - }, "node_modules/mocha": { - "version": "8.4.0", - "resolved": "https://registry.npmjs.org/mocha/-/mocha-8.4.0.tgz", - "integrity": "sha512-hJaO0mwDXmZS4ghXsvPVriOhsxQ7ofcpQdm8dE+jISUOKopitvnXFQmpRR7jd2K6VBG6E26gU3IAbXXGIbu4sQ==", + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.4.0.tgz", + "integrity": "sha512-eqhGB8JKapEYcC4ytX/xrzKforgEc3j1pGlAXVy3eRwrtAy5/nIfT1SvgGzfN0XZZxeLq0aQWkOUAmqIJiv+bA==", "dependencies": { - "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "chokidar": "3.5.1", - "debug": "4.3.1", + "chokidar": "3.5.3", + "debug": "4.3.4", "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", - "glob": "7.1.6", - "growl": "1.10.5", + "glob": "8.1.0", "he": "1.2.0", - "js-yaml": "4.0.0", - "log-symbols": "4.0.0", - "minimatch": "3.0.4", + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "5.0.1", "ms": "2.1.3", - "nanoid": "3.1.20", - "serialize-javascript": "5.0.1", + "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", - "which": "2.0.2", - "wide-align": "1.1.3", - "workerpool": "6.1.0", + "workerpool": "6.2.1", "yargs": "16.2.0", "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" }, "bin": { "_mocha": "bin/_mocha", - "mocha": "bin/mocha" + "mocha": "bin/mocha.js" }, "engines": { - "node": ">= 10.12.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mochajs" + "node": ">= 14.0.0" + } + }, + "node_modules/mocha/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" } }, "node_modules/mocha/node_modules/minimatch": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", - "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^2.0.1" }, "engines": { - "node": "*" + "node": ">=10" } }, "node_modules/mocha/node_modules/supports-color": { @@ -845,21 +819,10 @@ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, - "node_modules/nanoid": { - "version": "3.1.20", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.20.tgz", - "integrity": "sha512-a1cQNyczgKbLX9jwbS/+d7W8fX/RfgYR7lVWwWOGIPNgK2m0MWvrGF6/m4kk6U3QcFMnZf3RIhL0v2Jgh/0Uxw==", - "bin": { - "nanoid": "bin/nanoid.cjs" - }, - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - } - }, "node_modules/node-fetch": { - "version": "2.6.7", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", - "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", + "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", "dependencies": { "whatwg-url": "^5.0.0" }, @@ -927,14 +890,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/picomatch": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", @@ -955,9 +910,9 @@ } }, "node_modules/readdirp": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.5.0.tgz", - "integrity": "sha512-cMhu7c/8rdhkHXWsY+osBhfSy0JikwpHK/5+imo+LpeasTF8ouErHrlYkwT0++njiyuDvc7OFY5T3ukvZ8qmFQ==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", "dependencies": { "picomatch": "^2.2.1" }, @@ -993,47 +948,45 @@ ] }, "node_modules/sax": { - "version": "1.2.4", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.3.0.tgz", + "integrity": "sha512-0s+oAmw9zLl1V1cS9BtZN7JAd0cW5e0QH4W3LWEK6a4LaLEA2OTpGYWDY+6XasBLtz6wkm3u1xRw95mRuJ59WA==" }, "node_modules/serialize-javascript": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-5.0.1.tgz", - "integrity": "sha512-SaaNal9imEO737H2c05Og0/8LUXG7EnsZyMa8MzkmuHoELfT6txuj0cMqRj6zfPKnmQ1yasR4PCJc8x+M4JSPA==", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", "dependencies": { "randombytes": "^2.1.0" } }, "node_modules/stream-transform": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/stream-transform/-/stream-transform-2.1.3.tgz", - "integrity": "sha512-9GHUiM5hMiCi6Y03jD2ARC1ettBXkQBoQAe7nJsPknnI0ow10aXjTnew8QtYQmLjzn974BnmWEAJgCY6ZP1DeQ==", - "dependencies": { - "mixme": "^0.5.1" - } + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/stream-transform/-/stream-transform-3.3.1.tgz", + "integrity": "sha512-BL8pv9QL8Ikd11oZwlRDp1qYMhGR0i50zI9ltoijKGc4ubQWal/Rc4p6SYJp1TBOGpE0uAGchwbxOZ1ycwTuqQ==" }, "node_modules/string-width": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz", - "integrity": "sha512-nOqH59deCq9SRHlxq1Aw85Jnt4w6KvLKqWVik6oA9ZklXLNIOlqg4F2yrT1MVaTjAqvVwdfeZ7w7aCvJD7ugkw==", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", "dependencies": { - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^4.0.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/strip-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-4.0.0.tgz", - "integrity": "sha512-4XaJ2zQdCzROZDivEVIDPkcQn8LMFSa8kj8Gxb/Lnwzv9A8VctNZ+lfivC/sV3ivW8ElJTERXZoPBRrZKkNKow==", + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", "dependencies": { - "ansi-regex": "^3.0.0" + "ansi-regex": "^5.0.1" }, "engines": { - "node": ">=4" + "node": ">=8" } }, "node_modules/strip-json-comments": { @@ -1082,10 +1035,21 @@ "node": ">=0.6.11 <=0.7.0 || >=0.7.3" } }, + "node_modules/undici": { + "version": "5.28.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.28.4.tgz", + "integrity": "sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, "node_modules/universal-user-agent": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.0.tgz", - "integrity": "sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==" + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/universal-user-agent/-/universal-user-agent-6.0.1.tgz", + "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==" }, "node_modules/uuid": { "version": "8.3.2", @@ -1101,15 +1065,15 @@ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" }, "node_modules/webpagetest": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/webpagetest/-/webpagetest-0.6.0.tgz", - "integrity": "sha512-c1aLcSFVWJ1PwifqB5rrXgtkRPNFZiReMo4YFI+qk4ZwHHItjkCFpZJsMq6G6OYhTFetTwvq9JUK0OCkYzyKFA==", + "version": "0.7.4", + "resolved": "https://registry.npmjs.org/webpagetest/-/webpagetest-0.7.4.tgz", + "integrity": "sha512-6267WoRwkgx55gI0h3+O5E6KegqsQHjhpvlZULSK/RRpL6K/kXaG26dy33OEsm1NHh81rxYsqAcJmRI0DcXZlA==", "dependencies": { "commander": "^5.1.0", - "csv": "^5.3.2", - "entities": "^2.0.3", - "mocha": "^8.0.1", - "xml2js": "^0.4.23" + "csv": "^6.2.2", + "entities": "^4.4.0", + "mocha": "^10.1.0", + "xml2js": "^0.6.2" }, "bin": { "webpagetest": "bin/webpagetest" @@ -1127,32 +1091,10 @@ "webidl-conversions": "^3.0.0" } }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wide-align": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.3.tgz", - "integrity": "sha512-QGkOQc8XL6Bt5PwnsExKBPuMKBxnGxWWW3fU55Xt4feHozMUhdUMaBCk290qpm/wG5u/RSKzwdAC4i51YigihA==", - "dependencies": { - "string-width": "^1.0.2 || 2" - } - }, "node_modules/workerpool": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.1.0.tgz", - "integrity": "sha512-toV7q9rWNYha963Pl/qyeZ6wG+3nnsyvolaNUS8+R5Wtw6qJPTxIlOP1ZSvcGhEJw+l3HMMmtiNo9Gl61G4GVg==" + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz", + "integrity": "sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==" }, "node_modules/wrap-ansi": { "version": "7.0.0", @@ -1170,55 +1112,15 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wrap-ansi/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/wrappy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" }, "node_modules/xml2js": { - "version": "0.4.23", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.23.tgz", - "integrity": "sha512-ySPiMjM0+pLDftHgXY4By0uswI3SPKLDw/i3UXbnO8M/p28zqexCUoPmQFrYD+/1BzhGJSs2i1ERWKJAtiLrug==", + "version": "0.6.2", + "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz", + "integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==", "dependencies": { "sax": ">=0.6.0", "xmlbuilder": "~11.0.0" @@ -1282,46 +1184,6 @@ "node": ">=10" } }, - "node_modules/yargs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/yargs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/yocto-queue": { "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", diff --git a/node_modules/@actions/core/README.md b/node_modules/@actions/core/README.md index 3c20c8e..8a47143 100644 --- a/node_modules/@actions/core/README.md +++ b/node_modules/@actions/core/README.md @@ -121,7 +121,7 @@ const result = await core.group('Do something async', async () => { This library has 3 methods that will produce [annotations](https://docs.github.com/en/rest/reference/checks#create-a-check-run). ```js -core.error('This is a bad error. This will also fail the build.') +core.error('This is a bad error, action may still succeed though.') core.warning('Something went wrong, but it\'s not bad enough to fail the build.') @@ -163,7 +163,7 @@ export interface AnnotationProperties { startColumn?: number /** - * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * The end column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. * Defaults to `startColumn` when `startColumn` is provided. */ endColumn?: number diff --git a/node_modules/@actions/core/lib/core.d.ts b/node_modules/@actions/core/lib/core.d.ts index 1defb57..ceecdd3 100644 --- a/node_modules/@actions/core/lib/core.d.ts +++ b/node_modules/@actions/core/lib/core.d.ts @@ -21,7 +21,7 @@ export declare enum ExitCode { Failure = 1 } /** - * Optional properties that can be sent with annotatation commands (notice, error, and warning) + * Optional properties that can be sent with annotation commands (notice, error, and warning) * See: https://docs.github.com/en/rest/reference/checks#create-a-check-run for more information about annotations. */ export interface AnnotationProperties { @@ -46,7 +46,7 @@ export interface AnnotationProperties { */ startColumn?: number; /** - * The start column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. + * The end column for the annotation. Cannot be sent when `startLine` and `endLine` are different values. * Defaults to `startColumn` when `startColumn` is provided. */ endColumn?: number; diff --git a/node_modules/@actions/core/lib/core.js b/node_modules/@actions/core/lib/core.js index 1566289..48df6ad 100644 --- a/node_modules/@actions/core/lib/core.js +++ b/node_modules/@actions/core/lib/core.js @@ -34,7 +34,6 @@ const file_command_1 = require("./file-command"); const utils_1 = require("./utils"); const os = __importStar(require("os")); const path = __importStar(require("path")); -const uuid_1 = require("uuid"); const oidc_utils_1 = require("./oidc-utils"); /** * The code to exit an action @@ -64,20 +63,9 @@ function exportVariable(name, val) { process.env[name] = convertedVal; const filePath = process.env['GITHUB_ENV'] || ''; if (filePath) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - // These should realistically never happen, but just in case someone finds a way to exploit uuid generation let's not allow keys or values that contain the delimiter. - if (name.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedVal.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - const commandValue = `${name}<<${delimiter}${os.EOL}${convertedVal}${os.EOL}${delimiter}`; - file_command_1.issueCommand('ENV', commandValue); - } - else { - command_1.issueCommand('set-env', { name }, convertedVal); + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); } + command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** @@ -95,7 +83,7 @@ exports.setSecret = setSecret; function addPath(inputPath) { const filePath = process.env['GITHUB_PATH'] || ''; if (filePath) { - file_command_1.issueCommand('PATH', inputPath); + file_command_1.issueFileCommand('PATH', inputPath); } else { command_1.issueCommand('add-path', {}, inputPath); @@ -135,7 +123,10 @@ function getMultilineInput(name, options) { const inputs = getInput(name, options) .split('\n') .filter(x => x !== ''); - return inputs; + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); } exports.getMultilineInput = getMultilineInput; /** @@ -168,8 +159,12 @@ exports.getBooleanInput = getBooleanInput; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, value); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); } exports.setOutput = setOutput; /** @@ -298,7 +293,11 @@ exports.group = group; */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { - command_1.issueCommand('save-state', { name }, value); + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); + } + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); } exports.saveState = saveState; /** diff --git a/node_modules/@actions/core/lib/core.js.map b/node_modules/@actions/core/lib/core.js.map index 9abe68f..99f7fd8 100644 --- a/node_modules/@actions/core/lib/core.js.map +++ b/node_modules/@actions/core/lib/core.js.map @@ -1 +1 @@ -{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAA6C;AAC7C,iDAA+D;AAC/D,mCAA2D;AAE3D,uCAAwB;AACxB,2CAA4B;AAC5B,+BAAiC;AAEjC,6CAAuC;AAavC;;GAEG;AACH,IAAY,QAUX;AAVD,WAAY,QAAQ;IAClB;;OAEG;IACH,6CAAW,CAAA;IAEX;;OAEG;IACH,6CAAW,CAAA;AACb,CAAC,EAVW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAUnB;AAuCD,yEAAyE;AACzE,YAAY;AACZ,yEAAyE;AAEzE;;;;GAIG;AACH,8DAA8D;AAC9D,SAAgB,cAAc,CAAC,IAAY,EAAE,GAAQ;IACnD,MAAM,YAAY,GAAG,sBAAc,CAAC,GAAG,CAAC,CAAA;IACxC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,YAAY,CAAA;IAEhC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,EAAE,CAAA;IAChD,IAAI,QAAQ,EAAE;QACZ,MAAM,SAAS,GAAG,gBAAgB,SAAM,EAAE,EAAE,CAAA;QAE5C,sKAAsK;QACtK,IAAI,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CACb,4DAA4D,SAAS,GAAG,CACzE,CAAA;SACF;QAED,IAAI,YAAY,CAAC,QAAQ,CAAC,SAAS,CAAC,EAAE;YACpC,MAAM,IAAI,KAAK,CACb,6DAA6D,SAAS,GAAG,CAC1E,CAAA;SACF;QAED,MAAM,YAAY,GAAG,GAAG,IAAI,KAAK,SAAS,GAAG,EAAE,CAAC,GAAG,GAAG,YAAY,GAAG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;QACzF,2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BAEC;AAED,SAAsB,UAAU,CAAC,GAAY;;QAC3C,OAAO,MAAM,uBAAU,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;IACzC,CAAC;CAAA;AAFD,gCAEC;AAED;;GAEG;AACH,qCAAiC;AAAzB,kGAAA,OAAO,OAAA;AAEf;;GAEG;AACH,qCAAyC;AAAjC,0GAAA,eAAe,OAAA;AAEvB;;GAEG;AACH,2CAAqE;AAA7D,yGAAA,WAAW,OAAA;AAAE,yGAAA,WAAW,OAAA;AAAE,4GAAA,cAAc,OAAA"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/file-command.d.ts b/node_modules/@actions/core/lib/file-command.d.ts index ed408eb..2d1f2f4 100644 --- a/node_modules/@actions/core/lib/file-command.d.ts +++ b/node_modules/@actions/core/lib/file-command.d.ts @@ -1 +1,2 @@ -export declare function issueCommand(command: string, message: any): void; +export declare function issueFileCommand(command: string, message: any): void; +export declare function prepareKeyValueMessage(key: string, value: any): string; diff --git a/node_modules/@actions/core/lib/file-command.js b/node_modules/@actions/core/lib/file-command.js index 55e3e9f..2d0d738 100644 --- a/node_modules/@actions/core/lib/file-command.js +++ b/node_modules/@actions/core/lib/file-command.js @@ -20,13 +20,14 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.issueCommand = void 0; +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; // We use any as a valid input type /* eslint-disable @typescript-eslint/no-explicit-any */ const fs = __importStar(require("fs")); const os = __importStar(require("os")); +const uuid_1 = require("uuid"); const utils_1 = require("./utils"); -function issueCommand(command, message) { +function issueFileCommand(command, message) { const filePath = process.env[`GITHUB_${command}`]; if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); @@ -38,5 +39,20 @@ function issueCommand(command, message) { encoding: 'utf8' }); } -exports.issueCommand = issueCommand; +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; //# sourceMappingURL=file-command.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/file-command.js.map b/node_modules/@actions/core/lib/file-command.js.map index ee35699..b1a9d54 100644 --- a/node_modules/@actions/core/lib/file-command.js.map +++ b/node_modules/@actions/core/lib/file-command.js.map @@ -1 +1 @@ -{"version":3,"file":"file-command.js","sourceRoot":"","sources":["../src/file-command.ts"],"names":[],"mappings":";AAAA,uCAAuC;;;;;;;;;;;;;;;;;;;;;;AAEvC,mCAAmC;AACnC,uDAAuD;AAEvD,uCAAwB;AACxB,uCAAwB;AACxB,mCAAsC;AAEtC,SAAgB,YAAY,CAAC,OAAe,EAAE,OAAY;IACxD,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,OAAO,EAAE,CAAC,CAAA;IACjD,IAAI,CAAC,QAAQ,EAAE;QACb,MAAM,IAAI,KAAK,CACb,wDAAwD,OAAO,EAAE,CAClE,CAAA;KACF;IACD,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE;QAC5B,MAAM,IAAI,KAAK,CAAC,yBAAyB,QAAQ,EAAE,CAAC,CAAA;KACrD;IAED,EAAE,CAAC,cAAc,CAAC,QAAQ,EAAE,GAAG,sBAAc,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC,GAAG,EAAE,EAAE;QACjE,QAAQ,EAAE,MAAM;KACjB,CAAC,CAAA;AACJ,CAAC;AAdD,oCAcC"} \ No newline at end of file +{"version":3,"file":"file-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AG,EAAE,CAAC,GAAG,GAAG,SAAS,EAAE,CAAA;AAC9E,CAAC;AApBD,wDAoBC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/oidc-utils.js b/node_modules/@actions/core/lib/oidc-utils.js index f701277..092e93d 100644 --- a/node_modules/@actions/core/lib/oidc-utils.js +++ b/node_modules/@actions/core/lib/oidc-utils.js @@ -44,7 +44,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { diff --git a/node_modules/@actions/core/lib/oidc-utils.js.map b/node_modules/@actions/core/lib/oidc-utils.js.map index 284fa1d..22506b8 100644 --- a/node_modules/@actions/core/lib/oidc-utils.js.map +++ b/node_modules/@actions/core/lib/oidc-utils.js.map @@ -1 +1 @@ -{"version":3,"file":"oidc-utils.js","sourceRoot":"","sources":["../src/oidc-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;AAGA,sDAA+C;AAC/C,wDAAqE;AACrE,iCAAuC;AAKvC,MAAa,UAAU;IACb,MAAM,CAAC,gBAAgB,CAC7B,UAAU,GAAG,IAAI,EACjB,QAAQ,GAAG,EAAE;QAEb,MAAM,cAAc,GAAmB;YACrC,YAAY,EAAE,UAAU;YACxB,UAAU,EAAE,QAAQ;SACrB,CAAA;QAED,OAAO,IAAI,wBAAU,CACnB,qBAAqB,EACrB,CAAC,IAAI,8BAAuB,CAAC,UAAU,CAAC,eAAe,EAAE,CAAC,CAAC,EAC3D,cAAc,CACf,CAAA;IACH,CAAC;IAEO,MAAM,CAAC,eAAe;QAC5B,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAA;QAC3D,IAAI,CAAC,KAAK,EAAE;YACV,MAAM,IAAI,KAAK,CACb,2DAA2D,CAC5D,CAAA;SACF;QACD,OAAO,KAAK,CAAA;IACd,CAAC;IA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uBACa,KAAK,CAAC,UAAU;yBACd,KAAK,CAAC,OAAO,EAAE,CAC/B,CAAA;YACH,CAAC,CAAC,CAAA;YAEJ,MAAM,QAAQ,SAAG,GAAG,CAAC,MAAM,0CAAE,KAAK,CAAA;YAClC,IAAI,CAAC,QAAQ,EAAE;gBACb,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAA;aACjE;YACD,OAAO,QAAQ,CAAA;;KAChB;IAED,MAAM,CAAO,UAAU,CAAC,QAAiB;;YACvC,IAAI;gBACF,gDAAgD;gBAChD,IAAI,YAAY,GAAW,UAAU,CAAC,aAAa,EAAE,CAAA;gBACrD,IAAI,QAAQ,EAAE;oBACZ,MAAM,eAAe,GAAG,kBAAkB,CAAC,QAAQ,CAAC,CAAA;oBACpD,YAAY,GAAG,GAAG,YAAY,aAAa,eAAe,EAAE,CAAA;iBAC7D;gBAED,YAAK,CAAC,mBAAmB,YAAY,EAAE,CAAC,CAAA;gBAExC,MAAM,QAAQ,GAAG,MAAM,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,CAAA;gBACvD,gBAAS,CAAC,QAAQ,CAAC,CAAA;gBACnB,OAAO,QAAQ,CAAA;aAChB;YAAC,OAAO,KAAK,EAAE;gBACd,MAAM,IAAI,KAAK,CAAC,kBAAkB,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;aACnD;QACH,CAAC;KAAA;CACF;AAzED,gCAyEC"} \ No newline at end of file diff --git a/node_modules/@actions/core/package.json b/node_modules/@actions/core/package.json index 45341c3..1558268 100644 --- a/node_modules/@actions/core/package.json +++ b/node_modules/@actions/core/package.json @@ -1,6 +1,6 @@ { "name": "@actions/core", - "version": "1.9.1", + "version": "1.10.1", "description": "Actions core lib", "keywords": [ "github", @@ -30,7 +30,7 @@ "scripts": { "audit-moderate": "npm install && npm audit --json --audit-level=moderate > audit.json", "test": "echo \"Error: run tests from root\" && exit 1", - "tsc": "tsc" + "tsc": "tsc -p tsconfig.json" }, "bugs": { "url": "https://github.com/actions/toolkit/issues" @@ -43,4 +43,4 @@ "@types/node": "^12.0.2", "@types/uuid": "^8.3.4" } -} +} \ No newline at end of file diff --git a/node_modules/@actions/github/lib/github.d.ts b/node_modules/@actions/github/lib/github.d.ts index 90c3b98..8c2121d 100644 --- a/node_modules/@actions/github/lib/github.d.ts +++ b/node_modules/@actions/github/lib/github.d.ts @@ -1,6 +1,6 @@ import * as Context from './context'; import { GitHub } from './utils'; -import { OctokitOptions } from '@octokit/core/dist-types/types'; +import { OctokitOptions, OctokitPlugin } from '@octokit/core/dist-types/types'; export declare const context: Context.Context; /** * Returns a hydrated octokit ready to use for GitHub Actions @@ -8,4 +8,4 @@ export declare const context: Context.Context; * @param token the repo PAT or GITHUB_TOKEN * @param options other options to set */ -export declare function getOctokit(token: string, options?: OctokitOptions): InstanceType; +export declare function getOctokit(token: string, options?: OctokitOptions, ...additionalPlugins: OctokitPlugin[]): InstanceType; diff --git a/node_modules/@actions/github/lib/github.js b/node_modules/@actions/github/lib/github.js index f02c9fb..b717a6b 100644 --- a/node_modules/@actions/github/lib/github.js +++ b/node_modules/@actions/github/lib/github.js @@ -29,8 +29,9 @@ exports.context = new Context.Context(); * @param token the repo PAT or GITHUB_TOKEN * @param options other options to set */ -function getOctokit(token, options) { - return new utils_1.GitHub(utils_1.getOctokitOptions(token, options)); +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins(utils_1.getOctokitOptions(token, options)); } exports.getOctokit = getOctokit; //# sourceMappingURL=github.js.map \ No newline at end of file diff --git a/node_modules/@actions/github/lib/github.js.map b/node_modules/@actions/github/lib/github.js.map index 717d03e..60be74b 100644 --- a/node_modules/@actions/github/lib/github.js.map +++ b/node_modules/@actions/github/lib/github.js.map @@ -1 +1 @@ -{"version":3,"file":"github.js","sourceRoot":"","sources":["../src/github.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,mDAAoC;AACpC,mCAAiD;AAKpC,QAAA,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;AAE5C;;;;;GAKG;AACH,SAAgB,UAAU,CACxB,KAAa,EACb,OAAwB;IAExB,OAAO,IAAI,cAAM,CAAC,yBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;AACtD,CAAC;AALD,gCAKC"} \ No newline at end of file +{"version":3,"file":"github.js","sourceRoot":"","sources":["../src/github.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,mDAAoC;AACpC,mCAAiD;AAKpC,QAAA,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;AAE5C;;;;;GAKG;AACH,SAAgB,UAAU,CACxB,KAAa,EACb,OAAwB,EACxB,GAAG,iBAAkC;IAErC,MAAM,iBAAiB,GAAG,cAAM,CAAC,MAAM,CAAC,GAAG,iBAAiB,CAAC,CAAA;IAC7D,OAAO,IAAI,iBAAiB,CAAC,yBAAiB,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAA;AACjE,CAAC;AAPD,gCAOC"} \ No newline at end of file diff --git a/node_modules/@actions/github/lib/utils.d.ts b/node_modules/@actions/github/lib/utils.d.ts index fe28cbd..e889ee0 100644 --- a/node_modules/@actions/github/lib/utils.d.ts +++ b/node_modules/@actions/github/lib/utils.d.ts @@ -2,6 +2,7 @@ import * as Context from './context'; import { Octokit } from '@octokit/core'; import { OctokitOptions } from '@octokit/core/dist-types/types'; export declare const context: Context.Context; +export declare const defaults: OctokitOptions; export declare const GitHub: typeof Octokit & import("@octokit/core/dist-types/types").Constructor; diff --git a/node_modules/@actions/github/lib/utils.js b/node_modules/@actions/github/lib/utils.js index afb40e9..d803f01 100644 --- a/node_modules/@actions/github/lib/utils.js +++ b/node_modules/@actions/github/lib/utils.js @@ -19,7 +19,7 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOctokitOptions = exports.GitHub = exports.context = void 0; +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; const Context = __importStar(require("./context")); const Utils = __importStar(require("./internal/utils")); // octokit + plugins @@ -28,13 +28,13 @@ const plugin_rest_endpoint_methods_1 = require("@octokit/plugin-rest-endpoint-me const plugin_paginate_rest_1 = require("@octokit/plugin-paginate-rest"); exports.context = new Context.Context(); const baseUrl = Utils.getApiBaseUrl(); -const defaults = { +exports.defaults = { baseUrl, request: { agent: Utils.getProxyAgent(baseUrl) } }; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(defaults); +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); /** * Convience function to correctly format Octokit Options to pass into the constructor. * diff --git a/node_modules/@actions/github/lib/utils.js.map b/node_modules/@actions/github/lib/utils.js.map index 3a6f6b4..7221d06 100644 --- a/node_modules/@actions/github/lib/utils.js.map +++ b/node_modules/@actions/github/lib/utils.js.map @@ -1 +1 @@ -{"version":3,"file":"utils.js","sourceRoot":"","sources":["../src/utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,mDAAoC;AACpC,wDAAyC;AAEzC,oBAAoB;AACpB,wCAAqC;AAErC,wFAAyE;AACzE,wEAA0D;AAE7C,QAAA,OAAO,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,CAAA;AAE5C,MAAM,OAAO,GAAG,KAAK,CAAC,aAAa,EAAE,CAAA;AACrC,MAAM,QAAQ,GAAG;IACf,OAAO;IACP,OAAO,EAAE;QACP,KAAK,EAAE,KAAK,CAAC,aAAa,CAAC,OAAO,CAAC;KACpC;CACF,CAAA;AAEY,QAAA,MAAM,GAAG,cAAO,CAAC,MAAM,CAClC,kDAAmB,EACnB,mCAAY,CACb,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAA;AAEpB;;;;;GAKG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;IAED,OAAO,IAAI,CAAA;AACb,CAAC;AAbD,8CAaC"} \ No newline at end of file diff --git a/node_modules/@actions/github/package.json b/node_modules/@actions/github/package.json index 30da327..3bcbe30 100644 --- a/node_modules/@actions/github/package.json +++ b/node_modules/@actions/github/package.json @@ -1,6 +1,6 @@ { "name": "@actions/github", - "version": "5.0.3", + "version": "5.1.1", "description": "Actions github lib", "keywords": [ "github", diff --git a/node_modules/@actions/http-client/lib/auth.js.map b/node_modules/@actions/http-client/lib/auth.js.map index 7d3a18a..62cc16b 100644 --- a/node_modules/@actions/http-client/lib/auth.js.map +++ b/node_modules/@actions/http-client/lib/auth.js.map @@ -1 +1 @@ -{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":";;;;;;;;;;;;AAIA,MAAa,sBAAsB;IAIjC,YAAY,QAAgB,EAAE,QAAgB;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;QACxB,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAA;IAC1B,CAAC;IAED,cAAc,CAAC,OAA4B;QACzC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE;YACpB,MAAM,KAAK,CAAC,4BAA4B,CAAC,CAAA;SAC1C;QACD,OAAO,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,GAAG,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,QAAQ,EAAE,CACpC,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA1BD,wDA0BC;AAED,MAAa,uBAAuB;IAGlC,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAA;IACpB,CAAC;IAED,yCAAyC;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AAC,eAAe,CAAC,GAAG,SAAS,MAAM,CAAC,IAAI,CACrD,OAAO,IAAI,CAAC,KAAK,EAAE,CACpB,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAA;IACxB,CAAC;IAED,iCAAiC;IACjC,uBAAuB;QACrB,OAAO,KAAK,CAAA;IACd,CAAC;IAEK,oBAAoB;;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;QACpC,CAAC;KAAA;CACF;AA5BD,oFA4BC"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/index.d.ts b/node_modules/@actions/http-client/lib/index.d.ts index fe733d1..38db700 100644 --- a/node_modules/@actions/http-client/lib/index.d.ts +++ b/node_modules/@actions/http-client/lib/index.d.ts @@ -1,6 +1,9 @@ /// +/// +/// import * as http from 'http'; import * as ifm from './interfaces'; +import { ProxyAgent } from 'undici'; export declare enum HttpCodes { OK = 200, MultipleChoices = 300, @@ -51,6 +54,7 @@ export declare class HttpClientResponse { constructor(message: http.IncomingMessage); message: http.IncomingMessage; readBody(): Promise; + readBodyBuffer?(): Promise; } export declare function isHttps(requestUrl: string): boolean; export declare class HttpClient { @@ -66,6 +70,7 @@ export declare class HttpClient { private _maxRetries; private _agent; private _proxyAgent; + private _proxyAgentDispatcher; private _keepAlive; private _disposed; constructor(userAgent?: string, handlers?: ifm.RequestHandler[], requestOptions?: ifm.RequestOptions); @@ -114,10 +119,12 @@ export declare class HttpClient { * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com */ getAgent(serverUrl: string): http.Agent; + getAgentDispatcher(serverUrl: string): ProxyAgent | undefined; private _prepareRequest; private _mergeHeaders; private _getExistingOrDefaultHeader; private _getAgent; + private _getProxyAgentDispatcher; private _performExponentialBackoff; private _processResponse; } diff --git a/node_modules/@actions/http-client/lib/index.js b/node_modules/@actions/http-client/lib/index.js index a1b7d03..f627c6a 100644 --- a/node_modules/@actions/http-client/lib/index.js +++ b/node_modules/@actions/http-client/lib/index.js @@ -2,7 +2,11 @@ /* eslint-disable @typescript-eslint/no-explicit-any */ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; @@ -15,7 +19,7 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? ( var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; @@ -34,6 +38,7 @@ const http = __importStar(require("http")); const https = __importStar(require("https")); const pm = __importStar(require("./proxy")); const tunnel = __importStar(require("tunnel")); +const undici_1 = require("undici"); var HttpCodes; (function (HttpCodes) { HttpCodes[HttpCodes["OK"] = 200] = "OK"; @@ -63,16 +68,16 @@ var HttpCodes; HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes = exports.HttpCodes || (exports.HttpCodes = {})); +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); var Headers; (function (Headers) { Headers["Accept"] = "accept"; Headers["ContentType"] = "content-type"; -})(Headers = exports.Headers || (exports.Headers = {})); +})(Headers || (exports.Headers = Headers = {})); var MediaTypes; (function (MediaTypes) { MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes = exports.MediaTypes || (exports.MediaTypes = {})); +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); /** * Returns the proxy URL, depending upon the supplied url and proxy environment variables. * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com @@ -123,6 +128,19 @@ class HttpClientResponse { })); }); } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } } exports.HttpClientResponse = HttpClientResponse; function isHttps(requestUrl) { @@ -428,6 +446,15 @@ class HttpClient { const parsedUrl = new URL(serverUrl); return this._getAgent(parsedUrl); } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } _prepareRequest(method, requestUrl, headers) { const info = {}; info.parsedUrl = requestUrl; @@ -475,7 +502,7 @@ class HttpClient { if (this._keepAlive && useProxy) { agent = this._proxyAgent; } - if (this._keepAlive && !useProxy) { + if (!useProxy) { agent = this._agent; } // if agent is already assigned use that agent. @@ -507,16 +534,12 @@ class HttpClient { agent = tunnelAgent(agentOptions); this._proxyAgent = agent; } - // if reusing agent across request and tunneling agent isn't assigned create a new agent - if (this._keepAlive && !agent) { + // if tunneling agent isn't assigned create a new agent + if (!agent) { const options = { keepAlive: this._keepAlive, maxSockets }; agent = usingSsl ? new https.Agent(options) : new http.Agent(options); this._agent = agent; } - // if not using private agent and tunnel agent isn't setup then use global agent - if (!agent) { - agent = usingSsl ? https.globalAgent : http.globalAgent; - } if (usingSsl && this._ignoreSslError) { // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options @@ -527,6 +550,30 @@ class HttpClient { } return agent; } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } _performExponentialBackoff(retryNumber) { return __awaiter(this, void 0, void 0, function* () { retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); diff --git a/node_modules/@actions/http-client/lib/index.js.map b/node_modules/@actions/http-client/lib/index.js.map index ca8ea41..1fce6fc 100644 --- a/node_modules/@actions/http-client/lib/index.js.map +++ b/node_modules/@actions/http-client/lib/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvD,2CAA4B;AAC5B,6CAA8B;AAG9B,4CAA6B;AAC7B,+CAAgC;AAEhC,IAAY,SA4BX;AA5BD,WAAY,SAAS;IACnB,uCAAQ,CAAA;IACR,iEAAqB,CAAA;IACrB,mEAAsB,CAAA;IACtB,6DAAmB,CAAA;IACnB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,qEAAuB,CAAA;IACvB,qEAAuB,CAAA;IACvB,uDAAgB,CAAA;IAChB,2DAAkB,CAAA;IAClB,iE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AAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA"} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";AAAA,uDAAuD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEvD,2CAA4B;AAC5B,6CAA8B;AAG9B,4CAA6B;AAC7B,+CAAgC;AAChC,mCAAiC;AAEjC,IAAY,SA4BX;AA5BD,WAAY,SAAS;IACnB,uCAAQ,CAAA;IACR,iEAAqB,CAAA;IACrB,mEAAsB,CAAA;IACtB,6DAAmB,CAAA;IACnB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,mDAAc,CAAA;IACd,yDAAiB,CAAA;IACjB,qEAAuB,CAAA;IACvB,qEAAuB,CAAA;IACvB,uDAAgB,CAAA;IAChB,2DAAkB,CAAA;IAClB,iEAAqB,CAAA;IACrB,qDAAe,CAAA;IACf,mDAAc,CAAA;IACd,mEAAsB,CAAA;IACtB,6DAAmB,CAAA;IACnB,yFAAiC,CAAA;IACjC,+DAAoB,CAAA;IACpB,mDAAc,CAAA;IACd,2CAAU,CAAA;IACV,iEAAqB,CAAA;IACrB,yEAAyB,CAAA;IACzB,+DAAoB,CAAA;IACpB,uDAAgB,CAAA;IAChB,uEAAwB,CAAA;IACxB,+DAAoB,CAAA;AACtB,CAAC,EA5BW,SAAS,yBAAT,SAAS,QA4BpB;AAED,IAAY,OAGX;AAHD,WAAY,OAAO;IACjB,4BAAiB,CAAA;IACjB,uCAA4B,CAAA;AAC9B,CAAC,EAHW,OAAO,uBAAP,OAAO,QAGlB;AAED,IAAY,UAEX;AAFD,WAAY,UAAU;IACpB,kDAAoC,CAAA;AACtC,CAAC,EAFW,UAAU,0BAAV,UAAU,QAErB;AAED;;;GAGG;AACH,SAAgB,WAAW,CAAC,SAAiB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,QAAQ,CAAC,OAAO,GAAG,GAAG,CAAC,OAAO,CAAC,OAAO,CAAA;iBACvC;gBAAC,OAAO,GAAG,EAAE;oBACZ,iEAAiE;iBAClE;gBAED,yDAAyD;gBACzD,IAAI,UAAU,GAAG,GAAG,EAAE;oBACpB,IAAI,GAAW,CAAA;oBAEf,0DAA0D;oBAC1D,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,EAAE;wBACtB,GAAG,GAAG,GAAG,CAAC,OAAO,CAAA;qBAClB;yBAAM,IAAI,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE;wBAC1C,yEAAyE;wBACzE,GAAG,GAAG,QAAQ,CAAA;qBACf;yBAAM;wBACL,GAAG,GAAG,oBAAoB,UAAU,GAAG,CAAA;qBACxC;oBAED,MAAM,GAAG,GAAG,IAAI,eAAe,CAAC,GAAG,EAAE,UAAU,CAAC,CAAA;oBAChD,GAAG,CAAC,MAAM,GAAG,QAAQ,CAAC,MAAM,CAAA;oBAE5B,MAAM,CAAC,GAAG,CAAC,CAAA;iBACZ;qBAAM;oBACL,OAAO,CAAC,QAAQ,CAAC,CAAA;iBAClB;YACH,CAAC,CAAA,CAAC,CAAA;QACJ,CAAC;KAAA;CACF;AA3rBD,gCA2rBC;AAED,MAAM,aAAa,GAAG,CAAC,GAA2B,EAAO,EAAE,CACzD,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAM,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAA"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/interfaces.d.ts b/node_modules/@actions/http-client/lib/interfaces.d.ts index 54fd4a8..775ced9 100644 --- a/node_modules/@actions/http-client/lib/interfaces.d.ts +++ b/node_modules/@actions/http-client/lib/interfaces.d.ts @@ -1,4 +1,6 @@ /// +/// +/// import * as http from 'http'; import * as https from 'https'; import { HttpClientResponse } from './index'; diff --git a/node_modules/@actions/http-client/lib/proxy.js b/node_modules/@actions/http-client/lib/proxy.js index 528ffe4..d9c43ad 100644 --- a/node_modules/@actions/http-client/lib/proxy.js +++ b/node_modules/@actions/http-client/lib/proxy.js @@ -15,7 +15,13 @@ function getProxyUrl(reqUrl) { } })(); if (proxyVar) { - return new URL(proxyVar); + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } else { return undefined; @@ -26,6 +32,10 @@ function checkBypass(reqUrl) { if (!reqUrl.hostname) { return false; } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; if (!noProxy) { return false; @@ -51,11 +61,22 @@ function checkBypass(reqUrl) { .split(',') .map(x => x.trim().toUpperCase()) .filter(x => x)) { - if (upperReqHosts.some(x => x === upperNoProxyItem)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { return true; } } return false; } exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} //# sourceMappingURL=proxy.js.map \ No newline at end of file diff --git a/node_modules/@actions/http-client/lib/proxy.js.map b/node_modules/@actions/http-client/lib/proxy.js.map index 4440de9..585c17d 100644 --- a/node_modules/@actions/http-client/lib/proxy.js.map +++ b/node_modules/@actions/http-client/lib/proxy.js.map @@ -1 +1 @@ -{"version":3,"file":"proxy.js","sourceRoot":"","sources":["../src/proxy.ts"],"names":[],"mappings":";;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D;IAED,uCAAuC;IACvC,KAAK,MAAM,gBAAgB,IAAI,OAAO;SACnC,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;SAChC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE;QACjB,IACE,gBAAgB,KAAK,GAAG;YACxB,aAAa,CAAC,IAAI,CAChB,CAAC,CAAC,EAAE,CACF,CAAC,KAAK,gBAAgB;gBACtB,CAAC,CAAC,QAAQ,CAAC,IAAI,gBAAgB,EAAE,CAAC;gBAClC,CAAC,gBAAgB,CAAC,UAAU,CAAC,GAAG,CAAC;oBAC/B,CAAC,CAAC,QAAQ,CAAC,GAAG,gBAAgB,EAAE,CAAC,CAAC,CACvC,EACD;YACA,OAAO,IAAI,CAAA;SACZ;KACF;IAED,OAAO,KAAK,CAAA;AACd,CAAC;AAnDD,kCAmDC;AAED,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,SAAS,GAAG,IAAI,CAAC,WAAW,EAAE,CAAA;IACpC,OAAO,CACL,SAAS,KAAK,WAAW;QACzB,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC;QAC5B,SAAS,CAAC,UAAU,CAAC,OAAO,CAAC;QAC7B,SAAS,CAAC,UAAU,CAAC,mBAAmB,CAAC,CAC1C,CAAA;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@actions/http-client/package.json b/node_modules/@actions/http-client/package.json index c1de221..0ae89c3 100644 --- a/node_modules/@actions/http-client/package.json +++ b/node_modules/@actions/http-client/package.json @@ -1,6 +1,6 @@ { "name": "@actions/http-client", - "version": "2.0.1", + "version": "2.2.1", "description": "Actions Http Client", "keywords": [ "github", @@ -39,10 +39,13 @@ "url": "https://github.com/actions/toolkit/issues" }, "devDependencies": { + "@types/node": "20.7.1", "@types/tunnel": "0.0.3", - "proxy": "^1.0.1" + "proxy": "^2.1.1", + "@types/proxy": "^1.0.1" }, "dependencies": { - "tunnel": "^0.0.6" + "tunnel": "^0.0.6", + "undici": "^5.25.4" } -} +} \ No newline at end of file diff --git a/node_modules/@fastify/busboy/LICENSE b/node_modules/@fastify/busboy/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/@fastify/busboy/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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. \ No newline at end of file diff --git a/node_modules/@fastify/busboy/README.md b/node_modules/@fastify/busboy/README.md new file mode 100644 index 0000000..ece3cc8 --- /dev/null +++ b/node_modules/@fastify/busboy/README.md @@ -0,0 +1,271 @@ +# busboy + +
+ +[![Build Status](https://github.com/fastify/busboy/actions/workflows/ci.yml/badge.svg)](https://github.com/fastify/busboy/actions) +[![Coverage Status](https://coveralls.io/repos/fastify/busboy/badge.svg?branch=master)](https://coveralls.io/r/fastify/busboy?branch=master) +[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](https://standardjs.com/) +[![Security Responsible Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/fastify/.github/blob/main/SECURITY.md) + +
+ +
+ +[![NPM version](https://img.shields.io/npm/v/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) +[![NPM downloads](https://img.shields.io/npm/dm/@fastify/busboy.svg?style=flat)](https://www.npmjs.com/package/@fastify/busboy) + +
+ +Description +=========== + +A Node.js module for parsing incoming HTML form data. + +This is an officially supported fork by [fastify](https://github.com/fastify/) organization of the amazing library [originally created](https://github.com/mscdex/busboy) by Brian White, +aimed at addressing long-standing issues with it. + +Benchmark (Mean time for 500 Kb payload, 2000 cycles, 1000 cycle warmup): + +| Library | Version | Mean time in nanoseconds (less is better) | +|-----------------------|---------|-------------------------------------------| +| busboy | 0.3.1 | `340114` | +| @fastify/busboy | 1.0.0 | `270984` | + +[Changelog](https://github.com/fastify/busboy/blob/master/CHANGELOG.md) since busboy 0.31. + +Requirements +============ + +* [Node.js](http://nodejs.org/) 10+ + + +Install +======= + + npm i @fastify/busboy + + +Examples +======== + +* Parsing (multipart) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); +const Busboy = require('busboy'); + +http.createServer((req, res) => { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', (fieldname, file, filename, encoding, mimetype) => { + console.log(`File [${fieldname}]: filename: ${filename}, encoding: ${encoding}, mimetype: ${mimetype}`); + file.on('data', data => { + console.log(`File [${fieldname}] got ${data.length} bytes`); + }); + file.on('end', () => { + console.log(`File [${fieldname}] Finished`); + }); + }); + busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) => { + console.log(`Field [${fieldname}]: value: ${inspect(val)}`); + }); + busboy.on('finish', () => { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end(` +
+
+
+ +
+ `); + } +}).listen(8000, () => { + console.log('Listening for requests'); +}); + +// Example output, using http://nodejs.org/images/ryan-speaker.jpg as the file: +// +// Listening for requests +// File [filefield]: filename: ryan-speaker.jpg, encoding: binary +// File [filefield] got 11971 bytes +// Field [textfield]: value: 'testing! :-)' +// File [filefield] Finished +// Done parsing form! +``` + +* Save all incoming files to disk: + +```javascript +const http = require('node:http'); +const path = require('node:path'); +const os = require('node:os'); +const fs = require('node:fs'); + +const Busboy = require('busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + var saveTo = path.join(os.tmpdir(), path.basename(fieldname)); + file.pipe(fs.createWriteStream(saveTo)); + }); + busboy.on('finish', function() { + res.writeHead(200, { 'Connection': 'close' }); + res.end("That's all folks!"); + }); + return req.pipe(busboy); + } + res.writeHead(404); + res.end(); +}).listen(8000, function() { + console.log('Listening for requests'); +}); +``` + +* Parsing (urlencoded) with default options: + +```javascript +const http = require('node:http'); +const { inspect } = require('node:util'); + +const Busboy = require('busboy'); + +http.createServer(function(req, res) { + if (req.method === 'POST') { + const busboy = new Busboy({ headers: req.headers }); + busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { + console.log('File [' + fieldname + ']: filename: ' + filename); + file.on('data', function(data) { + console.log('File [' + fieldname + '] got ' + data.length + ' bytes'); + }); + file.on('end', function() { + console.log('File [' + fieldname + '] Finished'); + }); + }); + busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated) { + console.log('Field [' + fieldname + ']: value: ' + inspect(val)); + }); + busboy.on('finish', function() { + console.log('Done parsing form!'); + res.writeHead(303, { Connection: 'close', Location: '/' }); + res.end(); + }); + req.pipe(busboy); + } else if (req.method === 'GET') { + res.writeHead(200, { Connection: 'close' }); + res.end('\ +
\ +
\ +
\ + Node.js rules!
\ + \ +
\ + '); + } +}).listen(8000, function() { + console.log('Listening for requests'); +}); + +// Example output: +// +// Listening for requests +// Field [textfield]: value: 'testing! :-)' +// Field [selectfield]: value: '9001' +// Field [checkfield]: value: 'on' +// Done parsing form! +``` + + +API +=== + +_Busboy_ is a _Writable_ stream + +Busboy (special) events +----------------------- + +* **file**(< _string_ >fieldname, < _ReadableStream_ >stream, < _string_ >filename, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new file form field found. `transferEncoding` contains the 'Content-Transfer-Encoding' value for the file stream. `mimeType` contains the 'Content-Type' value for the file stream. + * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * The property `bytesRead` informs about the number of bytes that have been read so far. + +* **field**(< _string_ >fieldname, < _string_ >value, < _boolean_ >fieldnameTruncated, < _boolean_ >valueTruncated, < _string_ >transferEncoding, < _string_ >mimeType) - Emitted for each new non-file field found. + +* **partsLimit**() - Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + +* **filesLimit**() - Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + +* **fieldsLimit**() - Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + + +Busboy methods +-------------- + +* **(constructor)**(< _object_ >config) - Creates and returns a new Busboy instance. + + * The constructor takes the following valid `config` settings: + + * **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers. + + * **autoDestroy** - _boolean_ - Whether this stream should automatically call .destroy() on itself after ending. (Default: false). + + * **highWaterMark** - _integer_ - highWaterMark to use for this Busboy instance (Default: WritableStream default). + + * **fileHwm** - _integer_ - highWaterMark to use for file streams (Default: ReadableStream default). + + * **defCharset** - _string_ - Default character set to use when one isn't defined (Default: 'utf8'). + + * **preservePath** - _boolean_ - If paths in the multipart 'filename' field shall be preserved. (Default: false). + + * **isPartAFile** - __function__ - Use this function to override the default file detection functionality. It has following parameters: + + * fieldName - __string__ The name of the field. + + * contentType - __string__ The content-type of the part, e.g. `text/plain`, `image/jpeg`, `application/octet-stream` + + * fileName - __string__ The name of a file supplied by the part. + + (Default: `(fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)`) + + * **limits** - _object_ - Various limits on incoming data. Valid properties are: + + * **fieldNameSize** - _integer_ - Max field name size (in bytes) (Default: 100 bytes). + + * **fieldSize** - _integer_ - Max field value size (in bytes) (Default: 1 MiB, which is 1024 x 1024 bytes). + + * **fields** - _integer_ - Max number of non-file fields (Default: Infinity). + + * **fileSize** - _integer_ - For multipart forms, the max file size (in bytes) (Default: Infinity). + + * **files** - _integer_ - For multipart forms, the max number of file fields (Default: Infinity). + + * **parts** - _integer_ - For multipart forms, the max number of parts (fields + files) (Default: Infinity). + + * **headerPairs** - _integer_ - For multipart forms, the max number of header key=>value pairs to parse **Default:** 2000 + + * **headerSize** - _integer_ - For multipart forms, the max size of a multipart header **Default:** 81920. + + * The constructor can throw errors: + + * **Busboy expected an options-Object.** - Busboy expected an Object as first parameters. + + * **Busboy expected an options-Object with headers-attribute.** - The first parameter is lacking of a headers-attribute. + + * **Limit $limit is not a valid number** - Busboy expected the desired limit to be of type number. Busboy throws this Error to prevent a potential security issue by falling silently back to the Busboy-defaults. Potential source for this Error can be the direct use of environment variables without transforming them to the type number. + + * **Unsupported Content-Type.** - The `Content-Type` isn't one Busboy can parse. + + * **Missing Content-Type-header.** - The provided headers don't include `Content-Type` at all. diff --git a/node_modules/@fastify/busboy/deps/dicer/LICENSE b/node_modules/@fastify/busboy/deps/dicer/LICENSE new file mode 100644 index 0000000..290762e --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/LICENSE @@ -0,0 +1,19 @@ +Copyright Brian White. All rights reserved. + +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. \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js new file mode 100644 index 0000000..3c8c081 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/Dicer.js @@ -0,0 +1,213 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const inherits = require('node:util').inherits + +const StreamSearch = require('../../streamsearch/sbmh') + +const PartStream = require('./PartStream') +const HeaderParser = require('./HeaderParser') + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js new file mode 100644 index 0000000..65f667b --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/HeaderParser.js @@ -0,0 +1,100 @@ +'use strict' + +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits +const getLimit = require('../../../lib/utils/getLimit') + +const StreamSearch = require('../../streamsearch/sbmh') + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } + } + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} + +module.exports = HeaderParser diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js new file mode 100644 index 0000000..c91da1c --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/PartStream.js @@ -0,0 +1,13 @@ +'use strict' + +const inherits = require('node:util').inherits +const ReadableStream = require('node:stream').Readable + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream diff --git a/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts new file mode 100644 index 0000000..3c5b896 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/dicer/lib/dicer.d.ts @@ -0,0 +1,164 @@ +// Type definitions for dicer 0.2 +// Project: https://github.com/mscdex/dicer +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +/// + +import stream = require("stream"); + +// tslint:disable:unified-signatures + +/** + * A very fast streaming multipart parser for node.js. + * Dicer is a WritableStream + * + * Dicer (special) events: + * - on('finish', ()) - Emitted when all parts have been parsed and the Dicer instance has been ended. + * - on('part', (stream: PartStream)) - Emitted when a new part has been found. + * - on('preamble', (stream: PartStream)) - Emitted for preamble if you should happen to need it (can usually be ignored). + * - on('trailer', (data: Buffer)) - Emitted when trailing data was found after the terminating boundary (as with the preamble, this can usually be ignored too). + */ +export class Dicer extends stream.Writable { + /** + * Creates and returns a new Dicer instance with the following valid config settings: + * + * @param config The configuration to use + */ + constructor(config: Dicer.Config); + /** + * Sets the boundary to use for parsing and performs some initialization needed for parsing. + * You should only need to use this if you set headerFirst to true in the constructor and are parsing the boundary from the preamble header. + * + * @param boundary The boundary to use + */ + setBoundary(boundary: string): void; + addListener(event: "finish", listener: () => void): this; + addListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + addListener(event: "trailer", listener: (data: Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "part", listener: (stream: Dicer.PartStream) => void): this; + on(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + on(event: "trailer", listener: (data: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "part", listener: (stream: Dicer.PartStream) => void): this; + once(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + once(event: "trailer", listener: (data: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependListener(event: "trailer", listener: (data: Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + prependOnceListener(event: "trailer", listener: (data: Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "part", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "preamble", listener: (stream: Dicer.PartStream) => void): this; + removeListener(event: "trailer", listener: (data: Buffer) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pipe", listener: (src: stream.Readable) => void): this; + removeListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; +} + +declare namespace Dicer { + interface Config { + /** + * This is the boundary used to detect the beginning of a new part. + */ + boundary?: string | undefined; + /** + * If true, preamble header parsing will be performed first. + */ + headerFirst?: boolean | undefined; + /** + * The maximum number of header key=>value pairs to parse Default: 2000 (same as node's http). + */ + maxHeaderPairs?: number | undefined; + } + + /** + * PartStream is a _ReadableStream_ + * + * PartStream (special) events: + * - on('header', (header: object)) - An object containing the header for this particular part. Each property value is an array of one or more string values. + */ + interface PartStream extends stream.Readable { + addListener(event: "header", listener: (header: object) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "header", listener: (header: object) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "header", listener: (header: object) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "header", listener: (header: object) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "header", listener: (header: object) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + removeListener(event: "header", listener: (header: object) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: Buffer | string) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: string, listener: (...args: any[]) => void): this; + } +} \ No newline at end of file diff --git a/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js new file mode 100644 index 0000000..b90c0e8 --- /dev/null +++ b/node_modules/@fastify/busboy/deps/streamsearch/sbmh.js @@ -0,0 +1,228 @@ +'use strict' + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * 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. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = require('node:events').EventEmitter +const inherits = require('node:util').inherits + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH diff --git a/node_modules/@fastify/busboy/lib/main.d.ts b/node_modules/@fastify/busboy/lib/main.d.ts new file mode 100644 index 0000000..91b6448 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.d.ts @@ -0,0 +1,196 @@ +// Definitions by: Jacob Baskin +// BendingBender +// Igor Savin + +/// + +import * as http from 'http'; +import { Readable, Writable } from 'stream'; +export { Dicer } from "../deps/dicer/lib/dicer"; + +export const Busboy: BusboyConstructor; +export default Busboy; + +export interface BusboyConfig { + /** + * These are the HTTP headers of the incoming request, which are used by individual parsers. + */ + headers: BusboyHeaders; + /** + * `highWaterMark` to use for this Busboy instance. + * @default WritableStream default. + */ + highWaterMark?: number | undefined; + /** + * highWaterMark to use for file streams. + * @default ReadableStream default. + */ + fileHwm?: number | undefined; + /** + * Default character set to use when one isn't defined. + * @default 'utf8' + */ + defCharset?: string | undefined; + /** + * Detect if a Part is a file. + * + * By default a file is detected if contentType + * is application/octet-stream or fileName is not + * undefined. + * + * Modify this to handle e.g. Blobs. + */ + isPartAFile?: (fieldName: string | undefined, contentType: string | undefined, fileName: string | undefined) => boolean; + /** + * If paths in the multipart 'filename' field shall be preserved. + * @default false + */ + preservePath?: boolean | undefined; + /** + * Various limits on incoming data. + */ + limits?: + | { + /** + * Max field name size (in bytes) + * @default 100 bytes + */ + fieldNameSize?: number | undefined; + /** + * Max field value size (in bytes) + * @default 1MB + */ + fieldSize?: number | undefined; + /** + * Max number of non-file fields + * @default Infinity + */ + fields?: number | undefined; + /** + * For multipart forms, the max file size (in bytes) + * @default Infinity + */ + fileSize?: number | undefined; + /** + * For multipart forms, the max number of file fields + * @default Infinity + */ + files?: number | undefined; + /** + * For multipart forms, the max number of parts (fields + files) + * @default Infinity + */ + parts?: number | undefined; + /** + * For multipart forms, the max number of header key=>value pairs to parse + * @default 2000 + */ + headerPairs?: number | undefined; + + /** + * For multipart forms, the max size of a header part + * @default 81920 + */ + headerSize?: number | undefined; + } + | undefined; +} + +export type BusboyHeaders = { 'content-type': string } & http.IncomingHttpHeaders; + +export interface BusboyFileStream extends + Readable { + + truncated: boolean; + + /** + * The number of bytes that have been read so far. + */ + bytesRead: number; +} + +export interface Busboy extends Writable { + addListener(event: Event, listener: BusboyEvents[Event]): this; + + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + + on(event: Event, listener: BusboyEvents[Event]): this; + + on(event: string | symbol, listener: (...args: any[]) => void): this; + + once(event: Event, listener: BusboyEvents[Event]): this; + + once(event: string | symbol, listener: (...args: any[]) => void): this; + + removeListener(event: Event, listener: BusboyEvents[Event]): this; + + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + + off(event: Event, listener: BusboyEvents[Event]): this; + + off(event: string | symbol, listener: (...args: any[]) => void): this; + + prependListener(event: Event, listener: BusboyEvents[Event]): this; + + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + + prependOnceListener(event: Event, listener: BusboyEvents[Event]): this; + + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; +} + +export interface BusboyEvents { + /** + * Emitted for each new file form field found. + * + * * Note: if you listen for this event, you should always handle the `stream` no matter if you care about the + * file contents or not (e.g. you can simply just do `stream.resume();` if you want to discard the contents), + * otherwise the 'finish' event will never fire on the Busboy instance. However, if you don't care about **any** + * incoming files, you can simply not listen for the 'file' event at all and any/all files will be automatically + * and safely discarded (these discarded files do still count towards `files` and `parts` limits). + * * If a configured file size limit was reached, `stream` will both have a boolean property `truncated` + * (best checked at the end of the stream) and emit a 'limit' event to notify you when this happens. + * + * @param listener.transferEncoding Contains the 'Content-Transfer-Encoding' value for the file stream. + * @param listener.mimeType Contains the 'Content-Type' value for the file stream. + */ + file: ( + fieldname: string, + stream: BusboyFileStream, + filename: string, + transferEncoding: string, + mimeType: string, + ) => void; + /** + * Emitted for each new non-file field found. + */ + field: ( + fieldname: string, + value: string, + fieldnameTruncated: boolean, + valueTruncated: boolean, + transferEncoding: string, + mimeType: string, + ) => void; + finish: () => void; + /** + * Emitted when specified `parts` limit has been reached. No more 'file' or 'field' events will be emitted. + */ + partsLimit: () => void; + /** + * Emitted when specified `files` limit has been reached. No more 'file' events will be emitted. + */ + filesLimit: () => void; + /** + * Emitted when specified `fields` limit has been reached. No more 'field' events will be emitted. + */ + fieldsLimit: () => void; + error: (error: unknown) => void; +} + +export interface BusboyConstructor { + (options: BusboyConfig): Busboy; + + new(options: BusboyConfig): Busboy; +} + diff --git a/node_modules/@fastify/busboy/lib/main.js b/node_modules/@fastify/busboy/lib/main.js new file mode 100644 index 0000000..8794beb --- /dev/null +++ b/node_modules/@fastify/busboy/lib/main.js @@ -0,0 +1,85 @@ +'use strict' + +const WritableStream = require('node:stream').Writable +const { inherits } = require('node:util') +const Dicer = require('../deps/dicer/lib/Dicer') + +const MultipartParser = require('./types/multipart') +const UrlencodedParser = require('./types/urlencoded') +const parseParams = require('./utils/parseParams') + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports.default = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer diff --git a/node_modules/@fastify/busboy/lib/types/multipart.js b/node_modules/@fastify/busboy/lib/types/multipart.js new file mode 100644 index 0000000..d691eca --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/multipart.js @@ -0,0 +1,306 @@ +'use strict' + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = require('node:stream') +const { inherits } = require('node:util') + +const Dicer = require('../../deps/dicer/lib/Dicer') + +const parseParams = require('../utils/parseParams') +const decodeText = require('../utils/decodeText') +const basename = require('../utils/basename') +const getLimit = require('../utils/getLimit') + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart diff --git a/node_modules/@fastify/busboy/lib/types/urlencoded.js b/node_modules/@fastify/busboy/lib/types/urlencoded.js new file mode 100644 index 0000000..6f5f784 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/types/urlencoded.js @@ -0,0 +1,190 @@ +'use strict' + +const Decoder = require('../utils/Decoder') +const decodeText = require('../utils/decodeText') +const getLimit = require('../utils/getLimit') + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded diff --git a/node_modules/@fastify/busboy/lib/utils/Decoder.js b/node_modules/@fastify/busboy/lib/utils/Decoder.js new file mode 100644 index 0000000..7917678 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/Decoder.js @@ -0,0 +1,54 @@ +'use strict' + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder diff --git a/node_modules/@fastify/busboy/lib/utils/basename.js b/node_modules/@fastify/busboy/lib/utils/basename.js new file mode 100644 index 0000000..db58819 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/basename.js @@ -0,0 +1,14 @@ +'use strict' + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} diff --git a/node_modules/@fastify/busboy/lib/utils/decodeText.js b/node_modules/@fastify/busboy/lib/utils/decodeText.js new file mode 100644 index 0000000..eac7d35 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/decodeText.js @@ -0,0 +1,114 @@ +'use strict' + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText diff --git a/node_modules/@fastify/busboy/lib/utils/getLimit.js b/node_modules/@fastify/busboy/lib/utils/getLimit.js new file mode 100644 index 0000000..cb64fd6 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/getLimit.js @@ -0,0 +1,16 @@ +'use strict' + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} diff --git a/node_modules/@fastify/busboy/lib/utils/parseParams.js b/node_modules/@fastify/busboy/lib/utils/parseParams.js new file mode 100644 index 0000000..1698e62 --- /dev/null +++ b/node_modules/@fastify/busboy/lib/utils/parseParams.js @@ -0,0 +1,196 @@ +/* eslint-disable object-property-newline */ +'use strict' + +const decodeText = require('./decodeText') + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams diff --git a/node_modules/@fastify/busboy/package.json b/node_modules/@fastify/busboy/package.json new file mode 100644 index 0000000..83693ac --- /dev/null +++ b/node_modules/@fastify/busboy/package.json @@ -0,0 +1,86 @@ +{ + "name": "@fastify/busboy", + "version": "2.1.1", + "private": false, + "author": "Brian White ", + "contributors": [ + { + "name": "Igor Savin", + "email": "kibertoad@gmail.com", + "url": "https://github.com/kibertoad" + }, + { + "name": "Aras Abbasi", + "email": "aras.abbasi@gmail.com", + "url": "https://github.com/uzlopak" + } + ], + "description": "A streaming parser for HTML form data for node.js", + "main": "lib/main", + "type": "commonjs", + "types": "lib/main.d.ts", + "scripts": { + "bench:busboy": "cd benchmarks && npm install && npm run benchmark-fastify", + "bench:dicer": "node bench/dicer/dicer-bench-multipart-parser.js", + "coveralls": "nyc report --reporter=lcov", + "lint": "npm run lint:standard", + "lint:everything": "npm run lint && npm run test:types", + "lint:fix": "standard --fix", + "lint:standard": "standard --verbose | snazzy", + "test:mocha": "tap", + "test:types": "tsd", + "test:coverage": "nyc npm run test", + "test": "npm run test:mocha" + }, + "engines": { + "node": ">=14" + }, + "devDependencies": { + "@types/node": "^20.1.0", + "busboy": "^1.0.0", + "photofinish": "^1.8.0", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "tap": "^16.3.8", + "tinybench": "^2.5.1", + "tsd": "^0.30.0", + "typescript": "^5.0.2" + }, + "keywords": [ + "uploads", + "forms", + "multipart", + "form-data" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/fastify/busboy.git" + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": false, + "module": "commonjs", + "target": "ES2017" + } + }, + "standard": { + "globals": [ + "describe", + "it" + ], + "ignore": [ + "bench" + ] + }, + "files": [ + "README.md", + "LICENSE", + "lib/*", + "deps/encoding/*", + "deps/dicer/lib", + "deps/streamsearch/", + "deps/dicer/LICENSE" + ] +} diff --git a/node_modules/@ungap/promise-all-settled/LICENSE b/node_modules/@ungap/promise-all-settled/LICENSE deleted file mode 100644 index 5b7eb00..0000000 --- a/node_modules/@ungap/promise-all-settled/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2019, Andrea Giammarchi, @WebReflection - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE -OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/@ungap/promise-all-settled/README.md b/node_modules/@ungap/promise-all-settled/README.md deleted file mode 100644 index d15b811..0000000 --- a/node_modules/@ungap/promise-all-settled/README.md +++ /dev/null @@ -1,26 +0,0 @@ -# Promise.allSettled - -[![Build Status](https://travis-ci.com/ungap/promise-all-settled.svg?branch=master)](https://travis-ci.com/ungap/promise-all-settled) [![Coverage Status](https://coveralls.io/repos/github/ungap/promise-all-settled/badge.svg?branch=master)](https://coveralls.io/github/ungap/promise-all-settled?branch=master) [![Greenkeeper badge](https://badges.greenkeeper.io/ungap/promise-all-settled.svg)](https://greenkeeper.io/) ![WebReflection status](https://offline.report/status/webreflection.svg) - -A cross platform [Promise.allSettled](https://github.com/tc39/proposal-promise-allSettled) polyfill. - - * CDN global utility via https://unpkg.com/@ungap/promise-all-settled - * ESM via `import allSettled from '@ungap/promise-all-settled'` - * CJS via `const allSettled = require('@ungap/promise-all-settled')` - - -### Example - -```js -const allSettled = require("@ungap/promise-all-settled"); - -// use it via call -allSettled.call(Promise, []); - -// or bind it: -const $settled = allSettled.bind(Promise); - -// or put it in the Promise class -if (!Promise.allSettled) - Promise.allSettled = allSettled; -``` diff --git a/node_modules/@ungap/promise-all-settled/cjs/index.js b/node_modules/@ungap/promise-all-settled/cjs/index.js deleted file mode 100644 index 1ebc442..0000000 --- a/node_modules/@ungap/promise-all-settled/cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -var allSettled = Promise.allSettled || function ($) {'use strict'; - var self = this; - return self.all( - $.map( - function (value) { - return self.resolve(value).then(this.$, this._); - }, - { - $: function (value) { - return {status: 'fulfilled', value: value}; - }, - _: function (reason) { - return {status: 'rejected', reason: reason}; - } - } - ) - ); -}; -module.exports = allSettled; diff --git a/node_modules/@ungap/promise-all-settled/cjs/package.json b/node_modules/@ungap/promise-all-settled/cjs/package.json deleted file mode 100644 index 729ac4d..0000000 --- a/node_modules/@ungap/promise-all-settled/cjs/package.json +++ /dev/null @@ -1 +0,0 @@ -{"type":"commonjs"} diff --git a/node_modules/@ungap/promise-all-settled/esm/index.js b/node_modules/@ungap/promise-all-settled/esm/index.js deleted file mode 100644 index f53cebe..0000000 --- a/node_modules/@ungap/promise-all-settled/esm/index.js +++ /dev/null @@ -1,19 +0,0 @@ -var allSettled = Promise.allSettled || function ($) {'use strict'; - var self = this; - return self.all( - $.map( - function (value) { - return self.resolve(value).then(this.$, this._); - }, - { - $: function (value) { - return {status: 'fulfilled', value: value}; - }, - _: function (reason) { - return {status: 'rejected', reason: reason}; - } - } - ) - ); -}; -export default allSettled; diff --git a/node_modules/@ungap/promise-all-settled/index.js b/node_modules/@ungap/promise-all-settled/index.js deleted file mode 100644 index 0fd81b7..0000000 --- a/node_modules/@ungap/promise-all-settled/index.js +++ /dev/null @@ -1,18 +0,0 @@ -var allSettled = Promise.allSettled || function ($) {'use strict'; - var self = this; - return self.all( - $.map( - function (value) { - return self.resolve(value).then(this.$, this._); - }, - { - $: function (value) { - return {status: 'fulfilled', value: value}; - }, - _: function (reason) { - return {status: 'rejected', reason: reason}; - } - } - ) - ); -}; diff --git a/node_modules/@ungap/promise-all-settled/min.js b/node_modules/@ungap/promise-all-settled/min.js deleted file mode 100644 index b9b0ae2..0000000 --- a/node_modules/@ungap/promise-all-settled/min.js +++ /dev/null @@ -1 +0,0 @@ -var allSettled=Promise.allSettled||function(t){"use strict";var e=this;return e.all(t.map(function(t){return e.resolve(t).then(this.$,this._)},{$:function(t){return{status:"fulfilled",value:t}},_:function(t){return{status:"rejected",reason:t}}}))}; \ No newline at end of file diff --git a/node_modules/@ungap/promise-all-settled/package.json b/node_modules/@ungap/promise-all-settled/package.json deleted file mode 100644 index fd65853..0000000 --- a/node_modules/@ungap/promise-all-settled/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@ungap/promise-all-settled", - "version": "1.1.2", - "description": "A cross platform Promise.allSettled polyfill", - "main": "./cjs/index.js", - "module": "./esm/index.js", - "unpkg": "min.js", - "scripts": { - "build": "npm run cjs && npm run esm && npm run min && npm run test && npm run size", - "cjs": "cp index.js cjs/ && echo 'module.exports = allSettled;' >> cjs/index.js", - "esm": "cp index.js esm/ && echo 'export default allSettled;' >> esm/index.js", - "min": "uglifyjs index.js --support-ie8 --comments=/^!/ -c -m -o min.js", - "size": "cat index.js | wc -c && cat min.js | wc -c && gzip -c9 min.js | wc -c && cat min.js | brotli | wc -c", - "coveralls": "nyc report --reporter=text-lcov | coveralls", - "test": "nyc node test/index.js" - }, - "keywords": [ - "Promise", - "allSettled", - "polyfill", - "utility", - "ungap" - ], - "author": "Andrea Giammarchi", - "license": "ISC", - "devDependencies": { - "coveralls": "^3.1.0", - "nyc": "^15.0.1", - "uglify-js": "^3.9.1" - }, - "repository": { - "type": "git", - "url": "git+https://github.com/ungap/promise-all-settled.git" - }, - "bugs": { - "url": "https://github.com/ungap/promise-all-settled/issues" - }, - "homepage": "https://github.com/ungap/promise-all-settled#readme", - "type": "module", - "exports": { - "import": "./esm/index.js", - "default": "./cjs/index.js" - } -} diff --git a/node_modules/cliui/node_modules/ansi-regex/index.d.ts b/node_modules/ansi-regex/index.d.ts similarity index 100% rename from node_modules/cliui/node_modules/ansi-regex/index.d.ts rename to node_modules/ansi-regex/index.d.ts diff --git a/node_modules/ansi-regex/index.js b/node_modules/ansi-regex/index.js index 93f162c..616ff83 100644 --- a/node_modules/ansi-regex/index.js +++ b/node_modules/ansi-regex/index.js @@ -1,10 +1,10 @@ 'use strict'; -module.exports = () => { +module.exports = ({onlyFirst = false} = {}) => { const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[a-zA-Z\\d]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))' + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' ].join('|'); - return new RegExp(pattern, 'g'); + return new RegExp(pattern, onlyFirst ? undefined : 'g'); }; diff --git a/node_modules/ansi-regex/package.json b/node_modules/ansi-regex/package.json index 0548619..017f531 100644 --- a/node_modules/ansi-regex/package.json +++ b/node_modules/ansi-regex/package.json @@ -1,53 +1,55 @@ { - "name": "ansi-regex", - "version": "3.0.1", - "description": "Regular expression for matching ANSI escape codes", - "license": "MIT", - "repository": "chalk/ansi-regex", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava", - "view-supported": "node fixtures/view-codes.js" - }, - "files": [ - "index.js" - ], - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "text", - "regex", - "regexp", - "re", - "match", - "test", - "find", - "pattern" - ], - "devDependencies": { - "ava": "*", - "xo": "*" - } + "name": "ansi-regex", + "version": "5.0.1", + "description": "Regular expression for matching ANSI escape codes", + "license": "MIT", + "repository": "chalk/ansi-regex", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd", + "view-supported": "node fixtures/view-codes.js" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "command-line", + "text", + "regex", + "regexp", + "re", + "match", + "test", + "find", + "pattern" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.9.0", + "xo": "^0.25.3" + } } diff --git a/node_modules/ansi-regex/readme.md b/node_modules/ansi-regex/readme.md index 22db1c3..4d848bc 100644 --- a/node_modules/ansi-regex/readme.md +++ b/node_modules/ansi-regex/readme.md @@ -1,4 +1,4 @@ -# ansi-regex [![Build Status](https://travis-ci.org/chalk/ansi-regex.svg?branch=master)](https://travis-ci.org/chalk/ansi-regex) +# ansi-regex > Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) @@ -23,9 +23,33 @@ ansiRegex().test('cake'); '\u001B[4mcake\u001B[0m'.match(ansiRegex()); //=> ['\u001B[4m', '\u001B[0m'] + +'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); +//=> ['\u001B[4m'] + +'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); +//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] ``` +## API + +### ansiRegex(options?) + +Returns a regex for matching ANSI escape codes. + +#### options + +Type: `object` + +##### onlyFirst + +Type: `boolean`
+Default: `false` *(Matches any ANSI escape codes in a string)* + +Match only the first ANSI escape. + + ## FAQ ### Why do you test for codes not in the ECMA 48 standard? @@ -41,6 +65,14 @@ On the historical side, those ECMA standards were established in the early 90's - [Josh Junon](https://github.com/qix-) -## License +--- -MIT +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/anymatch/index.d.ts b/node_modules/anymatch/index.d.ts index 196d061..3ef7eaa 100644 --- a/node_modules/anymatch/index.d.ts +++ b/node_modules/anymatch/index.d.ts @@ -10,6 +10,7 @@ type PicomatchOptions = {dot: boolean}; declare const anymatch: { (matchers: AnymatchMatcher): AnymatchTester; + (matchers: AnymatchMatcher, testString: null, returnIndex: true | PicomatchOptions): AnymatchTester; (matchers: AnymatchMatcher, testString: string|any[], returnIndex: true | PicomatchOptions): number; (matchers: AnymatchMatcher, testString: string|any[]): boolean; } diff --git a/node_modules/anymatch/index.js b/node_modules/anymatch/index.js index 9fb3ebb..8eb73e9 100644 --- a/node_modules/anymatch/index.js +++ b/node_modules/anymatch/index.js @@ -47,7 +47,7 @@ const matchPatterns = (patterns, negPatterns, args, returnIndex) => { throw new TypeError('anymatch: second argument must be a string: got ' + Object.prototype.toString.call(_path)) } - const path = normalizePath(_path); + const path = normalizePath(_path, false); for (let index = 0; index < negPatterns.length; index++) { const nglob = negPatterns[index]; diff --git a/node_modules/anymatch/package.json b/node_modules/anymatch/package.json index f9b5284..2cb2307 100644 --- a/node_modules/anymatch/package.json +++ b/node_modules/anymatch/package.json @@ -1,6 +1,6 @@ { "name": "anymatch", - "version": "3.1.2", + "version": "3.1.3", "description": "Matches strings against configurable strings, globs, regular expressions, and/or functions", "files": [ "index.js", diff --git a/node_modules/async/all.js b/node_modules/async/all.js index 148db68..622b301 100644 --- a/node_modules/async/all.js +++ b/node_modules/async/all.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -113,7 +113,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function every(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(every, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allLimit.js b/node_modules/async/allLimit.js index 25b2c08..375e126 100644 --- a/node_modules/async/allLimit.js +++ b/node_modules/async/allLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,7 +40,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function everyLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(everyLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/allSeries.js b/node_modules/async/allSeries.js index 147c3dc..9a6bf7d 100644 --- a/node_modules/async/allSeries.js +++ b/node_modules/async/allSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function everySeries(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(everySeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/any.js b/node_modules/async/any.js index 2046cf6..a5bd328 100644 --- a/node_modules/async/any.js +++ b/node_modules/async/any.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -116,7 +116,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function some(coll, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(some, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anyLimit.js b/node_modules/async/anyLimit.js index c8a295a..3a8096f 100644 --- a/node_modules/async/anyLimit.js +++ b/node_modules/async/anyLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -41,7 +41,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function someLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(someLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/anySeries.js b/node_modules/async/anySeries.js index ee0654b..51aad19 100644 --- a/node_modules/async/anySeries.js +++ b/node_modules/async/anySeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,7 +40,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function someSeries(coll, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(someSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/apply.js b/node_modules/async/apply.js index 5246833..d40784f 100644 --- a/node_modules/async/apply.js +++ b/node_modules/async/apply.js @@ -1,55 +1,11 @@ "use strict"; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = function (fn, ...args) { - return (...callArgs) => fn(...args, ...callArgs); + return (...callArgs) => fn(...args, ...callArgs); }; -module.exports = exports["default"]; /** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEach.js b/node_modules/async/applyEach.js index b08c670..841842c 100644 --- a/node_modules/async/applyEach.js +++ b/node_modules/async/applyEach.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _applyEach = require('./internal/applyEach.js'); @@ -54,4 +54,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * ); */ exports.default = (0, _applyEach2.default)(_map2.default); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/applyEachSeries.js b/node_modules/async/applyEachSeries.js index 6a19ca3..f5267f6 100644 --- a/node_modules/async/applyEachSeries.js +++ b/node_modules/async/applyEachSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _applyEach = require('./internal/applyEach.js'); @@ -34,4 +34,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * a callback. */ exports.default = (0, _applyEach2.default)(_mapSeries2.default); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/asyncify.js b/node_modules/async/asyncify.js index 3c3bf88..ddc3f02 100644 --- a/node_modules/async/asyncify.js +++ b/node_modules/async/asyncify.js @@ -102,7 +102,7 @@ function handlePromise(promise, callback) { return promise.then(value => { invokeCallback(callback, null, value); }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); }); } @@ -115,4 +115,4 @@ function invokeCallback(callback, error, value) { }, err); } } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/auto.js b/node_modules/async/auto.js index c4a85d4..163c4f2 100644 --- a/node_modules/async/auto.js +++ b/node_modules/async/auto.js @@ -330,4 +330,4 @@ function auto(tasks, concurrency, callback) { return callback[_promiseCallback.PROMISE_SYMBOL]; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/autoInject.js b/node_modules/async/autoInject.js index 393baad..38eac15 100644 --- a/node_modules/async/autoInject.js +++ b/node_modules/async/autoInject.js @@ -179,4 +179,4 @@ function autoInject(tasks, callback) { return (0, _auto2.default)(newTasks, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/cargo.js b/node_modules/async/cargo.js index aa385f8..d4abd21 100644 --- a/node_modules/async/cargo.js +++ b/node_modules/async/cargo.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = cargo; @@ -58,6 +58,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * console.log('finished processing baz'); */ function cargo(worker, payload) { - return (0, _queue2.default)(worker, 1, payload); + return (0, _queue2.default)(worker, 1, payload); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/cargoQueue.js b/node_modules/async/cargoQueue.js index 823a631..69a60d6 100644 --- a/node_modules/async/cargoQueue.js +++ b/node_modules/async/cargoQueue.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = cargo; @@ -66,6 +66,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * }); */ function cargo(worker, concurrency, payload) { - return (0, _queue2.default)(worker, concurrency, payload); + return (0, _queue2.default)(worker, concurrency, payload); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/compose.js b/node_modules/async/compose.js index d4ce989..0131c02 100644 --- a/node_modules/async/compose.js +++ b/node_modules/async/compose.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = compose; @@ -50,6 +50,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * }); */ function compose(...args) { - return (0, _seq2.default)(...args.reverse()); + return (0, _seq2.default)(...args.reverse()); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concat.js b/node_modules/async/concat.js index 8eed1ac..4540a79 100644 --- a/node_modules/async/concat.js +++ b/node_modules/async/concat.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _concatLimit = require('./concatLimit.js'); @@ -109,7 +109,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function concat(coll, iteratee, callback) { - return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); } exports.default = (0, _awaitify2.default)(concat, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatLimit.js b/node_modules/async/concatLimit.js index 3d170f1..a27cc7d 100644 --- a/node_modules/async/concatLimit.js +++ b/node_modules/async/concatLimit.js @@ -57,4 +57,4 @@ function concatLimit(coll, limit, iteratee, callback) { }); } exports.default = (0, _awaitify2.default)(concatLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/concatSeries.js b/node_modules/async/concatSeries.js index 84add3b..332de3f 100644 --- a/node_modules/async/concatSeries.js +++ b/node_modules/async/concatSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _concatLimit = require('./concatLimit.js'); @@ -35,7 +35,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns A Promise, if no callback is passed */ function concatSeries(coll, iteratee, callback) { - return (0, _concatLimit2.default)(coll, 1, iteratee, callback); + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(concatSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/constant.js b/node_modules/async/constant.js index 0759653..ea406f6 100644 --- a/node_modules/async/constant.js +++ b/node_modules/async/constant.js @@ -11,45 +11,4 @@ exports.default = function (...args) { }; }; -module.exports = exports["default"]; /** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detect.js b/node_modules/async/detect.js index 05b2e5c..d5896ef 100644 --- a/node_modules/async/detect.js +++ b/node_modules/async/detect.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -90,7 +90,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function detect(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detect, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectLimit.js b/node_modules/async/detectLimit.js index db6961e..c59843b 100644 --- a/node_modules/async/detectLimit.js +++ b/node_modules/async/detectLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -42,7 +42,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function detectLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detectLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/detectSeries.js b/node_modules/async/detectSeries.js index b9131b4..b486899 100644 --- a/node_modules/async/detectSeries.js +++ b/node_modules/async/detectSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,8 +40,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function detectSeries(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detectSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dir.js b/node_modules/async/dir.js index 950d0a2..8e9fafd 100644 --- a/node_modules/async/dir.js +++ b/node_modules/async/dir.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _consoleFunc = require('./internal/consoleFunc.js'); @@ -40,4 +40,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * {hello: 'world'} */ exports.default = (0, _consoleFunc2.default)('dir'); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/dist/async.js b/node_modules/async/dist/async.js index 8d5e782..e58f8f2 100644 --- a/node_modules/async/dist/async.js +++ b/node_modules/async/dist/async.js @@ -1,8 +1,8 @@ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = {}))); -}(this, (function (exports) { 'use strict'; + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.async = {})); +})(this, (function (exports) { 'use strict'; /** * Creates a continuation function with some arguments already applied. @@ -74,19 +74,19 @@ return (fn, ...args) => defer(() => fn(...args)); } - var _defer; + var _defer$1; if (hasQueueMicrotask) { - _defer = queueMicrotask; + _defer$1 = queueMicrotask; } else if (hasSetImmediate) { - _defer = setImmediate; + _defer$1 = setImmediate; } else if (hasNextTick) { - _defer = process.nextTick; + _defer$1 = process.nextTick; } else { - _defer = fallback; + _defer$1 = fallback; } - var setImmediate$1 = wrap(_defer); + var setImmediate$1 = wrap(_defer$1); /** * Take a sync function and make it async, passing its return value to a @@ -173,7 +173,7 @@ return promise.then(value => { invokeCallback(callback, null, value); }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); }); } @@ -204,7 +204,8 @@ // conditionally promisify a function. // only return a promise if a callback is omitted - function awaitify (asyncFn, arity = asyncFn.length) { + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; if (!arity) throw new Error('arity is undefined') function awaitable (...args) { if (typeof args[arity - 1] === 'function') { @@ -223,7 +224,7 @@ return awaitable } - function applyEach (eachfn) { + function applyEach$1 (eachfn) { return function applyEach(fns, ...callArgs) { const go = awaitify(function (callback) { var that = this; @@ -262,6 +263,7 @@ // A temporary value used to identify if the loop should be broken. // See #1064, #1293 const breakLoop = {}; + var breakLoop$1 = breakLoop; function once(fn) { function wrapper (...args) { @@ -372,7 +374,7 @@ return } - if (result === breakLoop || (done && running <= 0)) { + if (result === breakLoop$1 || (done && running <= 0)) { done = true; //console.log('done iterCb') return callback(null); @@ -390,7 +392,7 @@ replenish(); } - var eachOfLimit = (limit) => { + var eachOfLimit$2 = (limit) => { return (obj, iteratee, callback) => { callback = once(callback); if (limit <= 0) { @@ -422,7 +424,7 @@ done = true; canceled = true; } - else if (value === breakLoop || (done && running <= 0)) { + else if (value === breakLoop$1 || (done && running <= 0)) { done = true; return callback(null); } @@ -473,11 +475,11 @@ * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @returns {Promise} a promise, if a callback is omitted */ - function eachOfLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); } - var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); + var eachOfLimit$1 = awaitify(eachOfLimit, 4); // eachOf implementation optimized for array-likes function eachOfArrayLike(coll, iteratee, callback) { @@ -497,7 +499,7 @@ if (canceled === true) return if (err) { callback(err); - } else if ((++completed === length) || value === breakLoop) { + } else if ((++completed === length) || value === breakLoop$1) { callback(null); } } @@ -509,7 +511,7 @@ // a generic version of eachOf which can handle array, object, and iterator cases. function eachOfGeneric (coll, iteratee, callback) { - return eachOfLimit$2(coll, Infinity, iteratee, callback); + return eachOfLimit$1(coll, Infinity, iteratee, callback); } /** @@ -789,7 +791,7 @@ * callback * ); */ - var applyEach$1 = applyEach(map$1); + var applyEach = applyEach$1(map$1); /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. @@ -810,7 +812,7 @@ * @returns {Promise} a promise, if a callback is omitted */ function eachOfSeries(coll, iteratee, callback) { - return eachOfLimit$2(coll, 1, iteratee, callback) + return eachOfLimit$1(coll, 1, iteratee, callback) } var eachOfSeries$1 = awaitify(eachOfSeries, 3); @@ -857,7 +859,7 @@ * appling the `args` to the list of functions. It takes no args, other than * a callback. */ - var applyEachSeries = applyEach(mapSeries$1); + var applyEachSeries = applyEach$1(mapSeries$1); const PROMISE_SYMBOL = Symbol('promiseCallback'); @@ -1455,7 +1457,7 @@ dll.head = dll.tail = node; } - function queue(worker, concurrency, payload) { + function queue$1(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } @@ -1773,8 +1775,8 @@ * await cargo.push({name: 'baz'}); * console.log('finished processing baz'); */ - function cargo(worker, payload) { - return queue(worker, 1, payload); + function cargo$1(worker, payload) { + return queue$1(worker, 1, payload); } /** @@ -1831,8 +1833,8 @@ * console.log('finished processing boo'); * }); */ - function cargo$1(worker, concurrency, payload) { - return queue(worker, concurrency, payload); + function cargo(worker, concurrency, payload) { + return queue$1(worker, concurrency, payload); } /** @@ -2088,7 +2090,7 @@ * @returns {Promise} a promise, if no callback is passed */ function mapLimit (coll, limit, iteratee, callback) { - return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) } var mapLimit$1 = awaitify(mapLimit, 4); @@ -2298,7 +2300,7 @@ * //... * }, callback); */ - function constant(...args) { + function constant$1(...args) { return function (...ignoredArgs/*, callback*/) { var callback = ignoredArgs.pop(); return callback(null, ...args); @@ -2317,7 +2319,7 @@ if (check(result) && !testResult) { testPassed = true; testResult = getResult(true, value); - return callback(null, breakLoop); + return callback(null, breakLoop$1); } callback(); }); @@ -2428,7 +2430,7 @@ * @returns {Promise} a promise, if a callback is omitted */ function detectLimit(coll, limit, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) } var detectLimit$1 = awaitify(detectLimit, 4); @@ -2454,7 +2456,7 @@ * @returns {Promise} a promise, if a callback is omitted */ function detectSeries(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) } var detectSeries$1 = awaitify(detectSeries, 3); @@ -2687,11 +2689,11 @@ * } * */ - function eachLimit(coll, iteratee, callback) { + function eachLimit$2(coll, iteratee, callback) { return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - var each = awaitify(eachLimit, 3); + var each = awaitify(eachLimit$2, 3); /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. @@ -2714,10 +2716,10 @@ * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @returns {Promise} a promise, if a callback is omitted */ - function eachLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - var eachLimit$2 = awaitify(eachLimit$1, 4); + var eachLimit$1 = awaitify(eachLimit, 4); /** * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. @@ -2743,7 +2745,7 @@ * @returns {Promise} a promise, if a callback is omitted */ function eachSeries(coll, iteratee, callback) { - return eachLimit$2(coll, 1, iteratee, callback) + return eachLimit$1(coll, 1, iteratee, callback) } var eachSeries$1 = awaitify(eachSeries, 3); @@ -2920,7 +2922,7 @@ * @returns {Promise} a promise, if no callback provided */ function everyLimit(coll, limit, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) } var everyLimit$1 = awaitify(everyLimit, 4); @@ -3083,7 +3085,7 @@ * @returns {Promise} a promise, if no callback provided */ function filterLimit (coll, limit, iteratee, callback) { - return _filter(eachOfLimit(limit), coll, iteratee, callback) + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) } var filterLimit$1 = awaitify(filterLimit, 4); @@ -3378,7 +3380,7 @@ callback = once(callback); var newObj = {}; var _iteratee = wrapAsync(iteratee); - return eachOfLimit(limit)(obj, (val, key, next) => { + return eachOfLimit$2(limit)(obj, (val, key, next) => { _iteratee(val, key, (err, result) => { if (err) return next(err); newObj[key] = result; @@ -3655,19 +3657,19 @@ * // a, b, and c equal 1, 2, and 3 * }, 1, 2, 3); */ - var _defer$1; + var _defer; if (hasNextTick) { - _defer$1 = process.nextTick; + _defer = process.nextTick; } else if (hasSetImmediate) { - _defer$1 = setImmediate; + _defer = setImmediate; } else { - _defer$1 = fallback; + _defer = fallback; } - var nextTick = wrap(_defer$1); + var nextTick = wrap(_defer); - var parallel = awaitify((eachfn, tasks, callback) => { + var _parallel = awaitify((eachfn, tasks, callback) => { var results = isArrayLike(tasks) ? [] : {}; eachfn(tasks, (task, key, taskCb) => { @@ -3840,8 +3842,8 @@ * } * */ - function parallel$1(tasks, callback) { - return parallel(eachOf$1, tasks, callback); + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); } /** @@ -3865,7 +3867,7 @@ * @returns {Promise} a promise, if a callback is not passed */ function parallelLimit(tasks, limit, callback) { - return parallel(eachOfLimit(limit), tasks, callback); + return _parallel(eachOfLimit$2(limit), tasks, callback); } /** @@ -4010,9 +4012,9 @@ * console.log('finished processing bar'); * }); */ - function queue$1 (worker, concurrency) { + function queue (worker, concurrency) { var _worker = wrapAsync(worker); - return queue((items, cb) => { + return queue$1((items, cb) => { _worker(items[0], cb); }, concurrency, 1); } @@ -4159,7 +4161,7 @@ */ function priorityQueue(worker, concurrency) { // Start with a normal queue - var q = queue$1(worker, concurrency); + var q = queue(worker, concurrency); var { push, @@ -4414,7 +4416,7 @@ return results; } - function reject(eachfn, arr, _iteratee, callback) { + function reject$2(eachfn, arr, _iteratee, callback) { const iteratee = wrapAsync(_iteratee); return _filter(eachfn, arr, (value, cb) => { iteratee(value, (err, v) => { @@ -4485,10 +4487,10 @@ * } * */ - function reject$1 (coll, iteratee, callback) { - return reject(eachOf$1, coll, iteratee, callback) + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) } - var reject$2 = awaitify(reject$1, 3); + var reject$1 = awaitify(reject, 3); /** * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a @@ -4511,7 +4513,7 @@ * @returns {Promise} a promise, if no callback is passed */ function rejectLimit (coll, limit, iteratee, callback) { - return reject(eachOfLimit(limit), coll, iteratee, callback) + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) } var rejectLimit$1 = awaitify(rejectLimit, 4); @@ -4534,11 +4536,11 @@ * @returns {Promise} a promise, if no callback is passed */ function rejectSeries (coll, iteratee, callback) { - return reject(eachOfSeries$1, coll, iteratee, callback) + return reject$2(eachOfSeries$1, coll, iteratee, callback) } var rejectSeries$1 = awaitify(rejectSeries, 3); - function constant$1(value) { + function constant(value) { return function () { return value; } @@ -4635,7 +4637,7 @@ function retry(opts, task, callback) { var options = { times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) + intervalFunc: constant(DEFAULT_INTERVAL) }; if (arguments.length < 3 && typeof opts === 'function') { @@ -4676,7 +4678,7 @@ acc.intervalFunc = typeof t.interval === 'function' ? t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); + constant(+t.interval || DEFAULT_INTERVAL); acc.errorFilter = t.errorFilter; } else if (typeof t === 'number' || typeof t === 'string') { @@ -4907,7 +4909,7 @@ * */ function series(tasks, callback) { - return parallel(eachOfSeries$1, tasks, callback); + return _parallel(eachOfSeries$1, tasks, callback); } /** @@ -5035,7 +5037,7 @@ * @returns {Promise} a promise, if no callback provided */ function someLimit(coll, limit, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) } var someLimit$1 = awaitify(someLimit, 4); @@ -5629,7 +5631,7 @@ * @method * @category Control Flow * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). + * execution of `iteratee`. Invoked with (callback). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test @@ -5841,20 +5843,21 @@ * @static */ + var index = { apply, - applyEach: applyEach$1, + applyEach, applyEachSeries, asyncify, auto, autoInject, - cargo, - cargoQueue: cargo$1, + cargo: cargo$1, + cargoQueue: cargo, compose, concat: concat$1, concatLimit: concatLimit$1, concatSeries: concatSeries$1, - constant, + constant: constant$1, detect: detect$1, detectLimit: detectLimit$1, detectSeries: detectSeries$1, @@ -5862,9 +5865,9 @@ doUntil, doWhilst: doWhilst$1, each, - eachLimit: eachLimit$2, + eachLimit: eachLimit$1, eachOf: eachOf$1, - eachOfLimit: eachOfLimit$2, + eachOfLimit: eachOfLimit$1, eachOfSeries: eachOfSeries$1, eachSeries: eachSeries$1, ensureAsync, @@ -5887,16 +5890,16 @@ mapValuesSeries, memoize, nextTick, - parallel: parallel$1, + parallel, parallelLimit, priorityQueue, - queue: queue$1, + queue, race: race$1, reduce: reduce$1, reduceRight, reflect, reflectAll, - reject: reject$2, + reject: reject$1, rejectLimit: rejectLimit$1, rejectSeries: rejectSeries$1, retry, @@ -5934,10 +5937,10 @@ flatMapSeries: concatSeries$1, forEach: each, forEachSeries: eachSeries$1, - forEachLimit: eachLimit$2, + forEachLimit: eachLimit$1, forEachOf: eachOf$1, forEachOfSeries: eachOfSeries$1, - forEachOfLimit: eachOfLimit$2, + forEachOfLimit: eachOfLimit$1, inject: reduce$1, foldl: reduce$1, foldr: reduceRight, @@ -5949,30 +5952,38 @@ doDuring: doWhilst$1 }; - exports.default = index; + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; exports.apply = apply; - exports.applyEach = applyEach$1; + exports.applyEach = applyEach; exports.applyEachSeries = applyEachSeries; exports.asyncify = asyncify; exports.auto = auto; exports.autoInject = autoInject; - exports.cargo = cargo; - exports.cargoQueue = cargo$1; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; exports.compose = compose; exports.concat = concat$1; exports.concatLimit = concatLimit$1; exports.concatSeries = concatSeries$1; - exports.constant = constant; + exports.constant = constant$1; + exports.default = index; exports.detect = detect$1; exports.detectLimit = detectLimit$1; exports.detectSeries = detectSeries$1; exports.dir = dir; + exports.doDuring = doWhilst$1; exports.doUntil = doUntil; exports.doWhilst = doWhilst$1; + exports.during = whilst$1; exports.each = each; - exports.eachLimit = eachLimit$2; + exports.eachLimit = eachLimit$1; exports.eachOf = eachOf$1; - exports.eachOfLimit = eachOfLimit$2; + exports.eachOfLimit = eachOfLimit$1; exports.eachOfSeries = eachOfSeries$1; exports.eachSeries = eachSeries$1; exports.ensureAsync = ensureAsync; @@ -5982,10 +5993,25 @@ exports.filter = filter$1; exports.filterLimit = filterLimit$1; exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; exports.forever = forever$1; exports.groupBy = groupBy; exports.groupByLimit = groupByLimit$1; exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; exports.log = log; exports.map = map$1; exports.mapLimit = mapLimit$1; @@ -5995,20 +6021,23 @@ exports.mapValuesSeries = mapValuesSeries; exports.memoize = memoize; exports.nextTick = nextTick; - exports.parallel = parallel$1; + exports.parallel = parallel; exports.parallelLimit = parallelLimit; exports.priorityQueue = priorityQueue; - exports.queue = queue$1; + exports.queue = queue; exports.race = race$1; exports.reduce = reduce$1; exports.reduceRight = reduceRight; exports.reflect = reflect; exports.reflectAll = reflectAll; - exports.reject = reject$2; + exports.reject = reject$1; exports.rejectLimit = rejectLimit$1; exports.rejectSeries = rejectSeries$1; exports.retry = retry; exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; exports.seq = seq; exports.series = series; exports.setImmediate = setImmediate$1; @@ -6026,34 +6055,8 @@ exports.until = until; exports.waterfall = waterfall$1; exports.whilst = whilst$1; - exports.all = every$1; - exports.allLimit = everyLimit$1; - exports.allSeries = everySeries$1; - exports.any = some$1; - exports.anyLimit = someLimit$1; - exports.anySeries = someSeries$1; - exports.find = detect$1; - exports.findLimit = detectLimit$1; - exports.findSeries = detectSeries$1; - exports.flatMap = concat$1; - exports.flatMapLimit = concatLimit$1; - exports.flatMapSeries = concatSeries$1; - exports.forEach = each; - exports.forEachSeries = eachSeries$1; - exports.forEachLimit = eachLimit$2; - exports.forEachOf = eachOf$1; - exports.forEachOfSeries = eachOfSeries$1; - exports.forEachOfLimit = eachOfLimit$2; - exports.inject = reduce$1; - exports.foldl = reduce$1; - exports.foldr = reduceRight; - exports.select = filter$1; - exports.selectLimit = filterLimit$1; - exports.selectSeries = filterSeries$1; exports.wrapSync = asyncify; - exports.during = whilst$1; - exports.doDuring = doWhilst$1; Object.defineProperty(exports, '__esModule', { value: true }); -}))); +})); diff --git a/node_modules/async/dist/async.min.js b/node_modules/async/dist/async.min.js index a12963b..f5c464e 100644 --- a/node_modules/async/dist/async.min.js +++ b/node_modules/async/dist/async.min.js @@ -1 +1 @@ -(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t(e.async={})})(this,function(e){'use strict';function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return u(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&e.message?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){_e(t=>{throw t},e)}}function u(e){return"AsyncFunction"===e[Symbol.toStringTag]}function d(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function c(e){if("function"!=typeof e)throw new Error("expected a function");return u(e)?r(e):e}function o(e,t=e.length){if(!t)throw new Error("arity is undefined");return function(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1{c(e).apply(i,n.concat(t))},a)});return a}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=c(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function(){return++t=t||d||l||(d=!0,e.next().then(({value:e,done:t})=>{if(!(u||l))return d=!1,t?(l=!0,void(0>=p&&a(null))):void(p++,n(e,c,r),c++,i())}).catch(s))}function r(e,t){return p-=1,u?void 0:e?s(e):!1===e?(l=!0,void(u=!0)):t===be||l&&0>=p?(l=!0,a(null)):void i()}function s(e){u||(d=!1,l=!0,a(e))}let l=!1,u=!1,d=!1,p=0,c=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===be)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i{t=e,n=a}),e}function A(e,t,n){function a(e,t){g.push(()=>l(e,t))}function i(){if(!h){if(0===g.length&&0===o)return n(null,p);for(;g.length&&oe()),i()}function l(e,t){if(!f){var a=L((t,...a)=>{if(o--,!1===t)return void(h=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(p).forEach(e=>{i[e]=p[e]}),i[e]=a,f=!0,y=Object.create(null),h)return;n(t,i)}else p[e]=a,s(e)});o++;var i=c(t[t.length-1]);1{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||b());var d=Object.keys(e).length;if(!d)return n(null);t||(t=d);var p={},o=0,h=!1,f=!1,y=Object.create(null),g=[],k=[],v={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void k.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void k.push(t)):void(v[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),function(){for(var e,t=0;k.length;)e=k.pop(),t++,u(e).forEach(e=>{0==--v[e]&&k.push(e)});if(t!==d)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}(),i(),n[Ce]}function I(e){let t="",n=0,a=e.indexOf("*/");for(;ne.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),c(r)(...n)}var i,r=e[t],s=u(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l=k._createTaskItem(e,n?i:a||i);if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,_e(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function u(e){return function(t,...n){o-=1;for(var a=0,r=e.length;as("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=c(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,_createTaskItem(e,t){return{data:e,callback:t}},*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?d(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const u=c(i);n(a,(n,a,i)=>{u(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>c(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=c(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return u(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?_e(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,c(n),a)}function G(e,t,n){return ut(e,1/0,t,n)}function W(e,t,n){return ut(e,1,t,n)}function H(e,t,n){return pt(e,1/0,t,n)}function J(e,t,n){return pt(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=c(e),l=n((e,n)=>{var u=t(...e);u in a?_e(()=>n(null,...a[u])):u in r?r[u].push(n):(r[u]=[n],s(...e,(e,...t)=>{e||(a[u]=t);var n=r[u];delete r[u];for(var s=0,d=n.length;s{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount({data:e,priority:t})):{data:e,priority:t}}var a=$(e,t),{push:i,pushAsync:r}=a;return a._tasks=new ht,a._createTaskItem=({data:e,priority:t},n)=>({data:e,priority:t,callback:n}),a.push=function(e,t=0,a){return i(n(e,t),a)},a.pushAsync=function(e,t=0,a){return r(n(e,t),a)},delete a.unshift,delete a.unshiftAsync,a}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=c(e);return n(function(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=c(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function ue(e){return function(){return e}}function de(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(n=t||b(),t=e):(pe(i,e),n=n||b()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=c(t),s=1;return a(),n[Ce]}function pe(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:ue(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function ce(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;u(t)&&(a+=1);var i=c(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length{var s,l=!1;n.push((...e)=>{l||(r(...e),clearTimeout(s))}),s=setTimeout(function(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),l=!0,r(n)},t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=c(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||b());var i=c(n);return Me(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=c(e);return _t(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var _e=i(xe);const be={};var Ae=e=>(t,n,a)=>{function i(e,t){if(!u)if(c-=1,e)l=!0,a(e);else if(!1===e)l=!0,u=!0;else{if(t===be||l&&0>=c)return l=!0,a(null);o||r()}}function r(){for(o=!0;c=c&&a(null));c+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(d(t))return E(t,e,n,a);if(p(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,u=!1,c=0,o=!1;r()},Ie=o(function(e,t,n,a){return Ae(t)(e,c(n),a)},4),Me=o(function(e,t,n){var a=y(e)?O:_;return a(e,c(t),n)},3),je=o(function(e,t,n){return f(Me,e,t,n)},3),we=h(je),Be=o(function(e,t,n){return Ie(e,1,t,n)},3),Te=o(function(e,t,n){return f(Be,e,t,n)},3),Fe=h(Te);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,Re=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function(e,t,n,a){a=m(a);var r=c(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function(e,t,n,a){return f(Ae(t),e,n,a)},4),Qe=o(function(e,t,n,a){var i=c(n);return De(e,t,(e,t)=>{i(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;re,(e,t)=>t)(Me,e,t,n)},3),He=o(function(e,t,n,a){return z(e=>e,(e,t)=>t)(Ae(t),e,n,a)},4),Je=o(function(e,t,n){return z(e=>e,(e,t)=>t)(Ae(1),e,t,n)},3),Ke=N("dir"),Xe=o(function(e,t,n){function a(e,...t){return e?n(e):void(!1===e||(r=t,l(...t,i)))}function i(e,t){return e?n(e):!1===e?void 0:t?void s(a):n(null,...r)}n=L(n);var r,s=c(e),l=c(t);return i(null,!0)},3),Ze=o(function(e,t,n){return Me(e,Y(c(t)),n)},3),$e=o(function(e,t,n,a){return Ae(t)(e,Y(c(n)),a)},4),et=o(function(e,t,n){return $e(e,1,t,n)},3),tt=o(function(e,t,n){return z(e=>!e,e=>!e)(Me,e,t,n)},3),nt=o(function(e,t,n,a){return z(e=>!e,e=>!e)(Ae(t),e,n,a)},4),at=o(function(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function(e,t,n){return U(Me,e,t,n)},3),rt=o(function(e,t,n,a){return U(Ae(t),e,n,a)},4),st=o(function(e,t,n){return U(Be,e,t,n)},3),lt=o(function(e,t){function n(e){return e?a(e):void(!1===e||i(n))}var a=L(t),i=c(q(e));return n()},2),ut=o(function(e,t,n,a){var i=c(n);return De(e,t,(e,t)=>{i(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s{r(e,t,(e,a)=>e?n(e):void(i[t]=a,n(e)))},e=>a(e,i))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var ct=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{c(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0e)(Me,e,t,n)},3),xt=o(function(e,t,n,a){return z(Boolean,e=>e)(Ae(t),e,n,a)},4),Lt=o(function(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function(e,t,n){function a(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var i=c(t);return je(e,(e,t)=>{i(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(a).map(e=>e.value)))},3),Ot=o(function(e,t){var n,a=null;return et(e,(e,t)=>{c(e)((e,...i)=>!1===e?t(e):void(2>i.length?[n]=i:n=i,a=e,t(e?null:{})))},()=>t(a,n))}),_t=o(function(e,t,n){function a(e,...t){if(e)return n(e);l=t;!1===e||s(i)}function i(e,t){return e?n(e):!1===e?void 0:t?void r(a):n(null,...l)}n=L(n);var r=c(t),s=c(e),l=[];return s(i)},3),bt=o(function(e,t){function n(t){var n=c(e[i++]);n(...t,L(a))}function a(a,...r){return!1===a?void 0:a||i===e.length?t(a,...r):void n(r)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var i=0;n([])});e.default={apply:t,applyEach:we,applyEachSeries:Fe,asyncify:r,auto:A,autoInject:j,cargo:T,cargoQueue:F,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Me,eachOfLimit:Ie,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:ut,groupBySeries:W,log:dt,map:je,mapLimit:De,mapSeries:Te,mapValues:H,mapValuesLimit:pt,mapValuesSeries:J,memoize:K,nextTick:ct,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:de,retryable:ce,seq:C,series:oe,setImmediate:_e,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:bt,whilst:_t,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Me,forEachOfSeries:Be,forEachOfLimit:Ie,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:_t,doDuring:Xe},e.apply=t,e.applyEach=we,e.applyEachSeries=Fe,e.asyncify=r,e.auto=A,e.autoInject=j,e.cargo=T,e.cargoQueue=F,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doUntil=V,e.doWhilst=Xe,e.each=Ze,e.eachLimit=$e,e.eachOf=Me,e.eachOfLimit=Ie,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.forever=lt,e.groupBy=G,e.groupByLimit=ut,e.groupBySeries=W,e.log=dt,e.map=je,e.mapLimit=De,e.mapSeries=Te,e.mapValues=H,e.mapValuesLimit=pt,e.mapValuesSeries=J,e.memoize=K,e.nextTick=ct,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=de,e.retryable=ce,e.seq=C,e.series=oe,e.setImmediate=_e,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=bt,e.whilst=_t,e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.forEach=Ze,e.forEachSeries=et,e.forEachLimit=$e,e.forEachOf=Me,e.forEachOfSeries=Be,e.forEachOfLimit=Ie,e.inject=qe,e.foldl=qe,e.foldr=ie,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.wrapSync=r,e.during=_t,e.doDuring=Xe,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file +(function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(e="undefined"==typeof globalThis?e||self:globalThis,t(e.async={}))})(this,function(e){"use strict";function t(e,...t){return(...n)=>e(...t,...n)}function n(e){return function(...t){var n=t.pop();return e.call(this,t,n)}}function a(e){setTimeout(e,0)}function i(e){return(t,...n)=>e(()=>t(...n))}function r(e){return d(e)?function(...t){const n=t.pop(),a=e.apply(this,t);return s(a,n)}:n(function(t,n){var a;try{a=e.apply(this,t)}catch(t){return n(t)}return a&&"function"==typeof a.then?s(a,n):void n(null,a)})}function s(e,t){return e.then(e=>{l(t,null,e)},e=>{l(t,e&&(e instanceof Error||e.message)?e:new Error(e))})}function l(e,t,n){try{e(t,n)}catch(e){_e(t=>{throw t},e)}}function d(e){return"AsyncFunction"===e[Symbol.toStringTag]}function u(e){return"AsyncGenerator"===e[Symbol.toStringTag]}function p(e){return"function"==typeof e[Symbol.asyncIterator]}function c(e){if("function"!=typeof e)throw new Error("expected a function");return d(e)?r(e):e}function o(e,t){function n(...n){return"function"==typeof n[t-1]?e.apply(this,n):new Promise((a,i)=>{n[t-1]=(e,...t)=>e?i(e):void a(1{c(e).apply(i,n.concat(t))},a)});return i}}function f(e,t,n,a){t=t||[];var i=[],r=0,s=c(n);return e(t,(e,t,n)=>{var a=r++;s(e,(e,t)=>{i[a]=t,n(e)})},e=>{a(e,i)})}function y(e){return e&&"number"==typeof e.length&&0<=e.length&&0==e.length%1}function m(e){function t(...t){if(null!==e){var n=e;e=null,n.apply(this,t)}}return Object.assign(t,e),t}function g(e){return e[Symbol.iterator]&&e[Symbol.iterator]()}function k(e){var t=-1,n=e.length;return function a(){return++t=t||u||l||(u=!0,e.next().then(({value:e,done:t})=>{if(!(d||l))return u=!1,t?(l=!0,void(0>=p&&a(null))):void(p++,n(e,c,r),c++,i())}).catch(s))}function r(e,t){return p-=1,d?void 0:e?s(e):!1===e?(l=!0,void(d=!0)):t===be||l&&0>=p?(l=!0,a(null)):void i()}function s(e){d||(u=!1,l=!0,a(e))}let l=!1,d=!1,u=!1,p=0,c=0;i()}function O(e,t,n){function a(e,t){!1===e&&(l=!0);!0===l||(e?n(e):(++r===s||t===be)&&n(null))}n=m(n);var i=0,r=0,{length:s}=e,l=!1;for(0===s&&n(null);i{t=e,n=a}),e}function A(e,t,n){function a(e,t){k.push(()=>l(e,t))}function i(){if(!f){if(0===k.length&&0===h)return n(null,o);for(;k.length&&he()),i()}function l(e,t){if(!y){var a=L((t,...a)=>{if(h--,!1===t)return void(f=!0);if(2>a.length&&([a]=a),t){var i={};if(Object.keys(o).forEach(e=>{i[e]=o[e]}),i[e]=a,y=!0,g=Object.create(null),f)return;n(t,i)}else o[e]=a,s(e)});h++;var i=c(t[t.length-1]);1{0==--S[e]&&v.push(e)});if(t!==p)throw new Error("async.auto cannot execute tasks due to a recursive dependency")}function u(t){var n=[];return Object.keys(e).forEach(a=>{const i=e[a];Array.isArray(i)&&0<=i.indexOf(t)&&n.push(a)}),n}"number"!=typeof t&&(n=t,t=null),n=m(n||b());var p=Object.keys(e).length;if(!p)return n(null);t||(t=p);var o={},h=0,f=!1,y=!1,g=Object.create(null),k=[],v=[],S={};return Object.keys(e).forEach(t=>{var n=e[t];if(!Array.isArray(n))return a(t,[n]),void v.push(t);var i=n.slice(0,n.length-1),s=i.length;return 0===s?(a(t,n),void v.push(t)):void(S[t]=s,i.forEach(l=>{if(!e[l])throw new Error("async.auto task `"+t+"` has a non-existent dependency `"+l+"` in "+i.join(", "));r(l,()=>{s--,0===s&&a(t,n)})}))}),d(),i(),n[Ce]}function I(e){let t="",n=0,a=e.indexOf("*/");for(;ne.replace(Ne,"").trim())}function j(e,t){var n={};return Object.keys(e).forEach(t=>{function a(e,t){var n=i.map(t=>e[t]);n.push(t),c(r)(...n)}var i,r=e[t],s=d(r),l=!s&&1===r.length||s&&0===r.length;if(Array.isArray(r))i=[...r],r=i.pop(),n[t]=i.concat(0{r(e,n),t(...a)};f[e].push(n)}function r(e,t){return e?t?void(f[e]=f[e].filter(e=>e!==t)):f[e]=[]:Object.keys(f).forEach(e=>f[e]=[])}function s(e,...t){f[e].forEach(e=>e(...t))}function l(e,t,n,a){function i(e,...t){return e?n?s(e):r():1>=t.length?r(t[0]):void r(t)}if(null!=a&&"function"!=typeof a)throw new Error("task callback must be a function");k.started=!0;var r,s,l=k._createTaskItem(e,n?i:a||i);if(t?k._tasks.unshift(l):k._tasks.push(l),y||(y=!0,_e(()=>{y=!1,k.process()})),n||!a)return new Promise((e,t)=>{r=e,s=t})}function d(e){return function(t,...n){o-=1;for(var a=0,r=e.length;as("drain")),!0)}if(null==t)t=1;else if(0===t)throw new RangeError("Concurrency must not be zero");var p=c(e),o=0,h=[];const f={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};var y=!1;const m=e=>t=>t?void(r(e),a(e,t)):new Promise((t,n)=>{i(e,(e,a)=>e?n(e):void t(a))});var g=!1,k={_tasks:new Ve,_createTaskItem(e,t){return{data:e,callback:t}},*[Symbol.iterator](){yield*k._tasks[Symbol.iterator]()},concurrency:t,payload:n,buffer:t/4,started:!1,paused:!1,push(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!1,t)):l(e,!1,!1,t)},pushAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!1,!0,t)):l(e,!1,!0,t)},kill(){r(),k._tasks.empty()},unshift(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!1,t)):l(e,!0,!1,t)},unshiftAsync(e,t){return Array.isArray(e)?u(e)?void 0:e.map(e=>l(e,!0,!0,t)):l(e,!0,!0,t)},remove(e){k._tasks.remove(e)},process(){var e=Math.min;if(!g){for(g=!0;!k.paused&&o{t.apply(n,e.concat((e,...t)=>{a(e,t)}))},(e,t)=>a(e,...t)),a[Ce]}}function P(...e){return C(...e.reverse())}function R(...e){return function(...t){var n=t.pop();return n(null,...e)}}function z(e,t){return(n,a,i,r)=>{var s,l=!1;const d=c(i);n(a,(n,a,i)=>{d(n,(a,r)=>a||!1===a?i(a):e(r)&&!s?(l=!0,s=t(!0,n),i(null,be)):void i())},e=>e?r(e):void r(null,l?s:t(!1)))}}function N(e){return(t,...n)=>c(t)(...n,(t,...n)=>{"object"==typeof console&&(t?console.error&&console.error(t):console[e]&&n.forEach(t=>console[e](t)))})}function V(e,t,n){const a=c(t);return Xe(e,(...e)=>{const t=e.pop();a(...e,(e,n)=>t(e,!n))},n)}function Y(e){return(t,n,a)=>e(t,a)}function q(e){return d(e)?e:function(...t){var n=t.pop(),a=!0;t.push((...e)=>{a?_e(()=>n(...e)):n(...e)}),e.apply(this,t),a=!1}}function D(e,t,n,a){var r=Array(t.length);e(t,(e,t,a)=>{n(e,(e,n)=>{r[t]=!!n,a(e)})},e=>{if(e)return a(e);for(var n=[],s=0;s{n(e,(n,r)=>n?a(n):void(r&&i.push({index:t,value:e}),a(n)))},e=>e?a(e):void a(null,i.sort((e,t)=>e.index-t.index).map(e=>e.value)))}function U(e,t,n,a){var i=y(t)?D:Q;return i(e,t,c(n),a)}function G(e,t,n){return dt(e,1/0,t,n)}function W(e,t,n){return dt(e,1,t,n)}function H(e,t,n){return pt(e,1/0,t,n)}function J(e,t,n){return pt(e,1,t,n)}function K(e,t=e=>e){var a=Object.create(null),r=Object.create(null),s=c(e),l=n((e,n)=>{var d=t(...e);d in a?_e(()=>n(null,...a[d])):d in r?r[d].push(n):(r[d]=[n],s(...e,(e,...t)=>{e||(a[d]=t);var n=r[d];delete r[d];for(var s=0,u=n.length;s{n(e[0],t)},t,1)}function ee(e){return(e<<1)+1}function te(e){return(e+1>>1)-1}function ne(e,t){return e.priority===t.priority?e.pushCount({data:e,priority:t})):{data:e,priority:t}}var a=$(e,t),{push:i,pushAsync:r}=a;return a._tasks=new ht,a._createTaskItem=({data:e,priority:t},n)=>({data:e,priority:t,callback:n}),a.push=function(e,t=0,a){return i(n(e,t),a)},a.pushAsync=function(e,t=0,a){return r(n(e,t),a)},delete a.unshift,delete a.unshiftAsync,a}function ie(e,t,n,a){var i=[...e].reverse();return qe(i,t,n,a)}function re(e){var t=c(e);return n(function a(e,n){return e.push((e,...t)=>{let a={};if(e&&(a.error=e),0=t.length&&([i]=t),a.value=i}n(null,a)}),t.apply(this,e)})}function se(e){var t;return Array.isArray(e)?t=e.map(re):(t={},Object.keys(e).forEach(n=>{t[n]=re.call(this,e[n])})),t}function le(e,t,n,a){const i=c(n);return U(e,t,(e,t)=>{i(e,(e,n)=>{t(e,!n)})},a)}function de(e){return function(){return e}}function ue(e,t,n){function a(){r((e,...t)=>{!1===e||(e&&s++arguments.length&&"function"==typeof e?(n=t||b(),t=e):(pe(i,e),n=n||b()),"function"!=typeof t)throw new Error("Invalid arguments for async.retry");var r=c(t),s=1;return a(),n[Ce]}function pe(e,n){if("object"==typeof n)e.times=+n.times||kt,e.intervalFunc="function"==typeof n.interval?n.interval:de(+n.interval||vt),e.errorFilter=n.errorFilter;else if("number"==typeof n||"string"==typeof n)e.times=+n||kt;else throw new Error("Invalid arguments for async.retry")}function ce(e,t){t||(t=e,e=null);let a=e&&e.arity||t.length;d(t)&&(a+=1);var i=c(t);return n((t,n)=>{function r(e){i(...t,e)}return(t.length{function s(){var t=e.name||"anonymous",n=new Error("Callback function \""+t+"\" timed out.");n.code="ETIMEDOUT",a&&(n.info=a),d=!0,r(n)}var l,d=!1;n.push((...e)=>{d||(r(...e),clearTimeout(l))}),l=setTimeout(s,t),i(...n)})}function fe(e){for(var t=Array(e);e--;)t[e]=e;return t}function ye(e,t,n,a){var i=c(n);return De(fe(e),t,i,a)}function me(e,t,n){return ye(e,1/0,t,n)}function ge(e,t,n){return ye(e,1,t,n)}function ke(e,t,n,a){3>=arguments.length&&"function"==typeof t&&(a=n,n=t,t=Array.isArray(e)?[]:{}),a=m(a||b());var i=c(n);return Me(e,(e,n,a)=>{i(t,e,n,a)},e=>a(e,t)),a[Ce]}function ve(e){return(...t)=>(e.unmemoized||e)(...t)}function Se(e,t,n){const a=c(e);return _t(e=>a((t,n)=>e(t,!n)),t,n)}var xe,Le="function"==typeof queueMicrotask&&queueMicrotask,Ee="function"==typeof setImmediate&&setImmediate,Oe="object"==typeof process&&"function"==typeof process.nextTick;xe=Le?queueMicrotask:Ee?setImmediate:Oe?process.nextTick:a;var _e=i(xe);var be={},Ae=e=>(t,n,a)=>{function i(e,t){if(!d)if(c-=1,e)l=!0,a(e);else if(!1===e)l=!0,d=!0;else{if(t===be||l&&0>=c)return l=!0,a(null);o||r()}}function r(){for(o=!0;c=c&&a(null));c+=1,n(t.value,t.key,L(i))}o=!1}if(a=m(a),0>=e)throw new RangeError("concurrency limit cannot be less than 1");if(!t)return a(null);if(u(t))return E(t,e,n,a);if(p(t))return E(t[Symbol.asyncIterator](),e,n,a);var s=x(t),l=!1,d=!1,c=0,o=!1;r()},Ie=o(function i(e,t,n,a){return Ae(t)(e,c(n),a)},4),Me=o(function a(e,t,n){var i=y(e)?O:_;return i(e,c(t),n)},3),je=o(function a(e,t,n){return f(Me,e,t,n)},3),we=h(je),Be=o(function a(e,t,n){return Ie(e,1,t,n)},3),Te=o(function a(e,t,n){return f(Be,e,t,n)},3),Fe=h(Te);const Ce=Symbol("promiseCallback");var Pe=/^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/,Re=/^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/,ze=/,/,Ne=/(=.+)?(\s*)$/;class Ve{constructor(){this.head=this.tail=null,this.length=0}removeLink(e){return e.prev?e.prev.next=e.next:this.head=e.next,e.next?e.next.prev=e.prev:this.tail=e.prev,e.prev=e.next=null,this.length-=1,e}empty(){for(;this.head;)this.shift();return this}insertAfter(e,t){t.prev=e,t.next=e.next,e.next?e.next.prev=t:this.tail=t,e.next=t,this.length+=1}insertBefore(e,t){t.prev=e.prev,t.next=e,e.prev?e.prev.next=t:this.head=t,e.prev=t,this.length+=1}unshift(e){this.head?this.insertBefore(this.head,e):w(this,e)}push(e){this.tail?this.insertAfter(this.tail,e):w(this,e)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){for(var e=this.head;e;)yield e.data,e=e.next}remove(e){for(var t=this.head;t;){var{next:n}=t;e(t)&&this.removeLink(t),t=n}return this}}var Ye,qe=o(function i(e,t,n,a){a=m(a);var r=c(n);return Be(e,(e,n,a)=>{r(t,e,(e,n)=>{t=n,a(e)})},e=>a(e,t))},4),De=o(function i(e,t,n,a){return f(Ae(t),e,n,a)},4),Qe=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(e,...n)=>e?t(e):t(e,n))},(e,t)=>{for(var n=[],r=0;re,(e,t)=>t)(Me,e,t,n)},3),He=o(function i(e,t,n,a){return z(e=>e,(e,t)=>t)(Ae(t),e,n,a)},4),Je=o(function a(e,t,n){return z(e=>e,(e,t)=>t)(Ae(1),e,t,n)},3),Ke=N("dir"),Xe=o(function a(e,t,n){function i(e,...t){return e?n(e):void(!1===e||(s=t,d(...t,r)))}function r(e,t){return e?n(e):!1===e?void 0:t?void l(i):n(null,...s)}n=L(n);var s,l=c(e),d=c(t);return r(null,!0)},3),Ze=o(function a(e,t,n){return Me(e,Y(c(t)),n)},3),$e=o(function i(e,t,n,a){return Ae(t)(e,Y(c(n)),a)},4),et=o(function a(e,t,n){return $e(e,1,t,n)},3),tt=o(function a(e,t,n){return z(e=>!e,e=>!e)(Me,e,t,n)},3),nt=o(function i(e,t,n,a){return z(e=>!e,e=>!e)(Ae(t),e,n,a)},4),at=o(function a(e,t,n){return z(e=>!e,e=>!e)(Be,e,t,n)},3),it=o(function a(e,t,n){return U(Me,e,t,n)},3),rt=o(function i(e,t,n,a){return U(Ae(t),e,n,a)},4),st=o(function a(e,t,n){return U(Be,e,t,n)},3),lt=o(function n(e,t){function a(e){return e?i(e):void(!1===e||r(a))}var i=L(t),r=c(q(e));return a()},2),dt=o(function i(e,t,n,a){var r=c(n);return De(e,t,(e,t)=>{r(e,(n,a)=>n?t(n):t(n,{key:a,val:e}))},(e,t)=>{for(var n={},{hasOwnProperty:r}=Object.prototype,s=0;s{s(e,t,(e,a)=>e?n(e):void(r[t]=a,n(e)))},e=>a(e,r))},4);Ye=Oe?process.nextTick:Ee?setImmediate:a;var ct=i(Ye),ot=o((e,t,n)=>{var a=y(t)?[]:{};e(t,(e,t,n)=>{c(e)((e,...i)=>{2>i.length&&([i]=i),a[t]=i,n(e)})},e=>n(e,a))},3);class ht{constructor(){this.heap=[],this.pushCount=Number.MIN_SAFE_INTEGER}get length(){return this.heap.length}empty(){return this.heap=[],this}percUp(e){for(let n;0e)(Me,e,t,n)},3),xt=o(function i(e,t,n,a){return z(Boolean,e=>e)(Ae(t),e,n,a)},4),Lt=o(function a(e,t,n){return z(Boolean,e=>e)(Be,e,t,n)},3),Et=o(function a(e,t,n){function i(e,t){var n=e.criteria,a=t.criteria;return na?1:0}var r=c(t);return je(e,(e,t)=>{r(e,(n,a)=>n?t(n):void t(n,{value:e,criteria:a}))},(e,t)=>e?n(e):void n(null,t.sort(i).map(e=>e.value)))},3),Ot=o(function n(e,t){var a,i=null;return et(e,(e,t)=>{c(e)((e,...n)=>!1===e?t(e):void(2>n.length?[a]=n:a=n,i=e,t(e?null:{})))},()=>t(i,a))}),_t=o(function a(e,t,n){function i(e,...t){if(e)return n(e);d=t;!1===e||l(r)}function r(e,t){return e?n(e):!1===e?void 0:t?void s(i):n(null,...d)}n=L(n);var s=c(t),l=c(e),d=[];return l(r)},3),bt=o(function n(e,t){function a(t){var n=c(e[r++]);n(...t,L(i))}function i(n,...i){return!1===n?void 0:n||r===e.length?t(n,...i):void a(i)}if(t=m(t),!Array.isArray(e))return t(new Error("First argument to waterfall must be an array of functions"));if(!e.length)return t();var r=0;a([])});e.all=tt,e.allLimit=nt,e.allSeries=at,e.any=St,e.anyLimit=xt,e.anySeries=Lt,e.apply=t,e.applyEach=we,e.applyEachSeries=Fe,e.asyncify=r,e.auto=A,e.autoInject=j,e.cargo=T,e.cargoQueue=F,e.compose=P,e.concat=Ue,e.concatLimit=Qe,e.concatSeries=Ge,e.constant=R,e.default={apply:t,applyEach:we,applyEachSeries:Fe,asyncify:r,auto:A,autoInject:j,cargo:T,cargoQueue:F,compose:P,concat:Ue,concatLimit:Qe,concatSeries:Ge,constant:R,detect:We,detectLimit:He,detectSeries:Je,dir:Ke,doUntil:V,doWhilst:Xe,each:Ze,eachLimit:$e,eachOf:Me,eachOfLimit:Ie,eachOfSeries:Be,eachSeries:et,ensureAsync:q,every:tt,everyLimit:nt,everySeries:at,filter:it,filterLimit:rt,filterSeries:st,forever:lt,groupBy:G,groupByLimit:dt,groupBySeries:W,log:ut,map:je,mapLimit:De,mapSeries:Te,mapValues:H,mapValuesLimit:pt,mapValuesSeries:J,memoize:K,nextTick:ct,parallel:X,parallelLimit:Z,priorityQueue:ae,queue:$,race:ft,reduce:qe,reduceRight:ie,reflect:re,reflectAll:se,reject:yt,rejectLimit:mt,rejectSeries:gt,retry:ue,retryable:ce,seq:C,series:oe,setImmediate:_e,some:St,someLimit:xt,someSeries:Lt,sortBy:Et,timeout:he,times:me,timesLimit:ye,timesSeries:ge,transform:ke,tryEach:Ot,unmemoize:ve,until:Se,waterfall:bt,whilst:_t,all:tt,allLimit:nt,allSeries:at,any:St,anyLimit:xt,anySeries:Lt,find:We,findLimit:He,findSeries:Je,flatMap:Ue,flatMapLimit:Qe,flatMapSeries:Ge,forEach:Ze,forEachSeries:et,forEachLimit:$e,forEachOf:Me,forEachOfSeries:Be,forEachOfLimit:Ie,inject:qe,foldl:qe,foldr:ie,select:it,selectLimit:rt,selectSeries:st,wrapSync:r,during:_t,doDuring:Xe},e.detect=We,e.detectLimit=He,e.detectSeries=Je,e.dir=Ke,e.doDuring=Xe,e.doUntil=V,e.doWhilst=Xe,e.during=_t,e.each=Ze,e.eachLimit=$e,e.eachOf=Me,e.eachOfLimit=Ie,e.eachOfSeries=Be,e.eachSeries=et,e.ensureAsync=q,e.every=tt,e.everyLimit=nt,e.everySeries=at,e.filter=it,e.filterLimit=rt,e.filterSeries=st,e.find=We,e.findLimit=He,e.findSeries=Je,e.flatMap=Ue,e.flatMapLimit=Qe,e.flatMapSeries=Ge,e.foldl=qe,e.foldr=ie,e.forEach=Ze,e.forEachLimit=$e,e.forEachOf=Me,e.forEachOfLimit=Ie,e.forEachOfSeries=Be,e.forEachSeries=et,e.forever=lt,e.groupBy=G,e.groupByLimit=dt,e.groupBySeries=W,e.inject=qe,e.log=ut,e.map=je,e.mapLimit=De,e.mapSeries=Te,e.mapValues=H,e.mapValuesLimit=pt,e.mapValuesSeries=J,e.memoize=K,e.nextTick=ct,e.parallel=X,e.parallelLimit=Z,e.priorityQueue=ae,e.queue=$,e.race=ft,e.reduce=qe,e.reduceRight=ie,e.reflect=re,e.reflectAll=se,e.reject=yt,e.rejectLimit=mt,e.rejectSeries=gt,e.retry=ue,e.retryable=ce,e.select=it,e.selectLimit=rt,e.selectSeries=st,e.seq=C,e.series=oe,e.setImmediate=_e,e.some=St,e.someLimit=xt,e.someSeries=Lt,e.sortBy=Et,e.timeout=he,e.times=me,e.timesLimit=ye,e.timesSeries=ge,e.transform=ke,e.tryEach=Ot,e.unmemoize=ve,e.until=Se,e.waterfall=bt,e.whilst=_t,e.wrapSync=r,Object.defineProperty(e,"__esModule",{value:!0})}); \ No newline at end of file diff --git a/node_modules/async/dist/async.mjs b/node_modules/async/dist/async.mjs index d0cd59d..41c63c1 100644 --- a/node_modules/async/dist/async.mjs +++ b/node_modules/async/dist/async.mjs @@ -68,19 +68,19 @@ function wrap(defer) { return (fn, ...args) => defer(() => fn(...args)); } -var _defer; +var _defer$1; if (hasQueueMicrotask) { - _defer = queueMicrotask; + _defer$1 = queueMicrotask; } else if (hasSetImmediate) { - _defer = setImmediate; + _defer$1 = setImmediate; } else if (hasNextTick) { - _defer = process.nextTick; + _defer$1 = process.nextTick; } else { - _defer = fallback; + _defer$1 = fallback; } -var setImmediate$1 = wrap(_defer); +var setImmediate$1 = wrap(_defer$1); /** * Take a sync function and make it async, passing its return value to a @@ -167,7 +167,7 @@ function handlePromise(promise, callback) { return promise.then(value => { invokeCallback(callback, null, value); }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); }); } @@ -198,7 +198,8 @@ function wrapAsync(asyncFn) { // conditionally promisify a function. // only return a promise if a callback is omitted -function awaitify (asyncFn, arity = asyncFn.length) { +function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; if (!arity) throw new Error('arity is undefined') function awaitable (...args) { if (typeof args[arity - 1] === 'function') { @@ -217,7 +218,7 @@ function awaitify (asyncFn, arity = asyncFn.length) { return awaitable } -function applyEach (eachfn) { +function applyEach$1 (eachfn) { return function applyEach(fns, ...callArgs) { const go = awaitify(function (callback) { var that = this; @@ -256,6 +257,7 @@ function isArrayLike(value) { // A temporary value used to identify if the loop should be broken. // See #1064, #1293 const breakLoop = {}; +var breakLoop$1 = breakLoop; function once(fn) { function wrapper (...args) { @@ -366,7 +368,7 @@ function asyncEachOfLimit(generator, limit, iteratee, callback) { return } - if (result === breakLoop || (done && running <= 0)) { + if (result === breakLoop$1 || (done && running <= 0)) { done = true; //console.log('done iterCb') return callback(null); @@ -384,7 +386,7 @@ function asyncEachOfLimit(generator, limit, iteratee, callback) { replenish(); } -var eachOfLimit = (limit) => { +var eachOfLimit$2 = (limit) => { return (obj, iteratee, callback) => { callback = once(callback); if (limit <= 0) { @@ -416,7 +418,7 @@ var eachOfLimit = (limit) => { done = true; canceled = true; } - else if (value === breakLoop || (done && running <= 0)) { + else if (value === breakLoop$1 || (done && running <= 0)) { done = true; return callback(null); } @@ -467,11 +469,11 @@ var eachOfLimit = (limit) => { * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @returns {Promise} a promise, if a callback is omitted */ -function eachOfLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); +function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); } -var eachOfLimit$2 = awaitify(eachOfLimit$1, 4); +var eachOfLimit$1 = awaitify(eachOfLimit, 4); // eachOf implementation optimized for array-likes function eachOfArrayLike(coll, iteratee, callback) { @@ -491,7 +493,7 @@ function eachOfArrayLike(coll, iteratee, callback) { if (canceled === true) return if (err) { callback(err); - } else if ((++completed === length) || value === breakLoop) { + } else if ((++completed === length) || value === breakLoop$1) { callback(null); } } @@ -503,7 +505,7 @@ function eachOfArrayLike(coll, iteratee, callback) { // a generic version of eachOf which can handle array, object, and iterator cases. function eachOfGeneric (coll, iteratee, callback) { - return eachOfLimit$2(coll, Infinity, iteratee, callback); + return eachOfLimit$1(coll, Infinity, iteratee, callback); } /** @@ -783,7 +785,7 @@ var map$1 = awaitify(map, 3); * callback * ); */ -var applyEach$1 = applyEach(map$1); +var applyEach = applyEach$1(map$1); /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. @@ -804,7 +806,7 @@ var applyEach$1 = applyEach(map$1); * @returns {Promise} a promise, if a callback is omitted */ function eachOfSeries(coll, iteratee, callback) { - return eachOfLimit$2(coll, 1, iteratee, callback) + return eachOfLimit$1(coll, 1, iteratee, callback) } var eachOfSeries$1 = awaitify(eachOfSeries, 3); @@ -851,7 +853,7 @@ var mapSeries$1 = awaitify(mapSeries, 3); * appling the `args` to the list of functions. It takes no args, other than * a callback. */ -var applyEachSeries = applyEach(mapSeries$1); +var applyEachSeries = applyEach$1(mapSeries$1); const PROMISE_SYMBOL = Symbol('promiseCallback'); @@ -1449,7 +1451,7 @@ function setInitial(dll, node) { dll.head = dll.tail = node; } -function queue(worker, concurrency, payload) { +function queue$1(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } @@ -1767,8 +1769,8 @@ function queue(worker, concurrency, payload) { * await cargo.push({name: 'baz'}); * console.log('finished processing baz'); */ -function cargo(worker, payload) { - return queue(worker, 1, payload); +function cargo$1(worker, payload) { + return queue$1(worker, 1, payload); } /** @@ -1825,8 +1827,8 @@ function cargo(worker, payload) { * console.log('finished processing boo'); * }); */ -function cargo$1(worker, concurrency, payload) { - return queue(worker, concurrency, payload); +function cargo(worker, concurrency, payload) { + return queue$1(worker, concurrency, payload); } /** @@ -2082,7 +2084,7 @@ function compose(...args) { * @returns {Promise} a promise, if no callback is passed */ function mapLimit (coll, limit, iteratee, callback) { - return _asyncMap(eachOfLimit(limit), coll, iteratee, callback) + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) } var mapLimit$1 = awaitify(mapLimit, 4); @@ -2292,7 +2294,7 @@ var concatSeries$1 = awaitify(concatSeries, 3); * //... * }, callback); */ -function constant(...args) { +function constant$1(...args) { return function (...ignoredArgs/*, callback*/) { var callback = ignoredArgs.pop(); return callback(null, ...args); @@ -2311,7 +2313,7 @@ function _createTester(check, getResult) { if (check(result) && !testResult) { testPassed = true; testResult = getResult(true, value); - return callback(null, breakLoop); + return callback(null, breakLoop$1); } callback(); }); @@ -2422,7 +2424,7 @@ var detect$1 = awaitify(detect, 3); * @returns {Promise} a promise, if a callback is omitted */ function detectLimit(coll, limit, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) } var detectLimit$1 = awaitify(detectLimit, 4); @@ -2448,7 +2450,7 @@ var detectLimit$1 = awaitify(detectLimit, 4); * @returns {Promise} a promise, if a callback is omitted */ function detectSeries(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit(1), coll, iteratee, callback) + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) } var detectSeries$1 = awaitify(detectSeries, 3); @@ -2681,11 +2683,11 @@ function _withoutIndex(iteratee) { * } * */ -function eachLimit(coll, iteratee, callback) { +function eachLimit$2(coll, iteratee, callback) { return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); } -var each = awaitify(eachLimit, 3); +var each = awaitify(eachLimit$2, 3); /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. @@ -2708,10 +2710,10 @@ var each = awaitify(eachLimit, 3); * `iteratee` functions have finished, or an error occurs. Invoked with (err). * @returns {Promise} a promise, if a callback is omitted */ -function eachLimit$1(coll, limit, iteratee, callback) { - return eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); +function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } -var eachLimit$2 = awaitify(eachLimit$1, 4); +var eachLimit$1 = awaitify(eachLimit, 4); /** * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. @@ -2737,7 +2739,7 @@ var eachLimit$2 = awaitify(eachLimit$1, 4); * @returns {Promise} a promise, if a callback is omitted */ function eachSeries(coll, iteratee, callback) { - return eachLimit$2(coll, 1, iteratee, callback) + return eachLimit$1(coll, 1, iteratee, callback) } var eachSeries$1 = awaitify(eachSeries, 3); @@ -2914,7 +2916,7 @@ var every$1 = awaitify(every, 3); * @returns {Promise} a promise, if no callback provided */ function everyLimit(coll, limit, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) } var everyLimit$1 = awaitify(everyLimit, 4); @@ -3077,7 +3079,7 @@ var filter$1 = awaitify(filter, 3); * @returns {Promise} a promise, if no callback provided */ function filterLimit (coll, limit, iteratee, callback) { - return _filter(eachOfLimit(limit), coll, iteratee, callback) + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) } var filterLimit$1 = awaitify(filterLimit, 4); @@ -3372,7 +3374,7 @@ function mapValuesLimit(obj, limit, iteratee, callback) { callback = once(callback); var newObj = {}; var _iteratee = wrapAsync(iteratee); - return eachOfLimit(limit)(obj, (val, key, next) => { + return eachOfLimit$2(limit)(obj, (val, key, next) => { _iteratee(val, key, (err, result) => { if (err) return next(err); newObj[key] = result; @@ -3649,19 +3651,19 @@ function memoize(fn, hasher = v => v) { * // a, b, and c equal 1, 2, and 3 * }, 1, 2, 3); */ -var _defer$1; +var _defer; if (hasNextTick) { - _defer$1 = process.nextTick; + _defer = process.nextTick; } else if (hasSetImmediate) { - _defer$1 = setImmediate; + _defer = setImmediate; } else { - _defer$1 = fallback; + _defer = fallback; } -var nextTick = wrap(_defer$1); +var nextTick = wrap(_defer); -var parallel = awaitify((eachfn, tasks, callback) => { +var _parallel = awaitify((eachfn, tasks, callback) => { var results = isArrayLike(tasks) ? [] : {}; eachfn(tasks, (task, key, taskCb) => { @@ -3834,8 +3836,8 @@ var parallel = awaitify((eachfn, tasks, callback) => { * } * */ -function parallel$1(tasks, callback) { - return parallel(eachOf$1, tasks, callback); +function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); } /** @@ -3859,7 +3861,7 @@ function parallel$1(tasks, callback) { * @returns {Promise} a promise, if a callback is not passed */ function parallelLimit(tasks, limit, callback) { - return parallel(eachOfLimit(limit), tasks, callback); + return _parallel(eachOfLimit$2(limit), tasks, callback); } /** @@ -4004,9 +4006,9 @@ function parallelLimit(tasks, limit, callback) { * console.log('finished processing bar'); * }); */ -function queue$1 (worker, concurrency) { +function queue (worker, concurrency) { var _worker = wrapAsync(worker); - return queue((items, cb) => { + return queue$1((items, cb) => { _worker(items[0], cb); }, concurrency, 1); } @@ -4153,7 +4155,7 @@ function smaller(x, y) { */ function priorityQueue(worker, concurrency) { // Start with a normal queue - var q = queue$1(worker, concurrency); + var q = queue(worker, concurrency); var { push, @@ -4408,7 +4410,7 @@ function reflectAll(tasks) { return results; } -function reject(eachfn, arr, _iteratee, callback) { +function reject$2(eachfn, arr, _iteratee, callback) { const iteratee = wrapAsync(_iteratee); return _filter(eachfn, arr, (value, cb) => { iteratee(value, (err, v) => { @@ -4479,10 +4481,10 @@ function reject(eachfn, arr, _iteratee, callback) { * } * */ -function reject$1 (coll, iteratee, callback) { - return reject(eachOf$1, coll, iteratee, callback) +function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) } -var reject$2 = awaitify(reject$1, 3); +var reject$1 = awaitify(reject, 3); /** * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a @@ -4505,7 +4507,7 @@ var reject$2 = awaitify(reject$1, 3); * @returns {Promise} a promise, if no callback is passed */ function rejectLimit (coll, limit, iteratee, callback) { - return reject(eachOfLimit(limit), coll, iteratee, callback) + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) } var rejectLimit$1 = awaitify(rejectLimit, 4); @@ -4528,11 +4530,11 @@ var rejectLimit$1 = awaitify(rejectLimit, 4); * @returns {Promise} a promise, if no callback is passed */ function rejectSeries (coll, iteratee, callback) { - return reject(eachOfSeries$1, coll, iteratee, callback) + return reject$2(eachOfSeries$1, coll, iteratee, callback) } var rejectSeries$1 = awaitify(rejectSeries, 3); -function constant$1(value) { +function constant(value) { return function () { return value; } @@ -4629,7 +4631,7 @@ const DEFAULT_INTERVAL = 0; function retry(opts, task, callback) { var options = { times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) + intervalFunc: constant(DEFAULT_INTERVAL) }; if (arguments.length < 3 && typeof opts === 'function') { @@ -4670,7 +4672,7 @@ function parseTimes(acc, t) { acc.intervalFunc = typeof t.interval === 'function' ? t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); + constant(+t.interval || DEFAULT_INTERVAL); acc.errorFilter = t.errorFilter; } else if (typeof t === 'number' || typeof t === 'string') { @@ -4901,7 +4903,7 @@ function retryable (opts, task) { * */ function series(tasks, callback) { - return parallel(eachOfSeries$1, tasks, callback); + return _parallel(eachOfSeries$1, tasks, callback); } /** @@ -5029,7 +5031,7 @@ var some$1 = awaitify(some, 3); * @returns {Promise} a promise, if no callback provided */ function someLimit(coll, limit, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfLimit(limit), coll, iteratee, callback) + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) } var someLimit$1 = awaitify(someLimit, 4); @@ -5623,7 +5625,7 @@ function unmemoize(fn) { * @method * @category Control Flow * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). + * execution of `iteratee`. Invoked with (callback). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test @@ -5835,20 +5837,21 @@ var waterfall$1 = awaitify(waterfall); * @static */ + var index = { apply, - applyEach: applyEach$1, + applyEach, applyEachSeries, asyncify, auto, autoInject, - cargo, - cargoQueue: cargo$1, + cargo: cargo$1, + cargoQueue: cargo, compose, concat: concat$1, concatLimit: concatLimit$1, concatSeries: concatSeries$1, - constant, + constant: constant$1, detect: detect$1, detectLimit: detectLimit$1, detectSeries: detectSeries$1, @@ -5856,9 +5859,9 @@ var index = { doUntil, doWhilst: doWhilst$1, each, - eachLimit: eachLimit$2, + eachLimit: eachLimit$1, eachOf: eachOf$1, - eachOfLimit: eachOfLimit$2, + eachOfLimit: eachOfLimit$1, eachOfSeries: eachOfSeries$1, eachSeries: eachSeries$1, ensureAsync, @@ -5881,16 +5884,16 @@ var index = { mapValuesSeries, memoize, nextTick, - parallel: parallel$1, + parallel, parallelLimit, priorityQueue, - queue: queue$1, + queue, race: race$1, reduce: reduce$1, reduceRight, reflect, reflectAll, - reject: reject$2, + reject: reject$1, rejectLimit: rejectLimit$1, rejectSeries: rejectSeries$1, retry, @@ -5928,10 +5931,10 @@ var index = { flatMapSeries: concatSeries$1, forEach: each, forEachSeries: eachSeries$1, - forEachLimit: eachLimit$2, + forEachLimit: eachLimit$1, forEachOf: eachOf$1, forEachOfSeries: eachOfSeries$1, - forEachOfLimit: eachOfLimit$2, + forEachOfLimit: eachOfLimit$1, inject: reduce$1, foldl: reduce$1, foldr: reduceRight, @@ -5943,5 +5946,4 @@ var index = { doDuring: doWhilst$1 }; -export default index; -export { apply, applyEach$1 as applyEach, applyEachSeries, asyncify, auto, autoInject, cargo, cargo$1 as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doUntil, doWhilst$1 as doWhilst, each, eachLimit$2 as eachLimit, eachOf$1 as eachOf, eachOfLimit$2 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel$1 as parallel, parallelLimit, priorityQueue, queue$1 as queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$2 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, each as forEach, eachSeries$1 as forEachSeries, eachLimit$2 as forEachLimit, eachOf$1 as forEachOf, eachOfSeries$1 as forEachOfSeries, eachOfLimit$2 as forEachOfLimit, reduce$1 as inject, reduce$1 as foldl, reduceRight as foldr, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, asyncify as wrapSync, whilst$1 as during, doWhilst$1 as doDuring }; +export { every$1 as all, everyLimit$1 as allLimit, everySeries$1 as allSeries, some$1 as any, someLimit$1 as anyLimit, someSeries$1 as anySeries, apply, applyEach, applyEachSeries, asyncify, auto, autoInject, cargo$1 as cargo, cargo as cargoQueue, compose, concat$1 as concat, concatLimit$1 as concatLimit, concatSeries$1 as concatSeries, constant$1 as constant, index as default, detect$1 as detect, detectLimit$1 as detectLimit, detectSeries$1 as detectSeries, dir, doWhilst$1 as doDuring, doUntil, doWhilst$1 as doWhilst, whilst$1 as during, each, eachLimit$1 as eachLimit, eachOf$1 as eachOf, eachOfLimit$1 as eachOfLimit, eachOfSeries$1 as eachOfSeries, eachSeries$1 as eachSeries, ensureAsync, every$1 as every, everyLimit$1 as everyLimit, everySeries$1 as everySeries, filter$1 as filter, filterLimit$1 as filterLimit, filterSeries$1 as filterSeries, detect$1 as find, detectLimit$1 as findLimit, detectSeries$1 as findSeries, concat$1 as flatMap, concatLimit$1 as flatMapLimit, concatSeries$1 as flatMapSeries, reduce$1 as foldl, reduceRight as foldr, each as forEach, eachLimit$1 as forEachLimit, eachOf$1 as forEachOf, eachOfLimit$1 as forEachOfLimit, eachOfSeries$1 as forEachOfSeries, eachSeries$1 as forEachSeries, forever$1 as forever, groupBy, groupByLimit$1 as groupByLimit, groupBySeries, reduce$1 as inject, log, map$1 as map, mapLimit$1 as mapLimit, mapSeries$1 as mapSeries, mapValues, mapValuesLimit$1 as mapValuesLimit, mapValuesSeries, memoize, nextTick, parallel, parallelLimit, priorityQueue, queue, race$1 as race, reduce$1 as reduce, reduceRight, reflect, reflectAll, reject$1 as reject, rejectLimit$1 as rejectLimit, rejectSeries$1 as rejectSeries, retry, retryable, filter$1 as select, filterLimit$1 as selectLimit, filterSeries$1 as selectSeries, seq, series, setImmediate$1 as setImmediate, some$1 as some, someLimit$1 as someLimit, someSeries$1 as someSeries, sortBy$1 as sortBy, timeout, times, timesLimit, timesSeries, transform, tryEach$1 as tryEach, unmemoize, until, waterfall$1 as waterfall, whilst$1 as whilst, asyncify as wrapSync }; diff --git a/node_modules/async/doDuring.js b/node_modules/async/doDuring.js index 4c98e9e..c72766d 100644 --- a/node_modules/async/doDuring.js +++ b/node_modules/async/doDuring.js @@ -65,4 +65,4 @@ function doWhilst(iteratee, test, callback) { } exports.default = (0, _awaitify2.default)(doWhilst, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doUntil.js b/node_modules/async/doUntil.js index 8aa0935..519900e 100644 --- a/node_modules/async/doUntil.js +++ b/node_modules/async/doUntil.js @@ -43,4 +43,4 @@ function doUntil(iteratee, test, callback) { _test(...args, (err, truth) => cb(err, !truth)); }, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/doWhilst.js b/node_modules/async/doWhilst.js index 4c98e9e..c72766d 100644 --- a/node_modules/async/doWhilst.js +++ b/node_modules/async/doWhilst.js @@ -65,4 +65,4 @@ function doWhilst(iteratee, test, callback) { } exports.default = (0, _awaitify2.default)(doWhilst, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/during.js b/node_modules/async/during.js index 32a4776..4165543 100644 --- a/node_modules/async/during.js +++ b/node_modules/async/during.js @@ -28,7 +28,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @method * @category Control Flow * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). + * execution of `iteratee`. Invoked with (callback). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test @@ -75,4 +75,4 @@ function whilst(test, iteratee, callback) { return _test(check); } exports.default = (0, _awaitify2.default)(whilst, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/each.js b/node_modules/async/each.js index 405d495..fdfcbd8 100644 --- a/node_modules/async/each.js +++ b/node_modules/async/each.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOf = require('./eachOf.js'); @@ -122,8 +122,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function eachLimit(coll, iteratee, callback) { - return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } exports.default = (0, _awaitify2.default)(eachLimit, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachLimit.js b/node_modules/async/eachLimit.js index 5f3d009..7f5928c 100644 --- a/node_modules/async/eachLimit.js +++ b/node_modules/async/eachLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit = require('./internal/eachOfLimit.js'); @@ -44,7 +44,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachLimit(coll, limit, iteratee, callback) { - return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } exports.default = (0, _awaitify2.default)(eachLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOf.js b/node_modules/async/eachOf.js index c22614f..9ed20f6 100644 --- a/node_modules/async/eachOf.js +++ b/node_modules/async/eachOf.js @@ -182,4 +182,4 @@ function eachOf(coll, iteratee, callback) { } exports.default = (0, _awaitify2.default)(eachOf, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfLimit.js b/node_modules/async/eachOfLimit.js index e9fc4db..a596e5a 100644 --- a/node_modules/async/eachOfLimit.js +++ b/node_modules/async/eachOfLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit2 = require('./internal/eachOfLimit.js'); @@ -40,8 +40,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachOfLimit(coll, limit, iteratee, callback) { - return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); } exports.default = (0, _awaitify2.default)(eachOfLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachOfSeries.js b/node_modules/async/eachOfSeries.js index cfb0f33..04243ad 100644 --- a/node_modules/async/eachOfSeries.js +++ b/node_modules/async/eachOfSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit = require('./eachOfLimit.js'); @@ -33,7 +33,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachOfSeries(coll, iteratee, callback) { - return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(eachOfSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/eachSeries.js b/node_modules/async/eachSeries.js index d674d0c..b04896e 100644 --- a/node_modules/async/eachSeries.js +++ b/node_modules/async/eachSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachLimit = require('./eachLimit.js'); @@ -38,7 +38,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachSeries(coll, iteratee, callback) { - return (0, _eachLimit2.default)(coll, 1, iteratee, callback); + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(eachSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/ensureAsync.js b/node_modules/async/ensureAsync.js index ad8beb5..749c5da 100644 --- a/node_modules/async/ensureAsync.js +++ b/node_modules/async/ensureAsync.js @@ -64,4 +64,4 @@ function ensureAsync(fn) { sync = false; }; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/every.js b/node_modules/async/every.js index 148db68..622b301 100644 --- a/node_modules/async/every.js +++ b/node_modules/async/every.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -113,7 +113,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function every(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(every, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everyLimit.js b/node_modules/async/everyLimit.js index 25b2c08..375e126 100644 --- a/node_modules/async/everyLimit.js +++ b/node_modules/async/everyLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,7 +40,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function everyLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(everyLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/everySeries.js b/node_modules/async/everySeries.js index 147c3dc..9a6bf7d 100644 --- a/node_modules/async/everySeries.js +++ b/node_modules/async/everySeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function everySeries(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => !bool, res => !res)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(everySeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filter.js b/node_modules/async/filter.js index 303dc1f..2c9a63d 100644 --- a/node_modules/async/filter.js +++ b/node_modules/async/filter.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -87,7 +87,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function filter(coll, iteratee, callback) { - return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filter, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterLimit.js b/node_modules/async/filterLimit.js index 89e55f5..d3b3f50 100644 --- a/node_modules/async/filterLimit.js +++ b/node_modules/async/filterLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function filterLimit(coll, limit, iteratee, callback) { - return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filterLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/filterSeries.js b/node_modules/async/filterSeries.js index a045e52..019a2d0 100644 --- a/node_modules/async/filterSeries.js +++ b/node_modules/async/filterSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -37,7 +37,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function filterSeries(coll, iteratee, callback) { - return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filterSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/find.js b/node_modules/async/find.js index 05b2e5c..d5896ef 100644 --- a/node_modules/async/find.js +++ b/node_modules/async/find.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -90,7 +90,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function detect(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detect, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findLimit.js b/node_modules/async/findLimit.js index db6961e..c59843b 100644 --- a/node_modules/async/findLimit.js +++ b/node_modules/async/findLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -42,7 +42,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function detectLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detectLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/findSeries.js b/node_modules/async/findSeries.js index b9131b4..b486899 100644 --- a/node_modules/async/findSeries.js +++ b/node_modules/async/findSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,8 +40,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function detectSeries(coll, iteratee, callback) { - return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); + return (0, _createTester2.default)(bool => bool, (res, item) => item)((0, _eachOfLimit2.default)(1), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(detectSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMap.js b/node_modules/async/flatMap.js index 8eed1ac..4540a79 100644 --- a/node_modules/async/flatMap.js +++ b/node_modules/async/flatMap.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _concatLimit = require('./concatLimit.js'); @@ -109,7 +109,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function concat(coll, iteratee, callback) { - return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); + return (0, _concatLimit2.default)(coll, Infinity, iteratee, callback); } exports.default = (0, _awaitify2.default)(concat, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapLimit.js b/node_modules/async/flatMapLimit.js index 3d170f1..a27cc7d 100644 --- a/node_modules/async/flatMapLimit.js +++ b/node_modules/async/flatMapLimit.js @@ -57,4 +57,4 @@ function concatLimit(coll, limit, iteratee, callback) { }); } exports.default = (0, _awaitify2.default)(concatLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/flatMapSeries.js b/node_modules/async/flatMapSeries.js index 84add3b..332de3f 100644 --- a/node_modules/async/flatMapSeries.js +++ b/node_modules/async/flatMapSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _concatLimit = require('./concatLimit.js'); @@ -35,7 +35,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns A Promise, if no callback is passed */ function concatSeries(coll, iteratee, callback) { - return (0, _concatLimit2.default)(coll, 1, iteratee, callback); + return (0, _concatLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(concatSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldl.js b/node_modules/async/foldl.js index 56e2db8..8a69548 100644 --- a/node_modules/async/foldl.js +++ b/node_modules/async/foldl.js @@ -150,4 +150,4 @@ function reduce(coll, memo, iteratee, callback) { }, err => callback(err, memo)); } exports.default = (0, _awaitify2.default)(reduce, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/foldr.js b/node_modules/async/foldr.js index bee5391..5be1b68 100644 --- a/node_modules/async/foldr.js +++ b/node_modules/async/foldr.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = reduceRight; @@ -35,7 +35,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function reduceRight(array, memo, iteratee, callback) { - var reversed = [...array].reverse(); - return (0, _reduce2.default)(reversed, memo, iteratee, callback); + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEach.js b/node_modules/async/forEach.js index 405d495..fdfcbd8 100644 --- a/node_modules/async/forEach.js +++ b/node_modules/async/forEach.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOf = require('./eachOf.js'); @@ -122,8 +122,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function eachLimit(coll, iteratee, callback) { - return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + return (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } exports.default = (0, _awaitify2.default)(eachLimit, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachLimit.js b/node_modules/async/forEachLimit.js index 5f3d009..7f5928c 100644 --- a/node_modules/async/forEachLimit.js +++ b/node_modules/async/forEachLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit = require('./internal/eachOfLimit.js'); @@ -44,7 +44,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachLimit(coll, limit, iteratee, callback) { - return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); + return (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); } exports.default = (0, _awaitify2.default)(eachLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOf.js b/node_modules/async/forEachOf.js index c22614f..9ed20f6 100644 --- a/node_modules/async/forEachOf.js +++ b/node_modules/async/forEachOf.js @@ -182,4 +182,4 @@ function eachOf(coll, iteratee, callback) { } exports.default = (0, _awaitify2.default)(eachOf, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfLimit.js b/node_modules/async/forEachOfLimit.js index e9fc4db..a596e5a 100644 --- a/node_modules/async/forEachOfLimit.js +++ b/node_modules/async/forEachOfLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit2 = require('./internal/eachOfLimit.js'); @@ -40,8 +40,8 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachOfLimit(coll, limit, iteratee, callback) { - return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); + return (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); } exports.default = (0, _awaitify2.default)(eachOfLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachOfSeries.js b/node_modules/async/forEachOfSeries.js index cfb0f33..04243ad 100644 --- a/node_modules/async/forEachOfSeries.js +++ b/node_modules/async/forEachOfSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachOfLimit = require('./eachOfLimit.js'); @@ -33,7 +33,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachOfSeries(coll, iteratee, callback) { - return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); + return (0, _eachOfLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(eachOfSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forEachSeries.js b/node_modules/async/forEachSeries.js index d674d0c..b04896e 100644 --- a/node_modules/async/forEachSeries.js +++ b/node_modules/async/forEachSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _eachLimit = require('./eachLimit.js'); @@ -38,7 +38,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is omitted */ function eachSeries(coll, iteratee, callback) { - return (0, _eachLimit2.default)(coll, 1, iteratee, callback); + return (0, _eachLimit2.default)(coll, 1, iteratee, callback); } exports.default = (0, _awaitify2.default)(eachSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/forever.js b/node_modules/async/forever.js index 2c8d5b8..2292518 100644 --- a/node_modules/async/forever.js +++ b/node_modules/async/forever.js @@ -65,4 +65,4 @@ function forever(fn, errback) { return next(); } exports.default = (0, _awaitify2.default)(forever, 2); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBy.js b/node_modules/async/groupBy.js index 6bb52aa..f295763 100644 --- a/node_modules/async/groupBy.js +++ b/node_modules/async/groupBy.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = groupBy; @@ -103,6 +103,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function groupBy(coll, iteratee, callback) { - return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); + return (0, _groupByLimit2.default)(coll, Infinity, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupByLimit.js b/node_modules/async/groupByLimit.js index 5766d6e..30fd290 100644 --- a/node_modules/async/groupByLimit.js +++ b/node_modules/async/groupByLimit.js @@ -68,4 +68,4 @@ function groupByLimit(coll, limit, iteratee, callback) { } exports.default = (0, _awaitify2.default)(groupByLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/groupBySeries.js b/node_modules/async/groupBySeries.js index 6056743..e2a5287 100644 --- a/node_modules/async/groupBySeries.js +++ b/node_modules/async/groupBySeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = groupBySeries; @@ -31,6 +31,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function groupBySeries(coll, iteratee, callback) { - return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); + return (0, _groupByLimit2.default)(coll, 1, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/index.js b/node_modules/async/index.js index ce647d5..6154647 100644 --- a/node_modules/async/index.js +++ b/node_modules/async/index.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.doDuring = exports.during = exports.wrapSync = undefined; exports.selectSeries = exports.selectLimit = exports.select = exports.foldr = exports.foldl = exports.inject = exports.forEachOfLimit = exports.forEachOfSeries = exports.forEachOf = exports.forEachLimit = exports.forEachSeries = exports.forEach = exports.flatMapSeries = exports.flatMapLimit = exports.flatMap = exports.findSeries = exports.findLimit = exports.find = exports.anySeries = exports.anyLimit = exports.any = exports.allSeries = exports.allLimit = exports.all = exports.whilst = exports.waterfall = exports.until = exports.unmemoize = exports.tryEach = exports.transform = exports.timesSeries = exports.timesLimit = exports.times = exports.timeout = exports.sortBy = exports.someSeries = exports.someLimit = exports.some = exports.setImmediate = exports.series = exports.seq = exports.retryable = exports.retry = exports.rejectSeries = exports.rejectLimit = exports.reject = exports.reflectAll = exports.reflect = exports.reduceRight = exports.reduce = exports.race = exports.queue = exports.priorityQueue = exports.parallelLimit = exports.parallel = exports.nextTick = exports.memoize = exports.mapValuesSeries = exports.mapValuesLimit = exports.mapValues = exports.mapSeries = exports.mapLimit = exports.map = exports.log = exports.groupBySeries = exports.groupByLimit = exports.groupBy = exports.forever = exports.filterSeries = exports.filterLimit = exports.filter = exports.everySeries = exports.everyLimit = exports.every = exports.ensureAsync = exports.eachSeries = exports.eachOfSeries = exports.eachOfLimit = exports.eachOf = exports.eachLimit = exports.each = exports.doWhilst = exports.doUntil = exports.dir = exports.detectSeries = exports.detectLimit = exports.detect = exports.constant = exports.concatSeries = exports.concatLimit = exports.concat = exports.compose = exports.cargoQueue = exports.cargo = exports.autoInject = exports.auto = exports.asyncify = exports.applyEachSeries = exports.applyEach = exports.apply = undefined; @@ -377,111 +377,111 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de */ exports.default = { - apply: _apply2.default, - applyEach: _applyEach2.default, - applyEachSeries: _applyEachSeries2.default, - asyncify: _asyncify2.default, - auto: _auto2.default, - autoInject: _autoInject2.default, - cargo: _cargo2.default, - cargoQueue: _cargoQueue2.default, - compose: _compose2.default, - concat: _concat2.default, - concatLimit: _concatLimit2.default, - concatSeries: _concatSeries2.default, - constant: _constant2.default, - detect: _detect2.default, - detectLimit: _detectLimit2.default, - detectSeries: _detectSeries2.default, - dir: _dir2.default, - doUntil: _doUntil2.default, - doWhilst: _doWhilst2.default, - each: _each2.default, - eachLimit: _eachLimit2.default, - eachOf: _eachOf2.default, - eachOfLimit: _eachOfLimit2.default, - eachOfSeries: _eachOfSeries2.default, - eachSeries: _eachSeries2.default, - ensureAsync: _ensureAsync2.default, - every: _every2.default, - everyLimit: _everyLimit2.default, - everySeries: _everySeries2.default, - filter: _filter2.default, - filterLimit: _filterLimit2.default, - filterSeries: _filterSeries2.default, - forever: _forever2.default, - groupBy: _groupBy2.default, - groupByLimit: _groupByLimit2.default, - groupBySeries: _groupBySeries2.default, - log: _log2.default, - map: _map2.default, - mapLimit: _mapLimit2.default, - mapSeries: _mapSeries2.default, - mapValues: _mapValues2.default, - mapValuesLimit: _mapValuesLimit2.default, - mapValuesSeries: _mapValuesSeries2.default, - memoize: _memoize2.default, - nextTick: _nextTick2.default, - parallel: _parallel2.default, - parallelLimit: _parallelLimit2.default, - priorityQueue: _priorityQueue2.default, - queue: _queue2.default, - race: _race2.default, - reduce: _reduce2.default, - reduceRight: _reduceRight2.default, - reflect: _reflect2.default, - reflectAll: _reflectAll2.default, - reject: _reject2.default, - rejectLimit: _rejectLimit2.default, - rejectSeries: _rejectSeries2.default, - retry: _retry2.default, - retryable: _retryable2.default, - seq: _seq2.default, - series: _series2.default, - setImmediate: _setImmediate2.default, - some: _some2.default, - someLimit: _someLimit2.default, - someSeries: _someSeries2.default, - sortBy: _sortBy2.default, - timeout: _timeout2.default, - times: _times2.default, - timesLimit: _timesLimit2.default, - timesSeries: _timesSeries2.default, - transform: _transform2.default, - tryEach: _tryEach2.default, - unmemoize: _unmemoize2.default, - until: _until2.default, - waterfall: _waterfall2.default, - whilst: _whilst2.default, - - // aliases - all: _every2.default, - allLimit: _everyLimit2.default, - allSeries: _everySeries2.default, - any: _some2.default, - anyLimit: _someLimit2.default, - anySeries: _someSeries2.default, - find: _detect2.default, - findLimit: _detectLimit2.default, - findSeries: _detectSeries2.default, - flatMap: _concat2.default, - flatMapLimit: _concatLimit2.default, - flatMapSeries: _concatSeries2.default, - forEach: _each2.default, - forEachSeries: _eachSeries2.default, - forEachLimit: _eachLimit2.default, - forEachOf: _eachOf2.default, - forEachOfSeries: _eachOfSeries2.default, - forEachOfLimit: _eachOfLimit2.default, - inject: _reduce2.default, - foldl: _reduce2.default, - foldr: _reduceRight2.default, - select: _filter2.default, - selectLimit: _filterLimit2.default, - selectSeries: _filterSeries2.default, - wrapSync: _asyncify2.default, - during: _whilst2.default, - doDuring: _doWhilst2.default + apply: _apply2.default, + applyEach: _applyEach2.default, + applyEachSeries: _applyEachSeries2.default, + asyncify: _asyncify2.default, + auto: _auto2.default, + autoInject: _autoInject2.default, + cargo: _cargo2.default, + cargoQueue: _cargoQueue2.default, + compose: _compose2.default, + concat: _concat2.default, + concatLimit: _concatLimit2.default, + concatSeries: _concatSeries2.default, + constant: _constant2.default, + detect: _detect2.default, + detectLimit: _detectLimit2.default, + detectSeries: _detectSeries2.default, + dir: _dir2.default, + doUntil: _doUntil2.default, + doWhilst: _doWhilst2.default, + each: _each2.default, + eachLimit: _eachLimit2.default, + eachOf: _eachOf2.default, + eachOfLimit: _eachOfLimit2.default, + eachOfSeries: _eachOfSeries2.default, + eachSeries: _eachSeries2.default, + ensureAsync: _ensureAsync2.default, + every: _every2.default, + everyLimit: _everyLimit2.default, + everySeries: _everySeries2.default, + filter: _filter2.default, + filterLimit: _filterLimit2.default, + filterSeries: _filterSeries2.default, + forever: _forever2.default, + groupBy: _groupBy2.default, + groupByLimit: _groupByLimit2.default, + groupBySeries: _groupBySeries2.default, + log: _log2.default, + map: _map2.default, + mapLimit: _mapLimit2.default, + mapSeries: _mapSeries2.default, + mapValues: _mapValues2.default, + mapValuesLimit: _mapValuesLimit2.default, + mapValuesSeries: _mapValuesSeries2.default, + memoize: _memoize2.default, + nextTick: _nextTick2.default, + parallel: _parallel2.default, + parallelLimit: _parallelLimit2.default, + priorityQueue: _priorityQueue2.default, + queue: _queue2.default, + race: _race2.default, + reduce: _reduce2.default, + reduceRight: _reduceRight2.default, + reflect: _reflect2.default, + reflectAll: _reflectAll2.default, + reject: _reject2.default, + rejectLimit: _rejectLimit2.default, + rejectSeries: _rejectSeries2.default, + retry: _retry2.default, + retryable: _retryable2.default, + seq: _seq2.default, + series: _series2.default, + setImmediate: _setImmediate2.default, + some: _some2.default, + someLimit: _someLimit2.default, + someSeries: _someSeries2.default, + sortBy: _sortBy2.default, + timeout: _timeout2.default, + times: _times2.default, + timesLimit: _timesLimit2.default, + timesSeries: _timesSeries2.default, + transform: _transform2.default, + tryEach: _tryEach2.default, + unmemoize: _unmemoize2.default, + until: _until2.default, + waterfall: _waterfall2.default, + whilst: _whilst2.default, + + // aliases + all: _every2.default, + allLimit: _everyLimit2.default, + allSeries: _everySeries2.default, + any: _some2.default, + anyLimit: _someLimit2.default, + anySeries: _someSeries2.default, + find: _detect2.default, + findLimit: _detectLimit2.default, + findSeries: _detectSeries2.default, + flatMap: _concat2.default, + flatMapLimit: _concatLimit2.default, + flatMapSeries: _concatSeries2.default, + forEach: _each2.default, + forEachSeries: _eachSeries2.default, + forEachLimit: _eachLimit2.default, + forEachOf: _eachOf2.default, + forEachOfSeries: _eachOfSeries2.default, + forEachOfLimit: _eachOfLimit2.default, + inject: _reduce2.default, + foldl: _reduce2.default, + foldr: _reduceRight2.default, + select: _filter2.default, + selectLimit: _filterLimit2.default, + selectSeries: _filterSeries2.default, + wrapSync: _asyncify2.default, + during: _whilst2.default, + doDuring: _doWhilst2.default }; exports.apply = _apply2.default; exports.applyEach = _applyEach2.default; diff --git a/node_modules/async/inject.js b/node_modules/async/inject.js index 56e2db8..8a69548 100644 --- a/node_modules/async/inject.js +++ b/node_modules/async/inject.js @@ -150,4 +150,4 @@ function reduce(coll, memo, iteratee, callback) { }, err => callback(err, memo)); } exports.default = (0, _awaitify2.default)(reduce, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/DoublyLinkedList.js b/node_modules/async/internal/DoublyLinkedList.js index cd11c3b..419ce44 100644 --- a/node_modules/async/internal/DoublyLinkedList.js +++ b/node_modules/async/internal/DoublyLinkedList.js @@ -89,4 +89,4 @@ function setInitial(dll, node) { dll.length = 1; dll.head = dll.tail = node; } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/Heap.js b/node_modules/async/internal/Heap.js index 80762fe..7867c92 100644 --- a/node_modules/async/internal/Heap.js +++ b/node_modules/async/internal/Heap.js @@ -117,4 +117,4 @@ function smaller(x, y) { return x.pushCount < y.pushCount; } } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/applyEach.js b/node_modules/async/internal/applyEach.js index a3f4ef1..5444912 100644 --- a/node_modules/async/internal/applyEach.js +++ b/node_modules/async/internal/applyEach.js @@ -26,4 +26,4 @@ var _awaitify2 = _interopRequireDefault(_awaitify); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/asyncEachOfLimit.js b/node_modules/async/internal/asyncEachOfLimit.js index bba74c7..34dd82b 100644 --- a/node_modules/async/internal/asyncEachOfLimit.js +++ b/node_modules/async/internal/asyncEachOfLimit.js @@ -72,4 +72,4 @@ function asyncEachOfLimit(generator, limit, iteratee, callback) { replenish(); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/awaitify.js b/node_modules/async/internal/awaitify.js index 7b36f1a..bb7a609 100644 --- a/node_modules/async/internal/awaitify.js +++ b/node_modules/async/internal/awaitify.js @@ -6,7 +6,8 @@ Object.defineProperty(exports, "__esModule", { exports.default = awaitify; // conditionally promisify a function. // only return a promise if a callback is omitted -function awaitify(asyncFn, arity = asyncFn.length) { +function awaitify(asyncFn, arity) { + if (!arity) arity = asyncFn.length; if (!arity) throw new Error('arity is undefined'); function awaitable(...args) { if (typeof args[arity - 1] === 'function') { @@ -24,4 +25,4 @@ function awaitify(asyncFn, arity = asyncFn.length) { return awaitable; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/breakLoop.js b/node_modules/async/internal/breakLoop.js index 8245e55..87413dd 100644 --- a/node_modules/async/internal/breakLoop.js +++ b/node_modules/async/internal/breakLoop.js @@ -1,10 +1,10 @@ "use strict"; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); // A temporary value used to identify if the loop should be broken. // See #1064, #1293 const breakLoop = {}; exports.default = breakLoop; -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/consoleFunc.js b/node_modules/async/internal/consoleFunc.js index 70347a5..748d54b 100644 --- a/node_modules/async/internal/consoleFunc.js +++ b/node_modules/async/internal/consoleFunc.js @@ -28,4 +28,4 @@ function consoleFunc(name) { } }); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/createTester.js b/node_modules/async/internal/createTester.js index 7b2d734..cafdf62 100644 --- a/node_modules/async/internal/createTester.js +++ b/node_modules/async/internal/createTester.js @@ -37,4 +37,4 @@ function _createTester(check, getResult) { }); }; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/eachOfLimit.js b/node_modules/async/internal/eachOfLimit.js index fc26b20..ceed60f 100644 --- a/node_modules/async/internal/eachOfLimit.js +++ b/node_modules/async/internal/eachOfLimit.js @@ -87,4 +87,4 @@ exports.default = limit => { }; }; -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/filter.js b/node_modules/async/internal/filter.js index aef2b9d..065c211 100644 --- a/node_modules/async/internal/filter.js +++ b/node_modules/async/internal/filter.js @@ -52,4 +52,4 @@ function _filter(eachfn, coll, iteratee, callback) { var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; return filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/getIterator.js b/node_modules/async/internal/getIterator.js index 830a545..f518fce 100644 --- a/node_modules/async/internal/getIterator.js +++ b/node_modules/async/internal/getIterator.js @@ -8,4 +8,4 @@ exports.default = function (coll) { return coll[Symbol.iterator] && coll[Symbol.iterator](); }; -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/initialParams.js b/node_modules/async/internal/initialParams.js index 245378c..04c0eff 100644 --- a/node_modules/async/internal/initialParams.js +++ b/node_modules/async/internal/initialParams.js @@ -11,4 +11,4 @@ exports.default = function (fn) { }; }; -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/isArrayLike.js b/node_modules/async/internal/isArrayLike.js index ce07670..a4c4c8a 100644 --- a/node_modules/async/internal/isArrayLike.js +++ b/node_modules/async/internal/isArrayLike.js @@ -7,4 +7,4 @@ exports.default = isArrayLike; function isArrayLike(value) { return value && typeof value.length === 'number' && value.length >= 0 && value.length % 1 === 0; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/iterator.js b/node_modules/async/internal/iterator.js index 90b0223..5778b1e 100644 --- a/node_modules/async/internal/iterator.js +++ b/node_modules/async/internal/iterator.js @@ -54,4 +54,4 @@ function createIterator(coll) { var iterator = (0, _getIterator2.default)(coll); return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/map.js b/node_modules/async/internal/map.js index af3fd09..acab1e7 100644 --- a/node_modules/async/internal/map.js +++ b/node_modules/async/internal/map.js @@ -27,4 +27,4 @@ function _asyncMap(eachfn, arr, iteratee, callback) { callback(err, results); }); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/once.js b/node_modules/async/internal/once.js index 49f3727..a8b5792 100644 --- a/node_modules/async/internal/once.js +++ b/node_modules/async/internal/once.js @@ -14,4 +14,4 @@ function once(fn) { Object.assign(wrapper, fn); return wrapper; } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/onlyOnce.js b/node_modules/async/internal/onlyOnce.js index 6ad721b..c95a92d 100644 --- a/node_modules/async/internal/onlyOnce.js +++ b/node_modules/async/internal/onlyOnce.js @@ -12,4 +12,4 @@ function onlyOnce(fn) { callFn.apply(this, args); }; } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/parallel.js b/node_modules/async/internal/parallel.js index 75741bb..57fbd0d 100644 --- a/node_modules/async/internal/parallel.js +++ b/node_modules/async/internal/parallel.js @@ -31,4 +31,4 @@ exports.default = (0, _awaitify2.default)((eachfn, tasks, callback) => { }); }, err => callback(err, results)); }, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/queue.js b/node_modules/async/internal/queue.js index cbc590d..7414e03 100644 --- a/node_modules/async/internal/queue.js +++ b/node_modules/async/internal/queue.js @@ -291,4 +291,4 @@ function queue(worker, concurrency, payload) { }); return q; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/range.js b/node_modules/async/internal/range.js index 6680e64..cc7b3a9 100644 --- a/node_modules/async/internal/range.js +++ b/node_modules/async/internal/range.js @@ -11,4 +11,4 @@ function range(size) { } return result; } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/reject.js b/node_modules/async/internal/reject.js index 7388ef4..9d9bc80 100644 --- a/node_modules/async/internal/reject.js +++ b/node_modules/async/internal/reject.js @@ -23,4 +23,4 @@ function reject(eachfn, arr, _iteratee, callback) { }); }, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/internal/withoutIndex.js b/node_modules/async/internal/withoutIndex.js index ec45fa3..fa91c2d 100644 --- a/node_modules/async/internal/withoutIndex.js +++ b/node_modules/async/internal/withoutIndex.js @@ -7,4 +7,4 @@ exports.default = _withoutIndex; function _withoutIndex(iteratee) { return (value, index, callback) => iteratee(value, callback); } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/log.js b/node_modules/async/log.js index 8fc1ed5..332b9da 100644 --- a/node_modules/async/log.js +++ b/node_modules/async/log.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _consoleFunc = require('./internal/consoleFunc.js'); @@ -38,4 +38,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * 'hello world' */ exports.default = (0, _consoleFunc2.default)('log'); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/map.js b/node_modules/async/map.js index ec4135d..c4b7a5a 100644 --- a/node_modules/async/map.js +++ b/node_modules/async/map.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _map2 = require('./internal/map.js'); @@ -136,7 +136,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function map(coll, iteratee, callback) { - return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); + return (0, _map3.default)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(map, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapLimit.js b/node_modules/async/mapLimit.js index b5e461c..6ad3572 100644 --- a/node_modules/async/mapLimit.js +++ b/node_modules/async/mapLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _map2 = require('./internal/map.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function mapLimit(coll, limit, iteratee, callback) { - return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _map3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(mapLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapSeries.js b/node_modules/async/mapSeries.js index 91f36bf..8dfdd8a 100644 --- a/node_modules/async/mapSeries.js +++ b/node_modules/async/mapSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _map2 = require('./internal/map.js'); @@ -38,7 +38,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function mapSeries(coll, iteratee, callback) { - return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _map3.default)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(mapSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValues.js b/node_modules/async/mapValues.js index 00da926..3d0470e 100644 --- a/node_modules/async/mapValues.js +++ b/node_modules/async/mapValues.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = mapValues; @@ -147,6 +147,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function mapValues(obj, iteratee, callback) { - return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); + return (0, _mapValuesLimit2.default)(obj, Infinity, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesLimit.js b/node_modules/async/mapValuesLimit.js index 93066ee..f59e36f 100644 --- a/node_modules/async/mapValuesLimit.js +++ b/node_modules/async/mapValuesLimit.js @@ -58,4 +58,4 @@ function mapValuesLimit(obj, limit, iteratee, callback) { } exports.default = (0, _awaitify2.default)(mapValuesLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/mapValuesSeries.js b/node_modules/async/mapValuesSeries.js index 560058a..5f05bf2 100644 --- a/node_modules/async/mapValuesSeries.js +++ b/node_modules/async/mapValuesSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = mapValuesSeries; @@ -32,6 +32,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function mapValuesSeries(obj, iteratee, callback) { - return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); + return (0, _mapValuesLimit2.default)(obj, 1, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/memoize.js b/node_modules/async/memoize.js index 6003e41..6535d4e 100644 --- a/node_modules/async/memoize.js +++ b/node_modules/async/memoize.js @@ -88,4 +88,4 @@ function memoize(fn, hasher = v => v) { memoized.unmemoized = fn; return memoized; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/nextTick.js b/node_modules/async/nextTick.js index e6d321b..8ebfda9 100644 --- a/node_modules/async/nextTick.js +++ b/node_modules/async/nextTick.js @@ -49,4 +49,4 @@ if (_setImmediate.hasNextTick) { } exports.default = (0, _setImmediate.wrap)(_defer); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/package.json b/node_modules/async/package.json index 9c464bc..af98905 100644 --- a/node_modules/async/package.json +++ b/node_modules/async/package.json @@ -1,7 +1,7 @@ { "name": "async", "description": "Higher-order functions and common patterns for asynchronous code", - "version": "3.2.4", + "version": "3.2.5", "main": "dist/async.js", "author": "Caolan McMahon", "homepage": "https://caolan.github.io/async/", @@ -20,7 +20,7 @@ ], "devDependencies": { "@babel/eslint-parser": "^7.16.5", - "babel-core": "^6.26.3", + "@babel/core": "7.23.2", "babel-minify": "^0.5.0", "babel-plugin-add-module-exports": "^1.0.4", "babel-plugin-istanbul": "^6.1.1", @@ -38,7 +38,7 @@ "es6-promise": "^4.2.8", "eslint": "^8.6.0", "eslint-plugin-prefer-arrow": "^1.2.3", - "fs-extra": "^10.0.0", + "fs-extra": "^11.1.1", "jsdoc": "^3.6.2", "karma": "^6.3.12", "karma-browserify": "^8.1.0", @@ -49,7 +49,7 @@ "mocha": "^6.1.4", "native-promise-only": "^0.8.0-a", "nyc": "^15.1.0", - "rollup": "^2.66.1", + "rollup": "^4.2.0", "rollup-plugin-node-resolve": "^5.2.0", "rollup-plugin-npm": "^2.0.0", "rsvp": "^4.8.5", diff --git a/node_modules/async/parallel.js b/node_modules/async/parallel.js index 76bc624..2c7976f 100644 --- a/node_modules/async/parallel.js +++ b/node_modules/async/parallel.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = parallel; @@ -175,6 +175,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function parallel(tasks, callback) { - return (0, _parallel3.default)(_eachOf2.default, tasks, callback); + return (0, _parallel3.default)(_eachOf2.default, tasks, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/parallelLimit.js b/node_modules/async/parallelLimit.js index dbe0bb8..4337957 100644 --- a/node_modules/async/parallelLimit.js +++ b/node_modules/async/parallelLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = parallelLimit; @@ -36,6 +36,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if a callback is not passed */ function parallelLimit(tasks, limit, callback) { - return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); + return (0, _parallel2.default)((0, _eachOfLimit2.default)(limit), tasks, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/priorityQueue.js b/node_modules/async/priorityQueue.js index 6006f66..16c4daa 100644 --- a/node_modules/async/priorityQueue.js +++ b/node_modules/async/priorityQueue.js @@ -57,30 +57,4 @@ var _Heap2 = _interopRequireDefault(_Heap); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = exports['default']; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, - * except this returns a promise that rejects if an error occurs. - * * The `unshift` and `unshiftAsync` methods were removed. - */ \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/queue.js b/node_modules/async/queue.js index c69becb..c01340d 100644 --- a/node_modules/async/queue.js +++ b/node_modules/async/queue.js @@ -1,14 +1,14 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = function (worker, concurrency) { - var _worker = (0, _wrapAsync2.default)(worker); - return (0, _queue2.default)((items, cb) => { - _worker(items[0], cb); - }, concurrency, 1); + var _worker = (0, _wrapAsync2.default)(worker); + return (0, _queue2.default)((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); }; var _queue = require('./internal/queue.js'); @@ -21,147 +21,4 @@ var _wrapAsync2 = _interopRequireDefault(_wrapAsync); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -module.exports = exports['default']; - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Iterable} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {number} payload - an integer that specifies how many items are - * passed to the worker function at a time. only applies if this is a - * [cargo]{@link module:ControlFlow.cargo} object - * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns - * a promise that rejects if an error occurs. - * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns - * a promise that rejects if an error occurs. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a function that sets a callback that is - * called when the number of running workers hits the `concurrency` limit, and - * further tasks will be queued. If the callback is omitted, `q.saturated()` - * returns a promise for the next occurrence. - * @property {Function} unsaturated - a function that sets a callback that is - * called when the number of running workers is less than the `concurrency` & - * `buffer` limits, and further tasks will not be queued. If the callback is - * omitted, `q.unsaturated()` returns a promise for the next occurrence. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a function that sets a callback that is called - * when the last item from the `queue` is given to a `worker`. If the callback - * is omitted, `q.empty()` returns a promise for the next occurrence. - * @property {Function} drain - a function that sets a callback that is called - * when the last item from the `queue` has returned from the `worker`. If the - * callback is omitted, `q.drain()` returns a promise for the next occurrence. - * @property {Function} error - a function that sets a callback that is called - * when a task errors. Has the signature `function(error, task)`. If the - * callback is omitted, `error()` returns a promise that rejects on the next - * error. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - * - * @example - * const q = async.queue(worker, 2) - * q.push(item1) - * q.push(item2) - * q.push(item3) - * // queues are iterable, spread into an array to inspect - * const items = [...q] // [item1, item2, item3] - * // or use for of - * for (let item of q) { - * console.log(item) - * } - * - * q.drain(() => { - * console.log('all done') - * }) - * // or - * await q.drain() - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain(function() { - * console.log('all items have been processed'); - * }); - * // or await the end - * await q.drain() - * - * // assign an error callback - * q.error(function(err, task) { - * console.error('task experienced an error'); - * }); - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * // callback is optional - * q.push({name: 'bar'}); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/race.js b/node_modules/async/race.js index 9595d88..aa167be 100644 --- a/node_modules/async/race.js +++ b/node_modules/async/race.js @@ -64,4 +64,4 @@ function race(tasks, callback) { } exports.default = (0, _awaitify2.default)(race, 2); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduce.js b/node_modules/async/reduce.js index 56e2db8..8a69548 100644 --- a/node_modules/async/reduce.js +++ b/node_modules/async/reduce.js @@ -150,4 +150,4 @@ function reduce(coll, memo, iteratee, callback) { }, err => callback(err, memo)); } exports.default = (0, _awaitify2.default)(reduce, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reduceRight.js b/node_modules/async/reduceRight.js index bee5391..5be1b68 100644 --- a/node_modules/async/reduceRight.js +++ b/node_modules/async/reduceRight.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = reduceRight; @@ -35,7 +35,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function reduceRight(array, memo, iteratee, callback) { - var reversed = [...array].reverse(); - return (0, _reduce2.default)(reversed, memo, iteratee, callback); + var reversed = [...array].reverse(); + return (0, _reduce2.default)(reversed, memo, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflect.js b/node_modules/async/reflect.js index 297ed79..3954495 100644 --- a/node_modules/async/reflect.js +++ b/node_modules/async/reflect.js @@ -75,4 +75,4 @@ function reflect(fn) { return _fn.apply(this, args); }); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reflectAll.js b/node_modules/async/reflectAll.js index a862ff0..b78d598 100644 --- a/node_modules/async/reflectAll.js +++ b/node_modules/async/reflectAll.js @@ -90,4 +90,4 @@ function reflectAll(tasks) { } return results; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/reject.js b/node_modules/async/reject.js index cabd96e..895949b 100644 --- a/node_modules/async/reject.js +++ b/node_modules/async/reject.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _reject2 = require('./internal/reject.js'); @@ -81,7 +81,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function reject(coll, iteratee, callback) { - return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); + return (0, _reject3.default)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(reject, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectLimit.js b/node_modules/async/rejectLimit.js index 1a89925..ce10edf 100644 --- a/node_modules/async/rejectLimit.js +++ b/node_modules/async/rejectLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _reject2 = require('./internal/reject.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function rejectLimit(coll, limit, iteratee, callback) { - return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _reject3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(rejectLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/rejectSeries.js b/node_modules/async/rejectSeries.js index 6e1a1c5..c08e413 100644 --- a/node_modules/async/rejectSeries.js +++ b/node_modules/async/rejectSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _reject2 = require('./internal/reject.js'); @@ -37,7 +37,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is passed */ function rejectSeries(coll, iteratee, callback) { - return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _reject3.default)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(rejectSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retry.js b/node_modules/async/retry.js index dba3030..a4b0235 100644 --- a/node_modules/async/retry.js +++ b/node_modules/async/retry.js @@ -156,4 +156,4 @@ function parseTimes(acc, t) { throw new Error("Invalid arguments for async.retry"); } } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/retryable.js b/node_modules/async/retryable.js index 1b1147c..68256c3 100644 --- a/node_modules/async/retryable.js +++ b/node_modules/async/retryable.js @@ -74,4 +74,4 @@ function retryable(opts, task) { return callback[_promiseCallback.PROMISE_SYMBOL]; }); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/select.js b/node_modules/async/select.js index 303dc1f..2c9a63d 100644 --- a/node_modules/async/select.js +++ b/node_modules/async/select.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -87,7 +87,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function filter(coll, iteratee, callback) { - return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); + return (0, _filter3.default)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filter, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectLimit.js b/node_modules/async/selectLimit.js index 89e55f5..d3b3f50 100644 --- a/node_modules/async/selectLimit.js +++ b/node_modules/async/selectLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -39,7 +39,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function filterLimit(coll, limit, iteratee, callback) { - return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _filter3.default)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filterLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/selectSeries.js b/node_modules/async/selectSeries.js index a045e52..019a2d0 100644 --- a/node_modules/async/selectSeries.js +++ b/node_modules/async/selectSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _filter2 = require('./internal/filter.js'); @@ -37,7 +37,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function filterSeries(coll, iteratee, callback) { - return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _filter3.default)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(filterSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/seq.js b/node_modules/async/seq.js index 28c825f..e7881cd 100644 --- a/node_modules/async/seq.js +++ b/node_modules/async/seq.js @@ -76,4 +76,4 @@ function seq(...functions) { return cb[_promiseCallback.PROMISE_SYMBOL]; }; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/series.js b/node_modules/async/series.js index 56e78f9..60c17ed 100644 --- a/node_modules/async/series.js +++ b/node_modules/async/series.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = series; @@ -181,6 +181,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function series(tasks, callback) { - return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); + return (0, _parallel3.default)(_eachOfSeries2.default, tasks, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/setImmediate.js b/node_modules/async/setImmediate.js index c712ec3..eea8677 100644 --- a/node_modules/async/setImmediate.js +++ b/node_modules/async/setImmediate.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _setImmediate = require('./internal/setImmediate.js'); @@ -42,4 +42,4 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * }, 1, 2, 3); */ exports.default = _setImmediate2.default; -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/some.js b/node_modules/async/some.js index 2046cf6..a5bd328 100644 --- a/node_modules/async/some.js +++ b/node_modules/async/some.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -116,7 +116,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * */ function some(coll, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)(_eachOf2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(some, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someLimit.js b/node_modules/async/someLimit.js index c8a295a..3a8096f 100644 --- a/node_modules/async/someLimit.js +++ b/node_modules/async/someLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -41,7 +41,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function someLimit(coll, limit, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)((0, _eachOfLimit2.default)(limit), coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(someLimit, 4); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/someSeries.js b/node_modules/async/someSeries.js index ee0654b..51aad19 100644 --- a/node_modules/async/someSeries.js +++ b/node_modules/async/someSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); var _createTester = require('./internal/createTester.js'); @@ -40,7 +40,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback provided */ function someSeries(coll, iteratee, callback) { - return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); + return (0, _createTester2.default)(Boolean, res => res)(_eachOfSeries2.default, coll, iteratee, callback); } exports.default = (0, _awaitify2.default)(someSeries, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/sortBy.js b/node_modules/async/sortBy.js index d17fb6a..0988b61 100644 --- a/node_modules/async/sortBy.js +++ b/node_modules/async/sortBy.js @@ -187,4 +187,4 @@ function sortBy(coll, iteratee, callback) { } } exports.default = (0, _awaitify2.default)(sortBy, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timeout.js b/node_modules/async/timeout.js index dd58eb3..46bb233 100644 --- a/node_modules/async/timeout.js +++ b/node_modules/async/timeout.js @@ -86,4 +86,4 @@ function timeout(asyncFn, milliseconds, info) { fn(...args); }); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/times.js b/node_modules/async/times.js index 4484c73..ca7df51 100644 --- a/node_modules/async/times.js +++ b/node_modules/async/times.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = times; @@ -45,6 +45,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * }); */ function times(n, iteratee, callback) { - return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); + return (0, _timesLimit2.default)(n, Infinity, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesLimit.js b/node_modules/async/timesLimit.js index 9fb0ba3..f76de25 100644 --- a/node_modules/async/timesLimit.js +++ b/node_modules/async/timesLimit.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = timesLimit; @@ -37,7 +37,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is provided */ function timesLimit(count, limit, iteratee, callback) { - var _iteratee = (0, _wrapAsync2.default)(iteratee); - return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); + var _iteratee = (0, _wrapAsync2.default)(iteratee); + return (0, _mapLimit2.default)((0, _range2.default)(count), limit, _iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/timesSeries.js b/node_modules/async/timesSeries.js index a10f0cb..776b4f3 100644 --- a/node_modules/async/timesSeries.js +++ b/node_modules/async/timesSeries.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = timesSeries; @@ -27,6 +27,6 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @returns {Promise} a promise, if no callback is provided */ function timesSeries(n, iteratee, callback) { - return (0, _timesLimit2.default)(n, 1, iteratee, callback); + return (0, _timesLimit2.default)(n, 1, iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/transform.js b/node_modules/async/transform.js index 75b754e..75dadea 100644 --- a/node_modules/async/transform.js +++ b/node_modules/async/transform.js @@ -170,4 +170,4 @@ function transform(coll, accumulator, iteratee, callback) { }, err => callback(err, accumulator)); return callback[_promiseCallback.PROMISE_SYMBOL]; } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/tryEach.js b/node_modules/async/tryEach.js index 82fe8ec..7e63f9d 100644 --- a/node_modules/async/tryEach.js +++ b/node_modules/async/tryEach.js @@ -75,4 +75,4 @@ function tryEach(tasks, callback) { } exports.default = (0, _awaitify2.default)(tryEach); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/unmemoize.js b/node_modules/async/unmemoize.js index 47a92b4..badd7ae 100644 --- a/node_modules/async/unmemoize.js +++ b/node_modules/async/unmemoize.js @@ -22,4 +22,4 @@ function unmemoize(fn) { return (fn.unmemoized || fn)(...args); }; } -module.exports = exports["default"]; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/until.js b/node_modules/async/until.js index 3c71e51..4b69b97 100644 --- a/node_modules/async/until.js +++ b/node_modules/async/until.js @@ -1,7 +1,7 @@ 'use strict'; Object.defineProperty(exports, "__esModule", { - value: true + value: true }); exports.default = until; @@ -55,7 +55,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * }) */ function until(test, iteratee, callback) { - const _test = (0, _wrapAsync2.default)(test); - return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); + const _test = (0, _wrapAsync2.default)(test); + return (0, _whilst2.default)(cb => _test((err, truth) => cb(err, !truth)), iteratee, callback); } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/waterfall.js b/node_modules/async/waterfall.js index fcd0dc1..c3242f7 100644 --- a/node_modules/async/waterfall.js +++ b/node_modules/async/waterfall.js @@ -102,4 +102,4 @@ function waterfall(tasks, callback) { } exports.default = (0, _awaitify2.default)(waterfall); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/whilst.js b/node_modules/async/whilst.js index 32a4776..4165543 100644 --- a/node_modules/async/whilst.js +++ b/node_modules/async/whilst.js @@ -28,7 +28,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de * @method * @category Control Flow * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). + * execution of `iteratee`. Invoked with (callback). * @param {AsyncFunction} iteratee - An async function which is called each time * `test` passes. Invoked with (callback). * @param {Function} [callback] - A callback which is called after the test @@ -75,4 +75,4 @@ function whilst(test, iteratee, callback) { return _test(check); } exports.default = (0, _awaitify2.default)(whilst, 3); -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/async/wrapSync.js b/node_modules/async/wrapSync.js index 3c3bf88..ddc3f02 100644 --- a/node_modules/async/wrapSync.js +++ b/node_modules/async/wrapSync.js @@ -102,7 +102,7 @@ function handlePromise(promise, callback) { return promise.then(value => { invokeCallback(callback, null, value); }, err => { - invokeCallback(callback, err && err.message ? err : new Error(err)); + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); }); } @@ -115,4 +115,4 @@ function invokeCallback(callback, error, value) { }, err); } } -module.exports = exports['default']; \ No newline at end of file +module.exports = exports.default; \ No newline at end of file diff --git a/node_modules/before-after-hook/README.md b/node_modules/before-after-hook/README.md index 1439db3..07d7756 100644 --- a/node_modules/before-after-hook/README.md +++ b/node_modules/before-after-hook/README.md @@ -3,9 +3,7 @@ > asynchronous hooks for internal functionality [![npm downloads](https://img.shields.io/npm/dw/before-after-hook.svg)](https://www.npmjs.com/package/before-after-hook) -[![Build Status](https://travis-ci.org/gr2m/before-after-hook.svg?branch=master)](https://travis-ci.org/gr2m/before-after-hook) -[![Coverage Status](https://coveralls.io/repos/gr2m/before-after-hook/badge.svg?branch=master)](https://coveralls.io/r/gr2m/before-after-hook?branch=master) -[![Greenkeeper badge](https://badges.greenkeeper.io/gr2m/before-after-hook.svg)](https://greenkeeper.io/) +[![Test](https://github.com/gr2m/before-after-hook/actions/workflows/test.yml/badge.svg)](https://github.com/gr2m/before-after-hook/actions/workflows/test.yml) ## Usage diff --git a/node_modules/before-after-hook/index.d.ts b/node_modules/before-after-hook/index.d.ts index 9c95de3..817bf93 100644 --- a/node_modules/before-after-hook/index.d.ts +++ b/node_modules/before-after-hook/index.d.ts @@ -1,34 +1,34 @@ type HookMethod = ( options: Options -) => Result | Promise +) => Result | Promise; -type BeforeHook = (options: Options) => void | Promise +type BeforeHook = (options: Options) => void | Promise; type ErrorHook = ( error: Error, options: Options -) => void | Promise +) => unknown | Promise; type AfterHook = ( result: Result, options: Options -) => void | Promise +) => void | Promise; type WrapHook = ( hookMethod: HookMethod, options: Options -) => Result | Promise +) => Result | Promise; type AnyHook = | BeforeHook | ErrorHook | AfterHook - | WrapHook + | WrapHook; -type TypeStoreKeyLong = 'Options' | 'Result' | 'Error' -type TypeStoreKeyShort = 'O' | 'R' | 'E' +type TypeStoreKeyLong = "Options" | "Result" | "Error"; +type TypeStoreKeyShort = "O" | "R" | "E"; type TypeStore = | ({ [key in TypeStoreKeyLong]?: any } & { [key in TypeStoreKeyShort]?: never }) | ({ [key in TypeStoreKeyLong]?: never } & - { [key in TypeStoreKeyShort]?: any }) + { [key in TypeStoreKeyShort]?: any }); type GetType< Store extends TypeStore, LongKey extends TypeStoreKeyLong, @@ -37,7 +37,7 @@ type GetType< ? Store[LongKey] : ShortKey extends keyof Store ? Store[ShortKey] - : any + : any; export interface HookCollection< HooksType extends Record = Record< @@ -52,100 +52,100 @@ export interface HookCollection< ( name: Name | Name[], hookMethod: HookMethod< - GetType, - GetType + GetType, + GetType >, - options?: GetType - ): Promise> + options?: GetType + ): Promise>; /** * Add `before` hook for given `name` */ before( name: Name, - beforeHook: BeforeHook> - ): void + beforeHook: BeforeHook> + ): void; /** * Add `error` hook for given `name` */ error( name: Name, errorHook: ErrorHook< - GetType, - GetType + GetType, + GetType > - ): void + ): void; /** * Add `after` hook for given `name` */ after( name: Name, afterHook: AfterHook< - GetType, - GetType + GetType, + GetType > - ): void + ): void; /** * Add `wrap` hook for given `name` */ wrap( name: Name, wrapHook: WrapHook< - GetType, - GetType + GetType, + GetType > - ): void + ): void; /** * Remove added hook for given `name` */ remove( name: Name, hook: AnyHook< - GetType, - GetType, - GetType + GetType, + GetType, + GetType > - ): void + ): void; /** * Public API */ api: Pick< HookCollection, - 'before' | 'error' | 'after' | 'wrap' | 'remove' - > + "before" | "error" | "after" | "wrap" | "remove" + >; } export interface HookSingular { /** * Invoke before and after hooks */ - (hookMethod: HookMethod, options?: Options): Promise + (hookMethod: HookMethod, options?: Options): Promise; /** * Add `before` hook */ - before(beforeHook: BeforeHook): void + before(beforeHook: BeforeHook): void; /** * Add `error` hook */ - error(errorHook: ErrorHook): void + error(errorHook: ErrorHook): void; /** * Add `after` hook */ - after(afterHook: AfterHook): void + after(afterHook: AfterHook): void; /** * Add `wrap` hook */ - wrap(wrapHook: WrapHook): void + wrap(wrapHook: WrapHook): void; /** * Remove added hook */ - remove(hook: AnyHook): void + remove(hook: AnyHook): void; /** * Public API */ api: Pick< HookSingular, - 'before' | 'error' | 'after' | 'wrap' | 'remove' - > + "before" | "error" | "after" | "wrap" | "remove" + >; } type Collection = new < @@ -153,12 +153,12 @@ type Collection = new < string, { Options: any; Result: any; Error: any } > ->() => HookCollection +>() => HookCollection; type Singular = new < Options = any, Result = any, Error = any ->() => HookSingular +>() => HookSingular; interface Hook { new < @@ -166,21 +166,21 @@ interface Hook { string, { Options: any; Result: any; Error: any } > - >(): HookCollection + >(): HookCollection; /** * Creates a collection of hooks */ - Collection: Collection + Collection: Collection; /** * Creates a nameless hook that supports strict typings */ - Singular: Singular + Singular: Singular; } -export const Hook: Hook -export const Collection: Collection -export const Singular: Singular +export const Hook: Hook; +export const Collection: Collection; +export const Singular: Singular; -export default Hook +export default Hook; diff --git a/node_modules/before-after-hook/index.js b/node_modules/before-after-hook/index.js index a97d89b..6b60d3c 100644 --- a/node_modules/before-after-hook/index.js +++ b/node_modules/before-after-hook/index.js @@ -1,57 +1,61 @@ -var register = require('./lib/register') -var addHook = require('./lib/add') -var removeHook = require('./lib/remove') +var register = require("./lib/register"); +var addHook = require("./lib/add"); +var removeHook = require("./lib/remove"); // bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) - -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef - - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) +var bind = Function.bind; +var bindable = bind.bind(bind); + +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); } -function HookSingular () { - var singularHookName = 'h' +function HookSingular() { + var singularHookName = "h"; var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; } -function HookCollection () { +function HookCollection() { var state = { - registry: {} - } + registry: {}, + }; - var hook = register.bind(null, state) - bindApi(hook, state) + var hook = register.bind(null, state); + bindApi(hook, state); - return hook + return hook; } -var collectionHookDeprecationMessageDisplayed = false -function Hook () { +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { if (!collectionHookDeprecationMessageDisplayed) { - console.warn('[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4') - collectionHookDeprecationMessageDisplayed = true + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; } - return HookCollection() + return HookCollection(); } -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); -module.exports = Hook +module.exports = Hook; // expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; diff --git a/node_modules/before-after-hook/package.json b/node_modules/before-after-hook/package.json index 25f4756..533a3eb 100644 --- a/node_modules/before-after-hook/package.json +++ b/node_modules/before-after-hook/package.json @@ -1,6 +1,6 @@ { "name": "before-after-hook", - "version": "2.2.2", + "version": "2.2.3", "description": "asynchronous before/error/after hooks for internal functionality", "main": "index.js", "files": [ @@ -13,8 +13,8 @@ "prebuild": "rimraf dist && mkdirp dist", "build": "browserify index.js --standalone=Hook > dist/before-after-hook.js", "postbuild": "uglifyjs dist/before-after-hook.js -mc > dist/before-after-hook.min.js", - "lint": "prettier --check '{lib,test,examples}/**/*' README.md package.json", - "lint:fix": "prettier --write '{lib,test,examples}/**/*' README.md package.json", + "lint": "prettier --check '{lib,test,examples}/**/*' 'index.*' README.md package.json", + "lint:fix": "prettier --write '{lib,test,examples}/**/*' 'index.*' README.md package.json", "pretest": "npm run -s lint", "test": "npm run -s test:node | tap-spec", "posttest": "npm run validate:ts", @@ -44,7 +44,7 @@ "mkdirp": "^1.0.3", "prettier": "^2.0.0", "rimraf": "^3.0.0", - "semantic-release": "^17.0.0", + "semantic-release": "^19.0.3", "simple-mock": "^0.8.0", "tap-min": "^2.0.0", "tap-spec": "^5.0.0", @@ -53,14 +53,19 @@ "uglify-js": "^3.9.0" }, "release": { - "publish": [ - "@semantic-release/npm", + "branches": [ + "+([0-9]).x", + "main", + "next", { - "path": "@semantic-release/github", - "assets": [ - "dist/*.js" - ] + "name": "beta", + "prerelease": true } ] + }, + "renovate": { + "extends": [ + "github>gr2m/.github" + ] } } diff --git a/node_modules/binary-extensions/binary-extensions.json b/node_modules/binary-extensions/binary-extensions.json index 4aab383..ac08048 100644 --- a/node_modules/binary-extensions/binary-extensions.json +++ b/node_modules/binary-extensions/binary-extensions.json @@ -7,6 +7,9 @@ "a", "aac", "adp", + "afdesign", + "afphoto", + "afpub", "ai", "aif", "aiff", diff --git a/node_modules/binary-extensions/license b/node_modules/binary-extensions/license index 401b1c7..5493a1a 100644 --- a/node_modules/binary-extensions/license +++ b/node_modules/binary-extensions/license @@ -1,6 +1,7 @@ MIT License -Copyright (c) 2019 Sindre Sorhus (https://sindresorhus.com), Paul Miller (https://paulmillr.com) +Copyright (c) Sindre Sorhus (https://sindresorhus.com) +Copyright (c) Paul Miller (https://paulmillr.com) 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: diff --git a/node_modules/binary-extensions/package.json b/node_modules/binary-extensions/package.json index c4d3641..4710c33 100644 --- a/node_modules/binary-extensions/package.json +++ b/node_modules/binary-extensions/package.json @@ -1,14 +1,16 @@ { "name": "binary-extensions", - "version": "2.2.0", + "version": "2.3.0", "description": "List of binary file extensions", "license": "MIT", "repository": "sindresorhus/binary-extensions", + "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" + "url": "https://sindresorhus.com" }, + "sideEffects": false, "engines": { "node": ">=8" }, diff --git a/node_modules/binary-extensions/readme.md b/node_modules/binary-extensions/readme.md index 3e25dd8..88519b3 100644 --- a/node_modules/binary-extensions/readme.md +++ b/node_modules/binary-extensions/readme.md @@ -4,14 +4,12 @@ The list is just a [JSON file](binary-extensions.json) and can be used anywhere. - ## Install -``` -$ npm install binary-extensions +```sh +npm install binary-extensions ``` - ## Usage ```js @@ -21,21 +19,7 @@ console.log(binaryExtensions); //=> ['3ds', '3g2', …] ``` - ## Related - [is-binary-path](https://github.com/sindresorhus/is-binary-path) - Check if a filepath is a binary file - [text-extensions](https://github.com/sindresorhus/text-extensions) - List of text file extensions - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/node_modules/chokidar/README.md b/node_modules/chokidar/README.md index 5cfb81e..d6a57fd 100644 --- a/node_modules/chokidar/README.md +++ b/node_modules/chokidar/README.md @@ -13,6 +13,7 @@ Node.js `fs.watch`: * Often reports events twice. * Emits most changes as `rename`. * Does not provide an easy way to recursively watch file trees. +* Does not support recursive watching on Linux. Node.js `fs.watchFile`: @@ -46,7 +47,7 @@ On MacOS, chokidar by default uses a native extension exposing the Darwin implementations like `kqueue` available on most \*nix platforms. Chokidar still does have to do some work to normalize the events received that way as well. -On other platforms, the `fs.watch`-based implementation is the default, which +On most other platforms, the `fs.watch`-based implementation is the default, which avoids polling and keeps CPU usage down. Be advised that chokidar will initiate watchers recursively for everything within scope of the paths that have been specified, so be judicious about not wasting system resources by watching much @@ -254,8 +255,8 @@ Available events: `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `ready`, Additionally `all` is available which gets emitted with the underlying event name and path for every event other than `ready`, `raw`, and `error`. `raw` is internal, use it carefully. * `.unwatch(path / paths)`: Stop watching files, directories, or glob patterns. -Takes an array of strings or just one string. Use with `await` to ensure bugs don't happen. -* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. +Takes an array of strings or just one string. +* `.close()`: **async** Removes all listeners from watched files. Asynchronous, returns Promise. Use with `await` to ensure bugs don't happen. * `.getWatched()`: Returns an object representing all the paths on the file system being watched by this `FSWatcher` instance. The object's keys are all the directories (using absolute paths unless the `cwd` option was used), and the @@ -264,7 +265,7 @@ values are arrays of the names of the items contained in each directory. ## CLI If you need a CLI interface for your file watching, check out -[chokidar-cli](https://github.com/kimmobrunfeldt/chokidar-cli), allowing you to +[chokidar-cli](https://github.com/open-cli-tools/chokidar-cli), allowing you to execute a command on each change, or get a stdio stream of change events. ## Install Troubleshooting diff --git a/node_modules/chokidar/index.js b/node_modules/chokidar/index.js index a14deeb..ed4b6d5 100644 --- a/node_modules/chokidar/index.js +++ b/node_modules/chokidar/index.js @@ -48,7 +48,8 @@ const { EMPTY_FN, isWindows, - isMacos + isMacos, + isIBMi } = require('./lib/constants'); const stat = promisify(fs.stat); @@ -330,6 +331,11 @@ constructor(_opts) { opts.usePolling = isMacos; } + // Always default to polling on IBM i because fs.watch() is not available on IBM i. + if(isIBMi) { + opts.usePolling = true; + } + // Global override (useful for end-developers that need to force polling for all // instances of chokidar, regardless of usage/dependency depth) const envPoll = process.env.CHOKIDAR_USEPOLLING; diff --git a/node_modules/chokidar/lib/constants.js b/node_modules/chokidar/lib/constants.js index 84c2d98..1454f85 100644 --- a/node_modules/chokidar/lib/constants.js +++ b/node_modules/chokidar/lib/constants.js @@ -2,6 +2,7 @@ const {sep} = require('path'); const {platform} = process; +const os = require('os'); exports.EV_ALL = 'all'; exports.EV_READY = 'ready'; @@ -61,3 +62,4 @@ exports.IDENTITY_FN = val => val; exports.isWindows = platform === 'win32'; exports.isMacos = platform === 'darwin'; exports.isLinux = platform === 'linux'; +exports.isIBMi = os.type() === 'OS400'; diff --git a/node_modules/chokidar/lib/fsevents-handler.js b/node_modules/chokidar/lib/fsevents-handler.js index 5c84bad..0f7f2cb 100644 --- a/node_modules/chokidar/lib/fsevents-handler.js +++ b/node_modules/chokidar/lib/fsevents-handler.js @@ -104,7 +104,8 @@ const createFSEventsInstance = (path, callback) => { * @returns {Function} closer */ function setFSEventsListener(path, realPath, listener, rawEmitter) { - let watchPath = sysPath.extname(path) ? sysPath.dirname(path) : path; + let watchPath = sysPath.extname(realPath) ? sysPath.dirname(realPath) : realPath; + const parentPath = sysPath.dirname(watchPath); let cont = FSEventsWatchers.get(watchPath); diff --git a/node_modules/chokidar/lib/nodefs-handler.js b/node_modules/chokidar/lib/nodefs-handler.js index 3a39643..199cfe9 100644 --- a/node_modules/chokidar/lib/nodefs-handler.js +++ b/node_modules/chokidar/lib/nodefs-handler.js @@ -421,7 +421,15 @@ async _handleSymlink(entry, directory, path, item) { if (!this.fsw.options.followSymlinks) { // watch symlink directly (don't follow) and detect changes this.fsw._incrReadyCount(); - const linkPath = await fsrealpath(path); + + let linkPath; + try { + linkPath = await fsrealpath(path); + } catch (e) { + this.fsw._emitReady(); + return true; + } + if (this.fsw.closed) return; if (dir.has(item)) { if (this.fsw._symlinkPaths.get(full) !== linkPath) { diff --git a/node_modules/chokidar/package.json b/node_modules/chokidar/package.json index 9ebbb40..6c3cd27 100644 --- a/node_modules/chokidar/package.json +++ b/node_modules/chokidar/package.json @@ -1,7 +1,7 @@ { "name": "chokidar", "description": "Minimal and efficient cross-platform file watching library", - "version": "3.5.1", + "version": "3.5.3", "homepage": "https://github.com/paulmillr/chokidar", "author": "Paul Miller (https://paulmillr.com)", "contributors": [ @@ -13,20 +13,20 @@ }, "main": "index.js", "dependencies": { - "anymatch": "~3.1.1", + "anymatch": "~3.1.2", "braces": "~3.0.2", - "glob-parent": "~5.1.0", + "glob-parent": "~5.1.2", "is-binary-path": "~2.1.0", "is-glob": "~4.0.1", "normalize-path": "~3.0.0", - "readdirp": "~3.5.0" + "readdirp": "~3.6.0" }, "optionalDependencies": { - "fsevents": "~2.3.1" + "fsevents": "~2.3.2" }, "devDependencies": { "@types/node": "^14", - "chai": "^4.2", + "chai": "^4.3", "dtslint": "^3.3.0", "eslint": "^7.0.0", "mocha": "^7.0.0", @@ -34,6 +34,7 @@ "rimraf": "^3.0.0", "sinon": "^9.0.1", "sinon-chai": "^3.3.0", + "typescript": "~4.4.3", "upath": "^1.2.0" }, "files": [ @@ -52,7 +53,7 @@ "scripts": { "dtslint": "dtslint types", "lint": "eslint --report-unused-disable-directives --ignore-path .gitignore .", - "mocha": "mocha --exit --timeout 60000", + "mocha": "mocha --exit --timeout 90000", "test": "npm run lint && npm run mocha" }, "keywords": [ @@ -74,5 +75,11 @@ "html", "text" ] - } + }, + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ] } diff --git a/node_modules/chokidar/types/index.d.ts b/node_modules/chokidar/types/index.d.ts index af0b558..aab8e33 100644 --- a/node_modules/chokidar/types/index.d.ts +++ b/node_modules/chokidar/types/index.d.ts @@ -4,6 +4,7 @@ import * as fs from "fs"; import { EventEmitter } from "events"; +import { Matcher } from 'anymatch'; export class FSWatcher extends EventEmitter implements fs.FSWatcher { options: WatchOptions; @@ -17,13 +18,13 @@ export class FSWatcher extends EventEmitter implements fs.FSWatcher { * Add files, directories, or glob patterns for tracking. Takes an array of strings or just one * string. */ - add(paths: string | ReadonlyArray): void; + add(paths: string | ReadonlyArray): this; /** * Stop watching files, directories, or glob patterns. Takes an array of strings or just one * string. */ - unwatch(paths: string | ReadonlyArray): void; + unwatch(paths: string | ReadonlyArray): this; /** * Returns an object representing all the paths on the file system being watched by this @@ -79,7 +80,7 @@ export interface WatchOptions { * (the path), second time with two arguments (the path and the * [`fs.Stats`](https://nodejs.org/api/fs.html#fs_class_fs_stats) object of that path). */ - ignored?: any; + ignored?: Matcher; /** * If set to `false` then `add`/`addDir` events are also emitted for matching paths while diff --git a/node_modules/cliui/node_modules/ansi-regex/index.js b/node_modules/cliui/node_modules/ansi-regex/index.js deleted file mode 100644 index 616ff83..0000000 --- a/node_modules/cliui/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; diff --git a/node_modules/cliui/node_modules/ansi-regex/license b/node_modules/cliui/node_modules/ansi-regex/license deleted file mode 100644 index e7af2f7..0000000 --- a/node_modules/cliui/node_modules/ansi-regex/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -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. diff --git a/node_modules/cliui/node_modules/ansi-regex/package.json b/node_modules/cliui/node_modules/ansi-regex/package.json deleted file mode 100644 index 017f531..0000000 --- a/node_modules/cliui/node_modules/ansi-regex/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "ansi-regex", - "version": "5.0.1", - "description": "Regular expression for matching ANSI escape codes", - "license": "MIT", - "repository": "chalk/ansi-regex", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd", - "view-supported": "node fixtures/view-codes.js" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "cli", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "command-line", - "text", - "regex", - "regexp", - "re", - "match", - "test", - "find", - "pattern" - ], - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.9.0", - "xo": "^0.25.3" - } -} diff --git a/node_modules/cliui/node_modules/ansi-regex/readme.md b/node_modules/cliui/node_modules/ansi-regex/readme.md deleted file mode 100644 index 4d848bc..0000000 --- a/node_modules/cliui/node_modules/ansi-regex/readme.md +++ /dev/null @@ -1,78 +0,0 @@ -# ansi-regex - -> Regular expression for matching [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) - - -## Install - -``` -$ npm install ansi-regex -``` - - -## Usage - -```js -const ansiRegex = require('ansi-regex'); - -ansiRegex().test('\u001B[4mcake\u001B[0m'); -//=> true - -ansiRegex().test('cake'); -//=> false - -'\u001B[4mcake\u001B[0m'.match(ansiRegex()); -//=> ['\u001B[4m', '\u001B[0m'] - -'\u001B[4mcake\u001B[0m'.match(ansiRegex({onlyFirst: true})); -//=> ['\u001B[4m'] - -'\u001B]8;;https://github.com\u0007click\u001B]8;;\u0007'.match(ansiRegex()); -//=> ['\u001B]8;;https://github.com\u0007', '\u001B]8;;\u0007'] -``` - - -## API - -### ansiRegex(options?) - -Returns a regex for matching ANSI escape codes. - -#### options - -Type: `object` - -##### onlyFirst - -Type: `boolean`
-Default: `false` *(Matches any ANSI escape codes in a string)* - -Match only the first ANSI escape. - - -## FAQ - -### Why do you test for codes not in the ECMA 48 standard? - -Some of the codes we run as a test are codes that we acquired finding various lists of non-standard or manufacturer specific codes. We test for both standard and non-standard codes, as most of them follow the same or similar format and can be safely matched in strings without the risk of removing actual string content. There are a few non-standard control codes that do not follow the traditional format (i.e. they end in numbers) thus forcing us to exclude them from the test because we cannot reliably match them. - -On the historical side, those ECMA standards were established in the early 90's whereas the VT100, for example, was designed in the mid/late 70's. At that point in time, control codes were still pretty ungoverned and engineers used them for a multitude of things, namely to activate hardware ports that may have been proprietary. Somewhere else you see a similar 'anarchy' of codes is in the x86 architecture for processors; there are a ton of "interrupts" that can mean different things on certain brands of processors, most of which have been phased out. - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/node_modules/cliui/node_modules/is-fullwidth-code-point/index.js b/node_modules/cliui/node_modules/is-fullwidth-code-point/index.js deleted file mode 100644 index 671f97f..0000000 --- a/node_modules/cliui/node_modules/is-fullwidth-code-point/index.js +++ /dev/null @@ -1,50 +0,0 @@ -/* eslint-disable yoda */ -'use strict'; - -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } - - return false; -}; - -module.exports = isFullwidthCodePoint; -module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/cliui/node_modules/is-fullwidth-code-point/package.json b/node_modules/cliui/node_modules/is-fullwidth-code-point/package.json deleted file mode 100644 index 2137e88..0000000 --- a/node_modules/cliui/node_modules/is-fullwidth-code-point/package.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "name": "is-fullwidth-code-point", - "version": "3.0.0", - "description": "Check if the character represented by a given Unicode code point is fullwidth", - "license": "MIT", - "repository": "sindresorhus/is-fullwidth-code-point", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd-check" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "fullwidth", - "full-width", - "full", - "width", - "unicode", - "character", - "string", - "codepoint", - "code", - "point", - "is", - "detect", - "check" - ], - "devDependencies": { - "ava": "^1.3.1", - "tsd-check": "^0.5.0", - "xo": "^0.24.0" - } -} diff --git a/node_modules/cliui/node_modules/is-fullwidth-code-point/readme.md b/node_modules/cliui/node_modules/is-fullwidth-code-point/readme.md deleted file mode 100644 index 4236bba..0000000 --- a/node_modules/cliui/node_modules/is-fullwidth-code-point/readme.md +++ /dev/null @@ -1,39 +0,0 @@ -# is-fullwidth-code-point [![Build Status](https://travis-ci.org/sindresorhus/is-fullwidth-code-point.svg?branch=master)](https://travis-ci.org/sindresorhus/is-fullwidth-code-point) - -> Check if the character represented by a given [Unicode code point](https://en.wikipedia.org/wiki/Code_point) is [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) - - -## Install - -``` -$ npm install is-fullwidth-code-point -``` - - -## Usage - -```js -const isFullwidthCodePoint = require('is-fullwidth-code-point'); - -isFullwidthCodePoint('谢'.codePointAt(0)); -//=> true - -isFullwidthCodePoint('a'.codePointAt(0)); -//=> false -``` - - -## API - -### isFullwidthCodePoint(codePoint) - -#### codePoint - -Type: `number` - -The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/cliui/node_modules/string-width/index.js b/node_modules/cliui/node_modules/string-width/index.js deleted file mode 100644 index f4d261a..0000000 --- a/node_modules/cliui/node_modules/string-width/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; -const stripAnsi = require('strip-ansi'); -const isFullwidthCodePoint = require('is-fullwidth-code-point'); -const emojiRegex = require('emoji-regex'); - -const stringWidth = string => { - if (typeof string !== 'string' || string.length === 0) { - return 0; - } - - string = stripAnsi(string); - - if (string.length === 0) { - return 0; - } - - string = string.replace(emojiRegex(), ' '); - - let width = 0; - - for (let i = 0; i < string.length; i++) { - const code = string.codePointAt(i); - - // Ignore control characters - if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { - continue; - } - - // Ignore combining characters - if (code >= 0x300 && code <= 0x36F) { - continue; - } - - // Surrogates - if (code > 0xFFFF) { - i++; - } - - width += isFullwidthCodePoint(code) ? 2 : 1; - } - - return width; -}; - -module.exports = stringWidth; -// TODO: remove this in the next major version -module.exports.default = stringWidth; diff --git a/node_modules/cliui/node_modules/string-width/license b/node_modules/cliui/node_modules/string-width/license deleted file mode 100644 index e7af2f7..0000000 --- a/node_modules/cliui/node_modules/string-width/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -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. diff --git a/node_modules/cliui/node_modules/string-width/package.json b/node_modules/cliui/node_modules/string-width/package.json deleted file mode 100644 index 28ba7b4..0000000 --- a/node_modules/cliui/node_modules/string-width/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "string-width", - "version": "4.2.3", - "description": "Get the visual width of a string - the number of columns required to display it", - "license": "MIT", - "repository": "sindresorhus/string-width", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "string", - "character", - "unicode", - "width", - "visual", - "column", - "columns", - "fullwidth", - "full-width", - "full", - "ansi", - "escape", - "codes", - "cli", - "command-line", - "terminal", - "console", - "cjk", - "chinese", - "japanese", - "korean", - "fixed-width" - ], - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "devDependencies": { - "ava": "^1.4.1", - "tsd": "^0.7.1", - "xo": "^0.24.0" - } -} diff --git a/node_modules/cliui/node_modules/string-width/readme.md b/node_modules/cliui/node_modules/string-width/readme.md deleted file mode 100644 index bdd3141..0000000 --- a/node_modules/cliui/node_modules/string-width/readme.md +++ /dev/null @@ -1,50 +0,0 @@ -# string-width - -> Get the visual width of a string - the number of columns required to display it - -Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. - -Useful to be able to measure the actual width of command-line output. - - -## Install - -``` -$ npm install string-width -``` - - -## Usage - -```js -const stringWidth = require('string-width'); - -stringWidth('a'); -//=> 1 - -stringWidth('古'); -//=> 2 - -stringWidth('\u001B[1m古\u001B[22m'); -//=> 2 -``` - - -## Related - -- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module -- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string -- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string - - ---- - -
- - Get professional support for this package with a Tidelift subscription - -
- - Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. -
-
diff --git a/node_modules/cliui/node_modules/strip-ansi/index.js b/node_modules/cliui/node_modules/strip-ansi/index.js deleted file mode 100644 index 9a593df..0000000 --- a/node_modules/cliui/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -const ansiRegex = require('ansi-regex'); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/cliui/node_modules/strip-ansi/license b/node_modules/cliui/node_modules/strip-ansi/license deleted file mode 100644 index e7af2f7..0000000 --- a/node_modules/cliui/node_modules/strip-ansi/license +++ /dev/null @@ -1,9 +0,0 @@ -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -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. diff --git a/node_modules/cliui/node_modules/strip-ansi/package.json b/node_modules/cliui/node_modules/strip-ansi/package.json deleted file mode 100644 index 1a41108..0000000 --- a/node_modules/cliui/node_modules/strip-ansi/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "strip-ansi", - "version": "6.0.1", - "description": "Strip ANSI escape codes from a string", - "license": "MIT", - "repository": "chalk/strip-ansi", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=8" - }, - "scripts": { - "test": "xo && ava && tsd" - }, - "files": [ - "index.js", - "index.d.ts" - ], - "keywords": [ - "strip", - "trim", - "remove", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "devDependencies": { - "ava": "^2.4.0", - "tsd": "^0.10.0", - "xo": "^0.25.3" - } -} diff --git a/node_modules/cliui/node_modules/strip-ansi/readme.md b/node_modules/cliui/node_modules/strip-ansi/readme.md deleted file mode 100644 index 7c4b56d..0000000 --- a/node_modules/cliui/node_modules/strip-ansi/readme.md +++ /dev/null @@ -1,46 +0,0 @@ -# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) - -> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string - - -## Install - -``` -$ npm install strip-ansi -``` - - -## Usage - -```js -const stripAnsi = require('strip-ansi'); - -stripAnsi('\u001B[4mUnicorn\u001B[0m'); -//=> 'Unicorn' - -stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); -//=> 'Click' -``` - - -## strip-ansi for enterprise - -Available as part of the Tidelift Subscription. - -The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - - -## Related - -- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module -- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module -- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes -- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes -- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right - - -## Maintainers - -- [Sindre Sorhus](https://github.com/sindresorhus) -- [Josh Junon](https://github.com/qix-) - diff --git a/node_modules/color-name/LICENSE b/node_modules/color-name/LICENSE index c6b1001..4d9802a 100644 --- a/node_modules/color-name/LICENSE +++ b/node_modules/color-name/LICENSE @@ -1,8 +1,8 @@ -The MIT License (MIT) -Copyright (c) 2015 Dmitry Ivanov - -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 MIT License (MIT) +Copyright (c) 2015 Dmitry Ivanov + +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. \ No newline at end of file diff --git a/node_modules/color-name/README.md b/node_modules/color-name/README.md index 932b979..3611a6b 100644 --- a/node_modules/color-name/README.md +++ b/node_modules/color-name/README.md @@ -1,11 +1,11 @@ -A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. - -[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) - - -```js -var colors = require('color-name'); -colors.red //[255,0,0] -``` - - +A JSON with color names and its values. Based on http://dev.w3.org/csswg/css-color/#named-colors. + +[![NPM](https://nodei.co/npm/color-name.png?mini=true)](https://nodei.co/npm/color-name/) + + +```js +var colors = require('color-name'); +colors.red //[255,0,0] +``` + + diff --git a/node_modules/color-name/index.js b/node_modules/color-name/index.js index b7c198a..e42aa68 100644 --- a/node_modules/color-name/index.js +++ b/node_modules/color-name/index.js @@ -1,152 +1,152 @@ -'use strict' - -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; +'use strict' + +module.exports = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; diff --git a/node_modules/csv-generate/README.md b/node_modules/csv-generate/README.md index 1d9d111..4fd74b8 100644 --- a/node_modules/csv-generate/README.md +++ b/node_modules/csv-generate/README.md @@ -1,19 +1,18 @@ -[![Build Status](https://api.travis-ci.org/adaltas/node-csv-generate.svg)](https://travis-ci.org/#!/adaltas/node-csv-generate) [![NPM](https://img.shields.io/npm/dm/csv-generate)](https://www.npmjs.com/package/csv-generate) [![NPM](https://img.shields.io/npm/v/csv-generate)](https://www.npmjs.com/package/csv-generate) +# CSV generator for Node.js and the web -# CSV and object generation +[![Build Status](https://img.shields.io/github/actions/workflow/status/adaltas/node-csv/nodejs.yml?branch=master)](https://github.com/adaltas/node-csv/actions) +[![NPM](https://img.shields.io/npm/dm/csv-generate)](https://www.npmjs.com/package/csv-generate) +[![NPM](https://img.shields.io/npm/v/csv-generate)](https://www.npmjs.com/package/csv-generate) -This package provides a flexible generator of CSV strings and Javascript objects -implementing the Node.js `stream.Readable` API. - -[Documentation for the "csv-generate" package is available here](https://csv.js.org/generate/). +The [`csv-generate` package](https://csv.js.org/generate/) provides a flexible generator of random CSV strings and Javascript objects implementing the Node.js `stream.Readable` API. It is part of the [CSV project](https://csv.js.org/). ## Documentation -* [Project homepage](http://csv.js.org/generate/) -* [API](http://csv.js.org/generate/api/) -* [Options](http://csv.js.org/generate/options/) -* [Examples](http://csv.js.org/generate/examples/) +* [Project homepage](https://csv.js.org/generate/) +* [API](https://csv.js.org/generate/api/) +* [Options](https://csv.js.org/generate/options/) +* [Examples](https://csv.js.org/generate/examples/) ## Main features @@ -26,9 +25,44 @@ implementing the Node.js `stream.Readable` API. ## Usage -Run `npm install csv` to install the full csv module or run `npm install csv-generate` if you are only interested by the CSV generator. - -Use the callback style API for simplicity or the stream based API for scalability. +Run `npm install csv` to install the full CSV module or run `npm install csv-generate` if you are only interested by the CSV generator. + +Use the callback and sync APIs for simplicity or the stream based API for scalability. + +## Example + +The [API](https://csv.js.org/generate/api/) is available in multiple flavors. This example illustrates the stream API. + +```js +import { generate } from 'csv-generate'; +import assert from 'assert'; + +const records = []; +// Initialize the generator +generate({ + seed: 1, + objectMode: true, + columns: 2, + length: 2 +}) + // Use the readable stream api to consume generated records + .on('readable', function(){ + let record; while((record = this.read()) !== null){ + records.push(record); + } + }) + // Catch any error + .on('error', function(err){ + console.error(err); + }) + // Test that the generated records matched the expected records + .on('end', function(){ + assert.deepEqual(records, [ + [ 'OMH', 'ONKCHhJmjadoA' ], + [ 'D', 'GeACHiN' ] + ]); + }); +``` ## Development @@ -40,4 +74,6 @@ The test suite is run online with [Travis](https://travis-ci.org/#!/adaltas/node ## Contributors +The project is sponsored by [Adaltas](https://www.adaltas.com), an Big Data consulting firm based in Paris, France. + * David Worms: diff --git a/node_modules/csv-generate/dist/cjs/index.cjs b/node_modules/csv-generate/dist/cjs/index.cjs new file mode 100644 index 0000000..4187f6a --- /dev/null +++ b/node_modules/csv-generate/dist/cjs/index.cjs @@ -0,0 +1,279 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; +}; +util.inherits(Generator, stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; +}; + +exports.Generator = Generator; +exports.generate = generate; diff --git a/node_modules/csv-generate/dist/cjs/index.d.cts b/node_modules/csv-generate/dist/cjs/index.d.cts new file mode 100644 index 0000000..c5528cf --- /dev/null +++ b/node_modules/csv-generate/dist/cjs/index.d.cts @@ -0,0 +1,94 @@ + +/// + +import * as stream from "stream"; + +type Callback = (err?: Error, records?: any) => void; + +export class Generator extends stream.Readable { + constructor(options?: Options); + + readonly options: Options; +} + +export type ColumnsFunctionArgs = { + options: Options; + state: State; +}; +export type ColumnsFunction = (args: ColumnsFunctionArgs) => string; + +export type State = { + start_time: number, + fixed_size_buffer: number, + count_written: number, + count_created: number, +} + +export interface Options extends stream.ReadableOptions { + /** + * Define the number of generated fields and the generation method. + */ + columns?: number | (string | ColumnsFunction)[]; + /** + * Set the field delimiter. + */ + delimiter?: string; + /** + * Period to run in milliseconds. + */ + duration?: number; + /** + * If specified, then buffers will be decoded to strings using the specified encoding. + */ + encoding?: BufferEncoding | undefined; + /** + * When to stop the generation. + */ + end?: number | Date; + /** + * One or multiple characters to print at the end of the file; only apply when objectMode is disabled. + */ + eof?: boolean | string; + /** + * Generate buffers equals length as defined by the `highWaterMark` option. + */ + fixed_size?: boolean; + fixedSize?: boolean; + /** + * The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. + */ + high_water_mark?: number; + highWaterMark?: number; + /** + * Number of lines or records to generate. + */ + length?: number; + /** + * Maximum number of characters per word. + */ + max_word_length?: number; + maxWordLength?: number; + /** + * Whether this stream should behave as a stream of objects. + */ + object_mode?: boolean + objectMode?: boolean; + /** + * One or multiple characters used to delimit records. + */ + row_delimiter?: string; + /** + * Generate idempotent random characters if a number provided. + */ + seed?: boolean | number; + /** + * The time to wait between the generation of each records + */ + sleep?: number; +} + +declare function generate(options?: Options, callback?: Callback): Generator; +declare function generate(callback?: Callback): Generator; + +// export default generate; +export {generate}; diff --git a/node_modules/csv-generate/dist/cjs/stream.d.cts b/node_modules/csv-generate/dist/cjs/stream.d.cts new file mode 100644 index 0000000..d577d3d --- /dev/null +++ b/node_modules/csv-generate/dist/cjs/stream.d.cts @@ -0,0 +1,6 @@ + +import { Options } from './index.cjs'; + +declare function generate(options?: Options): ReadableStream; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/dist/cjs/sync.cjs b/node_modules/csv-generate/dist/cjs/sync.cjs new file mode 100644 index 0000000..a43003d --- /dev/null +++ b/node_modules/csv-generate/dist/cjs/sync.cjs @@ -0,0 +1,269 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; +}; +util.inherits(Generator, stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } +}; + +exports.generate = generate; diff --git a/node_modules/csv-generate/dist/cjs/sync.d.cts b/node_modules/csv-generate/dist/cjs/sync.d.cts new file mode 100644 index 0000000..3a415ac --- /dev/null +++ b/node_modules/csv-generate/dist/cjs/sync.d.cts @@ -0,0 +1,6 @@ + +import { Options } from './index.cjs'; + +declare function generate(options: number | Options): string & Array; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/dist/esm/index.d.ts b/node_modules/csv-generate/dist/esm/index.d.ts new file mode 100644 index 0000000..c5528cf --- /dev/null +++ b/node_modules/csv-generate/dist/esm/index.d.ts @@ -0,0 +1,94 @@ + +/// + +import * as stream from "stream"; + +type Callback = (err?: Error, records?: any) => void; + +export class Generator extends stream.Readable { + constructor(options?: Options); + + readonly options: Options; +} + +export type ColumnsFunctionArgs = { + options: Options; + state: State; +}; +export type ColumnsFunction = (args: ColumnsFunctionArgs) => string; + +export type State = { + start_time: number, + fixed_size_buffer: number, + count_written: number, + count_created: number, +} + +export interface Options extends stream.ReadableOptions { + /** + * Define the number of generated fields and the generation method. + */ + columns?: number | (string | ColumnsFunction)[]; + /** + * Set the field delimiter. + */ + delimiter?: string; + /** + * Period to run in milliseconds. + */ + duration?: number; + /** + * If specified, then buffers will be decoded to strings using the specified encoding. + */ + encoding?: BufferEncoding | undefined; + /** + * When to stop the generation. + */ + end?: number | Date; + /** + * One or multiple characters to print at the end of the file; only apply when objectMode is disabled. + */ + eof?: boolean | string; + /** + * Generate buffers equals length as defined by the `highWaterMark` option. + */ + fixed_size?: boolean; + fixedSize?: boolean; + /** + * The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. + */ + high_water_mark?: number; + highWaterMark?: number; + /** + * Number of lines or records to generate. + */ + length?: number; + /** + * Maximum number of characters per word. + */ + max_word_length?: number; + maxWordLength?: number; + /** + * Whether this stream should behave as a stream of objects. + */ + object_mode?: boolean + objectMode?: boolean; + /** + * One or multiple characters used to delimit records. + */ + row_delimiter?: string; + /** + * Generate idempotent random characters if a number provided. + */ + seed?: boolean | number; + /** + * The time to wait between the generation of each records + */ + sleep?: number; +} + +declare function generate(options?: Options, callback?: Callback): Generator; +declare function generate(callback?: Callback): Generator; + +// export default generate; +export {generate}; diff --git a/node_modules/csv-generate/dist/esm/index.js b/node_modules/csv-generate/dist/esm/index.js new file mode 100644 index 0000000..68bfeb8 --- /dev/null +++ b/node_modules/csv-generate/dist/esm/index.js @@ -0,0 +1,5469 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; +}; +util.inherits(Generator, Stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; +}; + +export { Generator, generate }; diff --git a/node_modules/csv-generate/dist/esm/stream.d.ts b/node_modules/csv-generate/dist/esm/stream.d.ts new file mode 100644 index 0000000..d53894a --- /dev/null +++ b/node_modules/csv-generate/dist/esm/stream.d.ts @@ -0,0 +1,6 @@ + +import { Options } from './index.js'; + +declare function generate(options?: Options): ReadableStream; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/dist/esm/sync.d.ts b/node_modules/csv-generate/dist/esm/sync.d.ts new file mode 100644 index 0000000..965ad63 --- /dev/null +++ b/node_modules/csv-generate/dist/esm/sync.d.ts @@ -0,0 +1,6 @@ + +import { Options } from './index.js'; + +declare function generate(options: number | Options): string & Array; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/dist/esm/sync.js b/node_modules/csv-generate/dist/esm/sync.js new file mode 100644 index 0000000..a2853f7 --- /dev/null +++ b/node_modules/csv-generate/dist/esm/sync.js @@ -0,0 +1,5460 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; +}; +util.inherits(Generator, Stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } +}; + +export { generate }; diff --git a/node_modules/csv-generate/dist/iife/index.js b/node_modules/csv-generate/dist/iife/index.js new file mode 100644 index 0000000..22278f3 --- /dev/null +++ b/node_modules/csv-generate/dist/iife/index.js @@ -0,0 +1,5477 @@ +var csv_generate = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; + }; + + exports.Generator = Generator; + exports.generate = generate; + + return exports; + +})({}); diff --git a/node_modules/csv-generate/dist/iife/sync.js b/node_modules/csv-generate/dist/iife/sync.js new file mode 100644 index 0000000..aaf06ed --- /dev/null +++ b/node_modules/csv-generate/dist/iife/sync.js @@ -0,0 +1,5467 @@ +var csv_generate_sync = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } + }; + + exports.generate = generate; + + return exports; + +})({}); diff --git a/node_modules/csv-generate/dist/umd/index.js b/node_modules/csv-generate/dist/umd/index.js new file mode 100644 index 0000000..0c66ce6 --- /dev/null +++ b/node_modules/csv-generate/dist/umd/index.js @@ -0,0 +1,5478 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_generate = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; + }; + + exports.Generator = Generator; + exports.generate = generate; + +})); diff --git a/node_modules/csv-generate/dist/umd/sync.js b/node_modules/csv-generate/dist/umd/sync.js new file mode 100644 index 0000000..c5a4a47 --- /dev/null +++ b/node_modules/csv-generate/dist/umd/sync.js @@ -0,0 +1,5468 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_generate_sync = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } + }; + + exports.generate = generate; + +})); diff --git a/node_modules/csv-generate/lib/api/index.js b/node_modules/csv-generate/lib/api/index.js new file mode 100644 index 0000000..fdfbddc --- /dev/null +++ b/node_modules/csv-generate/lib/api/index.js @@ -0,0 +1,6 @@ + +import {init_state} from './init_state.js'; +import {normalize_options} from './normalize_options.js'; +import {read} from './read.js'; + +export {normalize_options, init_state, read}; diff --git a/node_modules/csv-generate/lib/api/init_state.js b/node_modules/csv-generate/lib/api/init_state.js new file mode 100644 index 0000000..b99e269 --- /dev/null +++ b/node_modules/csv-generate/lib/api/init_state.js @@ -0,0 +1,12 @@ + +const init_state = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +export {init_state}; diff --git a/node_modules/csv-generate/lib/api/normalize_options.js b/node_modules/csv-generate/lib/api/normalize_options.js new file mode 100644 index 0000000..80a2493 --- /dev/null +++ b/node_modules/csv-generate/lib/api/normalize_options.js @@ -0,0 +1,67 @@ + +import {types} from './types.js'; + +const camelize = function(str){ + return str.replace(/_([a-z])/gi, function(_, match){ + return match.toUpperCase(); + }); +}; + +const normalize_options = (opts) => { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +export { normalize_options }; diff --git a/node_modules/csv-generate/lib/api/random.js b/node_modules/csv-generate/lib/api/random.js new file mode 100644 index 0000000..04692e5 --- /dev/null +++ b/node_modules/csv-generate/lib/api/random.js @@ -0,0 +1,11 @@ + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else{ + return Math.random(); + } +}; + +export {random}; diff --git a/node_modules/csv-generate/lib/api/read.js b/node_modules/csv-generate/lib/api/read.js new file mode 100644 index 0000000..a94c3c4 --- /dev/null +++ b/node_modules/csv-generate/lib/api/read.js @@ -0,0 +1,89 @@ + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else{ + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else{ + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else{ + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +export {read}; diff --git a/node_modules/csv-generate/lib/api/types.js b/node_modules/csv-generate/lib/api/types.js new file mode 100644 index 0000000..e2e703b --- /dev/null +++ b/node_modules/csv-generate/lib/api/types.js @@ -0,0 +1,25 @@ + +import {random} from './random.js'; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/* -CSV Generate - main module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ -var stream = require('stream'); - -var util = require('util'); - -module.exports = function () { - var options; - var callback; - - if (arguments.length === 2) { - options = arguments[0]; - callback = arguments[1]; - } else if (arguments.length === 1) { - if (typeof arguments[0] === 'function') { - options = {}; - callback = arguments[0]; - } else { - options = arguments[0]; - } - } else if (arguments.length === 0) { - options = {}; - } - - var generator = new Generator(options); - - if (callback) { - var data = []; - generator.on('readable', function () { - var d; - - while (d = generator.read()) { - data.push(d); - } - }); - generator.on('error', callback); - generator.on('end', function () { - if (generator.options.objectMode) { - callback(null, data); - } else { - if (generator.options.encoding) { - callback(null, data.join('')); - } else { - callback(null, Buffer.concat(data)); - } - } - }); - } - - return generator; -}; - -Generator = function (_Generator) { - function Generator() { - return _Generator.apply(this, arguments); - } - - Generator.toString = function () { - return _Generator.toString(); - }; - - return Generator; -}(function () { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - // Convert Stream Readable options if underscored - if (options.high_water_mark) { - options.highWaterMark = options.high_water_mark; - } - - if (options.object_mode) { - options.objectMode = options.object_mode; - } // Call parent constructor - - - stream.Readable.call(this, options); // Clone and camelize options - - this.options = {}; - - for (var k in options) { - this.options[Generator.camelize(k)] = options[k]; - } // Normalize options - - - var dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0 - }; - - for (var _k in dft) { - if (this.options[_k] === undefined) { - this.options[_k] = dft[_k]; - } - } // Default values - - - if (this.options.eof === true) { - this.options.eof = this.options.rowDelimiter; - } // State - - - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0 - }; - - if (typeof this.options.columns === 'number') { - this.options.columns = new Array(this.options.columns); - } - - var accepted_header_types = Object.keys(Generator).filter(function (t) { - return !['super_', 'camelize'].includes(t); - }); - - for (var i = 0; i < this.options.columns.length; i++) { - var v = this.options.columns[i] || 'ascii'; - - if (typeof v === 'string') { - if (!accepted_header_types.includes(v)) { - throw Error("Invalid column type: got \"".concat(v, "\", default values are ").concat(JSON.stringify(accepted_header_types))); - } - - this.options.columns[i] = Generator[v]; - } - } - - return this; -}); - -util.inherits(Generator, stream.Readable); // Export the class - -module.exports.Generator = Generator; // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. - -Generator.prototype.random = function () { - if (this.options.seed) { - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100; - } else { - return Math.random(); - } -}; // Stop the generation. - - -Generator.prototype.end = function () { - this.push(null); -}; // Put new data into the read queue. - - -Generator.prototype._read = function (size) { - var _this = this; - - // Already started - var data = []; - var length = this._.fixed_size_buffer.length; - - if (length !== 0) { - data.push(this._.fixed_size_buffer); - } - - var _loop = function _loop() { - // Time for some rest: flush first and stop later - if (_this._.count_created === _this.options.length || _this.options.end && Date.now() > _this.options.end || _this.options.duration && Date.now() > _this._.start_time + _this.options.duration) { - // Flush - if (data.length) { - if (_this.options.objectMode) { - var _iterator = _createForOfIteratorHelper(data), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _line = _step.value; - - _this.__push(_line); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } else { - _this.__push(data.join('') + (_this.options.eof ? _this.options.eof : '')); - } - } // Stop - - - return { - v: _this.push(null) - }; - } // Create the line - - - var line = []; - var lineLength = void 0; - - _this.options.columns.forEach(function (fn) { - line.push(fn(_this)); - }); // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - - - if (_this.options.objectMode) { - lineLength = 0; - - var _iterator2 = _createForOfIteratorHelper(line), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - lineLength += column.length; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } else { - // Stringify the line - line = (_this._.count_created === 0 ? '' : _this.options.rowDelimiter) + line.join(_this.options.delimiter); - lineLength = line.length; - } - - _this._.count_created++; - - if (length + lineLength > size) { - if (_this.options.objectMode) { - data.push(line); - - var _iterator3 = _createForOfIteratorHelper(data), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _line2 = _step3.value; - - _this.__push(_line2); - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - } else { - if (_this.options.fixedSize) { - _this._.fixed_size_buffer = line.substr(size - length); - data.push(line.substr(0, size - length)); - } else { - data.push(line); - } - - _this.__push(data.join('')); - } - - return { - v: void 0 - }; - } - - length += lineLength; - data.push(line); - }; - - while (true) { - var _ret = _loop(); - - if (_typeof(_ret) === "object") return _ret.v; - } -}; // Put new data into the read queue. - - -Generator.prototype.__push = function (record) { - var _this2 = this; - - this._.count_written++; - - if (this.options.sleep > 0) { - setTimeout(function () { - _this2.push(record); - }, this.options.sleep); - } else { - this.push(record); - } -}; // Generate an ASCII value. - - -Generator.ascii = function (gen) { - // Column - var column = []; - var nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength); - - for (var i = 0; i < nb_chars; i++) { - var _char = Math.floor(gen.random() * 32); - - column.push(String.fromCharCode(_char + (_char < 16 ? 65 : 97 - 16))); - } - - return column.join(''); -}; // Generate an integer value. - - -Generator["int"] = function (gen) { - return Math.floor(gen.random() * Math.pow(2, 52)); -}; // Generate an boolean value. - - -Generator.bool = function (gen) { - return Math.floor(gen.random() * 2); -}; // Camelize option properties - - -Generator.camelize = function (str) { - return str.replace(/_([a-z])/gi, function (_, match, index) { - return match.toUpperCase(); - }); -}; - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":5,"stream":24,"util":43}],2:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],3:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],4:[function(require,module,exports){ - -},{}],5:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":3,"buffer":5,"ieee754":17}],6:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":7,"get-intrinsic":13}],7:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":12,"get-intrinsic":13}],8:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":13}],9:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],10:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],11:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],12:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":11}],13:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":12,"has":16,"has-symbols":14}],14:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":15}],15:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],16:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":12}],17:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],18:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],19:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":6}],20:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],21:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":2,"call-bind/callBound":6,"es-abstract/helpers/getOwnPropertyDescriptor":8,"foreach":10,"has-symbols":14}],22:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],23:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":5}],24:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":9,"inherits":18,"readable-stream/lib/_stream_duplex.js":26,"readable-stream/lib/_stream_passthrough.js":27,"readable-stream/lib/_stream_readable.js":28,"readable-stream/lib/_stream_transform.js":29,"readable-stream/lib/_stream_writable.js":30,"readable-stream/lib/internal/streams/end-of-stream.js":34,"readable-stream/lib/internal/streams/pipeline.js":36}],25:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],26:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":28,"./_stream_writable":30,"_process":22,"inherits":18}],27:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":29,"inherits":18}],28:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":25,"./_stream_duplex":26,"./internal/streams/async_iterator":31,"./internal/streams/buffer_list":32,"./internal/streams/destroy":33,"./internal/streams/from":35,"./internal/streams/state":37,"./internal/streams/stream":38,"_process":22,"buffer":5,"events":9,"inherits":18,"string_decoder/":39,"util":4}],29:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":25,"./_stream_duplex":26,"inherits":18}],30:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":25,"./_stream_duplex":26,"./internal/streams/destroy":33,"./internal/streams/state":37,"./internal/streams/stream":38,"_process":22,"buffer":5,"inherits":18,"util-deprecate":40}],31:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":34,"_process":22}],32:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":5,"util":4}],33:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":22}],34:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":25}],35:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],36:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":25,"./end-of-stream":34}],37:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":25}],38:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":9}],39:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":23}],40:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],41:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],42:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":19,"is-generator-function":20,"is-typed-array":21,"which-typed-array":44}],43:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":41,"./support/types":42,"_process":22,"inherits":18}],44:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":2,"call-bind/callBound":6,"es-abstract/helpers/getOwnPropertyDescriptor":8,"foreach":10,"has-symbols":14,"is-typed-array":21}]},{},[1])(1) -}); diff --git a/node_modules/csv-generate/lib/browser/sync.js b/node_modules/csv-generate/lib/browser/sync.js deleted file mode 100644 index 67815ed..0000000 --- a/node_modules/csv-generate/lib/browser/sync.js +++ /dev/null @@ -1,8671 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/* -CSV Generate - main module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ -var stream = require('stream'); - -var util = require('util'); - -module.exports = function () { - var options; - var callback; - - if (arguments.length === 2) { - options = arguments[0]; - callback = arguments[1]; - } else if (arguments.length === 1) { - if (typeof arguments[0] === 'function') { - options = {}; - callback = arguments[0]; - } else { - options = arguments[0]; - } - } else if (arguments.length === 0) { - options = {}; - } - - var generator = new Generator(options); - - if (callback) { - var data = []; - generator.on('readable', function () { - var d; - - while (d = generator.read()) { - data.push(d); - } - }); - generator.on('error', callback); - generator.on('end', function () { - if (generator.options.objectMode) { - callback(null, data); - } else { - if (generator.options.encoding) { - callback(null, data.join('')); - } else { - callback(null, Buffer.concat(data)); - } - } - }); - } - - return generator; -}; - -Generator = function (_Generator) { - function Generator() { - return _Generator.apply(this, arguments); - } - - Generator.toString = function () { - return _Generator.toString(); - }; - - return Generator; -}(function () { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - // Convert Stream Readable options if underscored - if (options.high_water_mark) { - options.highWaterMark = options.high_water_mark; - } - - if (options.object_mode) { - options.objectMode = options.object_mode; - } // Call parent constructor - - - stream.Readable.call(this, options); // Clone and camelize options - - this.options = {}; - - for (var k in options) { - this.options[Generator.camelize(k)] = options[k]; - } // Normalize options - - - var dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0 - }; - - for (var _k in dft) { - if (this.options[_k] === undefined) { - this.options[_k] = dft[_k]; - } - } // Default values - - - if (this.options.eof === true) { - this.options.eof = this.options.rowDelimiter; - } // State - - - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0 - }; - - if (typeof this.options.columns === 'number') { - this.options.columns = new Array(this.options.columns); - } - - var accepted_header_types = Object.keys(Generator).filter(function (t) { - return !['super_', 'camelize'].includes(t); - }); - - for (var i = 0; i < this.options.columns.length; i++) { - var v = this.options.columns[i] || 'ascii'; - - if (typeof v === 'string') { - if (!accepted_header_types.includes(v)) { - throw Error("Invalid column type: got \"".concat(v, "\", default values are ").concat(JSON.stringify(accepted_header_types))); - } - - this.options.columns[i] = Generator[v]; - } - } - - return this; -}); - -util.inherits(Generator, stream.Readable); // Export the class - -module.exports.Generator = Generator; // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. - -Generator.prototype.random = function () { - if (this.options.seed) { - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100; - } else { - return Math.random(); - } -}; // Stop the generation. - - -Generator.prototype.end = function () { - this.push(null); -}; // Put new data into the read queue. - - -Generator.prototype._read = function (size) { - var _this = this; - - // Already started - var data = []; - var length = this._.fixed_size_buffer.length; - - if (length !== 0) { - data.push(this._.fixed_size_buffer); - } - - var _loop = function _loop() { - // Time for some rest: flush first and stop later - if (_this._.count_created === _this.options.length || _this.options.end && Date.now() > _this.options.end || _this.options.duration && Date.now() > _this._.start_time + _this.options.duration) { - // Flush - if (data.length) { - if (_this.options.objectMode) { - var _iterator = _createForOfIteratorHelper(data), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _line = _step.value; - - _this.__push(_line); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } else { - _this.__push(data.join('') + (_this.options.eof ? _this.options.eof : '')); - } - } // Stop - - - return { - v: _this.push(null) - }; - } // Create the line - - - var line = []; - var lineLength = void 0; - - _this.options.columns.forEach(function (fn) { - line.push(fn(_this)); - }); // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - - - if (_this.options.objectMode) { - lineLength = 0; - - var _iterator2 = _createForOfIteratorHelper(line), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - lineLength += column.length; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } else { - // Stringify the line - line = (_this._.count_created === 0 ? '' : _this.options.rowDelimiter) + line.join(_this.options.delimiter); - lineLength = line.length; - } - - _this._.count_created++; - - if (length + lineLength > size) { - if (_this.options.objectMode) { - data.push(line); - - var _iterator3 = _createForOfIteratorHelper(data), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _line2 = _step3.value; - - _this.__push(_line2); - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - } else { - if (_this.options.fixedSize) { - _this._.fixed_size_buffer = line.substr(size - length); - data.push(line.substr(0, size - length)); - } else { - data.push(line); - } - - _this.__push(data.join('')); - } - - return { - v: void 0 - }; - } - - length += lineLength; - data.push(line); - }; - - while (true) { - var _ret = _loop(); - - if (_typeof(_ret) === "object") return _ret.v; - } -}; // Put new data into the read queue. - - -Generator.prototype.__push = function (record) { - var _this2 = this; - - this._.count_written++; - - if (this.options.sleep > 0) { - setTimeout(function () { - _this2.push(record); - }, this.options.sleep); - } else { - this.push(record); - } -}; // Generate an ASCII value. - - -Generator.ascii = function (gen) { - // Column - var column = []; - var nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength); - - for (var i = 0; i < nb_chars; i++) { - var _char = Math.floor(gen.random() * 32); - - column.push(String.fromCharCode(_char + (_char < 16 ? 65 : 97 - 16))); - } - - return column.join(''); -}; // Generate an integer value. - - -Generator["int"] = function (gen) { - return Math.floor(gen.random() * Math.pow(2, 52)); -}; // Generate an boolean value. - - -Generator.bool = function (gen) { - return Math.floor(gen.random() * 2); -}; // Camelize option properties - - -Generator.camelize = function (str) { - return str.replace(/_([a-z])/gi, function (_, match, index) { - return match.toUpperCase(); - }); -}; - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":6,"stream":25,"util":44}],2:[function(require,module,exports){ -"use strict"; - -/* -CSV Generate - sync module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ -var generate = require('.'); - -module.exports = function (options) { - if (typeof options === 'string' && /\d+/.test(options)) { - options = parseInt(options); - } - - if (Number.isInteger(options)) { - options = { - length: options - }; - } - - if (!Number.isInteger(options.length)) { - throw Error('Invalid Argument: length is not defined'); - } - - var chunks = []; - var work = true; // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options - - options.highWaterMark = options.objectMode ? 16 : 16384; - var generator = new generate.Generator(options); - - generator.push = function (chunk) { - if (chunk === null) { - return work = false; - } - - if (options.objectMode) { - chunks.push(chunk); - } else { - chunks.push(chunk); - } - }; - - while (work) { - generator._read(options.highWaterMark); - } - - if (!options.objectMode) { - return chunks.join(''); - } else { - return chunks; - } -}; - -},{".":1}],3:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],4:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],5:[function(require,module,exports){ - -},{}],6:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":4,"buffer":6,"ieee754":18}],7:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":8,"get-intrinsic":14}],8:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":13,"get-intrinsic":14}],9:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":14}],10:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],11:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],12:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],13:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":12}],14:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":13,"has":17,"has-symbols":15}],15:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":16}],16:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],17:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":13}],18:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],19:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],20:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":7}],21:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],22:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":3,"call-bind/callBound":7,"es-abstract/helpers/getOwnPropertyDescriptor":9,"foreach":11,"has-symbols":15}],23:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],24:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":6}],25:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":10,"inherits":19,"readable-stream/lib/_stream_duplex.js":27,"readable-stream/lib/_stream_passthrough.js":28,"readable-stream/lib/_stream_readable.js":29,"readable-stream/lib/_stream_transform.js":30,"readable-stream/lib/_stream_writable.js":31,"readable-stream/lib/internal/streams/end-of-stream.js":35,"readable-stream/lib/internal/streams/pipeline.js":37}],26:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],27:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":29,"./_stream_writable":31,"_process":23,"inherits":19}],28:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":30,"inherits":19}],29:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":26,"./_stream_duplex":27,"./internal/streams/async_iterator":32,"./internal/streams/buffer_list":33,"./internal/streams/destroy":34,"./internal/streams/from":36,"./internal/streams/state":38,"./internal/streams/stream":39,"_process":23,"buffer":6,"events":10,"inherits":19,"string_decoder/":40,"util":5}],30:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":26,"./_stream_duplex":27,"inherits":19}],31:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":26,"./_stream_duplex":27,"./internal/streams/destroy":34,"./internal/streams/state":38,"./internal/streams/stream":39,"_process":23,"buffer":6,"inherits":19,"util-deprecate":41}],32:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":35,"_process":23}],33:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":6,"util":5}],34:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":23}],35:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":26}],36:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],37:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":26,"./end-of-stream":35}],38:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":26}],39:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":10}],40:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":24}],41:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],42:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],43:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":20,"is-generator-function":21,"is-typed-array":22,"which-typed-array":45}],44:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":42,"./support/types":43,"_process":23,"inherits":19}],45:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":3,"call-bind/callBound":7,"es-abstract/helpers/getOwnPropertyDescriptor":9,"foreach":11,"has-symbols":15,"is-typed-array":22}]},{},[2])(2) -}); diff --git a/node_modules/csv-generate/lib/es5/index.d.ts b/node_modules/csv-generate/lib/es5/index.d.ts deleted file mode 100644 index befb973..0000000 --- a/node_modules/csv-generate/lib/es5/index.d.ts +++ /dev/null @@ -1,98 +0,0 @@ - -/// - -import * as stream from "stream"; - -export = generate; - -declare function generate(options?: generate.Options, callback?: generate.Callback): generate.Generator; -declare function generate(callback?: generate.Callback): generate.Generator; -declare namespace generate { - - type Callback = (err?: Error, records?: any) => void; - - type MatcherFunc = (value: any) => boolean; - - class Generator extends stream.Readable { - constructor(options?: Options); - - readonly options: Options; - } - - interface Options { - - /** - * Define the number of generated fields and the generation method. - */ - columns?: number | string[]; - - /** - * Set the field delimiter. - */ - delimiter?: string; - - /** - * Period to run in milliseconds. - */ - duration?: number; - - /** - * If specified, then buffers will be decoded to strings using the specified encoding. - */ - encoding?: string; - - /** - * When to stop the generation. - */ - end?: number | Date; - - /** - * One or multiple characters to print at the end of the file; only apply when objectMode is disabled. - */ - eof?: boolean | string; - - /** - * Generate buffers equals length as defined by the `highWaterMark` option. - */ - fixed_size?: boolean; - fixedSize?: boolean; - - /** - * The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. - */ - high_water_mark?: number; - highWaterMark?: number; - - /** - * Number of lines or records to generate. - */ - length?: number; - - /** - * Maximum number of characters per word. - */ - max_word_length?: number; - maxWordLength?: number; - - /** - * Whether this stream should behave as a stream of objects. - */ - object_mode?: boolean - objectMode?: boolean; - - /** - * One or multiple characters used to delimit records. - */ - row_delimiter?: string; - - /** - * Generate idempotent random characters if a number provided. - */ - seed?: boolean | number; - - /** - * The time to wait between the generation of each records - */ - sleep?: number; - } -} diff --git a/node_modules/csv-generate/lib/es5/index.js b/node_modules/csv-generate/lib/es5/index.js deleted file mode 100644 index a612975..0000000 --- a/node_modules/csv-generate/lib/es5/index.js +++ /dev/null @@ -1,343 +0,0 @@ -"use strict"; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/* -CSV Generate - main module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ -var stream = require('stream'); - -var util = require('util'); - -module.exports = function () { - var options; - var callback; - - if (arguments.length === 2) { - options = arguments[0]; - callback = arguments[1]; - } else if (arguments.length === 1) { - if (typeof arguments[0] === 'function') { - options = {}; - callback = arguments[0]; - } else { - options = arguments[0]; - } - } else if (arguments.length === 0) { - options = {}; - } - - var generator = new Generator(options); - - if (callback) { - var data = []; - generator.on('readable', function () { - var d; - - while (d = generator.read()) { - data.push(d); - } - }); - generator.on('error', callback); - generator.on('end', function () { - if (generator.options.objectMode) { - callback(null, data); - } else { - if (generator.options.encoding) { - callback(null, data.join('')); - } else { - callback(null, Buffer.concat(data)); - } - } - }); - } - - return generator; -}; - -Generator = function (_Generator) { - function Generator() { - return _Generator.apply(this, arguments); - } - - Generator.toString = function () { - return _Generator.toString(); - }; - - return Generator; -}(function () { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - // Convert Stream Readable options if underscored - if (options.high_water_mark) { - options.highWaterMark = options.high_water_mark; - } - - if (options.object_mode) { - options.objectMode = options.object_mode; - } // Call parent constructor - - - stream.Readable.call(this, options); // Clone and camelize options - - this.options = {}; - - for (var k in options) { - this.options[Generator.camelize(k)] = options[k]; - } // Normalize options - - - var dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0 - }; - - for (var _k in dft) { - if (this.options[_k] === undefined) { - this.options[_k] = dft[_k]; - } - } // Default values - - - if (this.options.eof === true) { - this.options.eof = this.options.rowDelimiter; - } // State - - - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0 - }; - - if (typeof this.options.columns === 'number') { - this.options.columns = new Array(this.options.columns); - } - - var accepted_header_types = Object.keys(Generator).filter(function (t) { - return !['super_', 'camelize'].includes(t); - }); - - for (var i = 0; i < this.options.columns.length; i++) { - var v = this.options.columns[i] || 'ascii'; - - if (typeof v === 'string') { - if (!accepted_header_types.includes(v)) { - throw Error("Invalid column type: got \"".concat(v, "\", default values are ").concat(JSON.stringify(accepted_header_types))); - } - - this.options.columns[i] = Generator[v]; - } - } - - return this; -}); - -util.inherits(Generator, stream.Readable); // Export the class - -module.exports.Generator = Generator; // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. - -Generator.prototype.random = function () { - if (this.options.seed) { - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100; - } else { - return Math.random(); - } -}; // Stop the generation. - - -Generator.prototype.end = function () { - this.push(null); -}; // Put new data into the read queue. - - -Generator.prototype._read = function (size) { - var _this = this; - - // Already started - var data = []; - var length = this._.fixed_size_buffer.length; - - if (length !== 0) { - data.push(this._.fixed_size_buffer); - } - - var _loop = function _loop() { - // Time for some rest: flush first and stop later - if (_this._.count_created === _this.options.length || _this.options.end && Date.now() > _this.options.end || _this.options.duration && Date.now() > _this._.start_time + _this.options.duration) { - // Flush - if (data.length) { - if (_this.options.objectMode) { - var _iterator = _createForOfIteratorHelper(data), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var _line = _step.value; - - _this.__push(_line); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } else { - _this.__push(data.join('') + (_this.options.eof ? _this.options.eof : '')); - } - } // Stop - - - return { - v: _this.push(null) - }; - } // Create the line - - - var line = []; - var lineLength = void 0; - - _this.options.columns.forEach(function (fn) { - line.push(fn(_this)); - }); // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - - - if (_this.options.objectMode) { - lineLength = 0; - - var _iterator2 = _createForOfIteratorHelper(line), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - lineLength += column.length; - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } else { - // Stringify the line - line = (_this._.count_created === 0 ? '' : _this.options.rowDelimiter) + line.join(_this.options.delimiter); - lineLength = line.length; - } - - _this._.count_created++; - - if (length + lineLength > size) { - if (_this.options.objectMode) { - data.push(line); - - var _iterator3 = _createForOfIteratorHelper(data), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var _line2 = _step3.value; - - _this.__push(_line2); - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - } else { - if (_this.options.fixedSize) { - _this._.fixed_size_buffer = line.substr(size - length); - data.push(line.substr(0, size - length)); - } else { - data.push(line); - } - - _this.__push(data.join('')); - } - - return { - v: void 0 - }; - } - - length += lineLength; - data.push(line); - }; - - while (true) { - var _ret = _loop(); - - if (_typeof(_ret) === "object") return _ret.v; - } -}; // Put new data into the read queue. - - -Generator.prototype.__push = function (record) { - var _this2 = this; - - this._.count_written++; - - if (this.options.sleep > 0) { - setTimeout(function () { - _this2.push(record); - }, this.options.sleep); - } else { - this.push(record); - } -}; // Generate an ASCII value. - - -Generator.ascii = function (gen) { - // Column - var column = []; - var nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength); - - for (var i = 0; i < nb_chars; i++) { - var _char = Math.floor(gen.random() * 32); - - column.push(String.fromCharCode(_char + (_char < 16 ? 65 : 97 - 16))); - } - - return column.join(''); -}; // Generate an integer value. - - -Generator["int"] = function (gen) { - return Math.floor(gen.random() * Math.pow(2, 52)); -}; // Generate an boolean value. - - -Generator.bool = function (gen) { - return Math.floor(gen.random() * 2); -}; // Camelize option properties - - -Generator.camelize = function (str) { - return str.replace(/_([a-z])/gi, function (_, match, index) { - return match.toUpperCase(); - }); -}; \ No newline at end of file diff --git a/node_modules/csv-generate/lib/es5/sync.js b/node_modules/csv-generate/lib/es5/sync.js deleted file mode 100644 index 468e1ea..0000000 --- a/node_modules/csv-generate/lib/es5/sync.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; - -/* -CSV Generate - sync module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ -var generate = require('.'); - -module.exports = function (options) { - if (typeof options === 'string' && /\d+/.test(options)) { - options = parseInt(options); - } - - if (Number.isInteger(options)) { - options = { - length: options - }; - } - - if (!Number.isInteger(options.length)) { - throw Error('Invalid Argument: length is not defined'); - } - - var chunks = []; - var work = true; // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options - - options.highWaterMark = options.objectMode ? 16 : 16384; - var generator = new generate.Generator(options); - - generator.push = function (chunk) { - if (chunk === null) { - return work = false; - } - - if (options.objectMode) { - chunks.push(chunk); - } else { - chunks.push(chunk); - } - }; - - while (work) { - generator._read(options.highWaterMark); - } - - if (!options.objectMode) { - return chunks.join(''); - } else { - return chunks; - } -}; \ No newline at end of file diff --git a/node_modules/csv-generate/lib/index.d.ts b/node_modules/csv-generate/lib/index.d.ts index befb973..c5528cf 100644 --- a/node_modules/csv-generate/lib/index.d.ts +++ b/node_modules/csv-generate/lib/index.d.ts @@ -3,96 +3,92 @@ import * as stream from "stream"; -export = generate; +type Callback = (err?: Error, records?: any) => void; -declare function generate(options?: generate.Options, callback?: generate.Callback): generate.Generator; -declare function generate(callback?: generate.Callback): generate.Generator; -declare namespace generate { - - type Callback = (err?: Error, records?: any) => void; - - type MatcherFunc = (value: any) => boolean; - - class Generator extends stream.Readable { - constructor(options?: Options); - - readonly options: Options; - } - - interface Options { - - /** - * Define the number of generated fields and the generation method. - */ - columns?: number | string[]; - - /** - * Set the field delimiter. - */ - delimiter?: string; - - /** - * Period to run in milliseconds. - */ - duration?: number; - - /** - * If specified, then buffers will be decoded to strings using the specified encoding. - */ - encoding?: string; - - /** - * When to stop the generation. - */ - end?: number | Date; - - /** - * One or multiple characters to print at the end of the file; only apply when objectMode is disabled. - */ - eof?: boolean | string; - - /** - * Generate buffers equals length as defined by the `highWaterMark` option. - */ - fixed_size?: boolean; - fixedSize?: boolean; - - /** - * The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. - */ - high_water_mark?: number; - highWaterMark?: number; +export class Generator extends stream.Readable { + constructor(options?: Options); + + readonly options: Options; +} - /** - * Number of lines or records to generate. - */ - length?: number; +export type ColumnsFunctionArgs = { + options: Options; + state: State; +}; +export type ColumnsFunction = (args: ColumnsFunctionArgs) => string; + +export type State = { + start_time: number, + fixed_size_buffer: number, + count_written: number, + count_created: number, +} - /** - * Maximum number of characters per word. - */ - max_word_length?: number; - maxWordLength?: number; - - /** - * Whether this stream should behave as a stream of objects. - */ - object_mode?: boolean - objectMode?: boolean; +export interface Options extends stream.ReadableOptions { + /** + * Define the number of generated fields and the generation method. + */ + columns?: number | (string | ColumnsFunction)[]; + /** + * Set the field delimiter. + */ + delimiter?: string; + /** + * Period to run in milliseconds. + */ + duration?: number; + /** + * If specified, then buffers will be decoded to strings using the specified encoding. + */ + encoding?: BufferEncoding | undefined; + /** + * When to stop the generation. + */ + end?: number | Date; + /** + * One or multiple characters to print at the end of the file; only apply when objectMode is disabled. + */ + eof?: boolean | string; + /** + * Generate buffers equals length as defined by the `highWaterMark` option. + */ + fixed_size?: boolean; + fixedSize?: boolean; + /** + * The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. + */ + high_water_mark?: number; + highWaterMark?: number; + /** + * Number of lines or records to generate. + */ + length?: number; + /** + * Maximum number of characters per word. + */ + max_word_length?: number; + maxWordLength?: number; + /** + * Whether this stream should behave as a stream of objects. + */ + object_mode?: boolean + objectMode?: boolean; + /** + * One or multiple characters used to delimit records. + */ + row_delimiter?: string; + /** + * Generate idempotent random characters if a number provided. + */ + seed?: boolean | number; + /** + * The time to wait between the generation of each records + */ + sleep?: number; +} - /** - * One or multiple characters used to delimit records. - */ - row_delimiter?: string; +declare function generate(options?: Options, callback?: Callback): Generator; +declare function generate(callback?: Callback): Generator; - /** - * Generate idempotent random characters if a number provided. - */ - seed?: boolean | number; - - /** - * The time to wait between the generation of each records - */ - sleep?: number; - } -} +// export default generate; +export {generate}; diff --git a/node_modules/csv-generate/lib/index.js b/node_modules/csv-generate/lib/index.js index c3e5fba..6c6480f 100644 --- a/node_modules/csv-generate/lib/index.js +++ b/node_modules/csv-generate/lib/index.js @@ -6,224 +6,91 @@ Please look at the [project documentation](https://csv.js.org/generate/) for additional information. */ -const stream = require('stream') -const util = require('util') +import stream from 'stream'; +import util from 'util'; +import {normalize_options, init_state, read} from './api/index.js'; -module.exports = function(){ - let options - let callback +const Generator = function(options = {}){ + this.options = normalize_options(options); + // Call parent constructor + stream.Readable.call(this, this.options); + this.state = init_state(this.options); + return this; +}; +util.inherits(Generator, stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else{ + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(){ + let options; + let callback; if(arguments.length === 2){ - options = arguments[0] - callback = arguments[1] + options = arguments[0]; + callback = arguments[1]; }else if(arguments.length === 1){ if(typeof arguments[0] === 'function'){ - options = {} - callback = arguments[0] + options = {}; + callback = arguments[0]; }else{ - options = arguments[0] + options = arguments[0]; } }else if(arguments.length === 0){ - options = {} + options = {}; } - const generator = new Generator(options) + const generator = new Generator(options); if(callback){ - const data = [] + const data = []; generator.on('readable', function(){ - let d; while(d = generator.read()){ - data.push(d) + let d; while((d = generator.read()) !== null){ + data.push(d); } - }) - generator.on('error', callback) + }); + generator.on('error', callback); generator.on('end', function(){ if(generator.options.objectMode){ - callback(null, data) + callback(null, data); }else{ if(generator.options.encoding){ - callback(null, data.join('')) + callback(null, data.join('')); }else{ - callback(null, Buffer.concat(data)) + callback(null, Buffer.concat(data)); } } - }) + }); } - return generator -} + return generator; +}; -Generator = function(options = {}){ - // Convert Stream Readable options if underscored - if(options.high_water_mark){ - options.highWaterMark = options.high_water_mark - } - if(options.object_mode){ - options.objectMode = options.object_mode - } - // Call parent constructor - stream.Readable.call(this, options) - // Clone and camelize options - this.options = {} - for(let k in options){ - this.options[Generator.camelize(k)] = options[k] - } - // Normalize options - const dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0, - } - for(const k in dft){ - if(this.options[k] === undefined){ - this.options[k] = dft[k] - } - } - // Default values - if(this.options.eof === true){ - this.options.eof = this.options.rowDelimiter - } - // State - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0, - } - if(typeof this.options.columns === 'number'){ - this.options.columns = new Array(this.options.columns) - } - const accepted_header_types = Object.keys(Generator).filter( (t) => ( !['super_', 'camelize'].includes(t) )) - for(let i = 0; i < this.options.columns.length; i++){ - const v = this.options.columns[i] || 'ascii' - if(typeof v === 'string'){ - if(!accepted_header_types.includes(v)){ - throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`) - } - this.options.columns[i] = Generator[v] - } - } - return this -} -util.inherits(Generator, stream.Readable) -// Export the class -module.exports.Generator = Generator -// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. -Generator.prototype.random = function(){ - if(this.options.seed){ - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100 - }else{ - return Math.random() - } -} -// Stop the generation. -Generator.prototype.end = function(){ - this.push(null) -} -// Put new data into the read queue. -Generator.prototype._read = function(size){ - // Already started - const data = [] - let length = this._.fixed_size_buffer.length - if(length !== 0){ - data.push(this._.fixed_size_buffer) - } - while(true){ - // Time for some rest: flush first and stop later - if( (this._.count_created === this.options.length) || (this.options.end && Date.now() > this.options.end) || (this.options.duration && Date.now() > this._.start_time + this.options.duration) ){ - // Flush - if(data.length){ - if(this.options.objectMode){ - for(const line of data){ - this.__push(line) - } - }else{ - this.__push(data.join('') + (this.options.eof ? this.options.eof : '')) - } - } - // Stop - return this.push(null) - } - // Create the line - let line = [] - let lineLength - this.options.columns.forEach((fn) => { - line.push(fn(this)) - }) - // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - if(this.options.objectMode){ - lineLength = 0 - for(const column of line) - lineLength += column.length - }else{ - // Stringify the line - line = (this._.count_created === 0 ? '' : this.options.rowDelimiter)+line.join(this.options.delimiter) - lineLength = line.length - } - this._.count_created++ - if(length + lineLength > size){ - if(this.options.objectMode){ - data.push(line) - for(const line of data){ - this.__push(line) - } - }else{ - if(this.options.fixedSize){ - this._.fixed_size_buffer = line.substr(size - length) - data.push(line.substr(0, size - length)) - }else{ - data.push(line) - } - this.__push(data.join('')) - } - return - } - length += lineLength - data.push(line) - } -} -// Put new data into the read queue. -Generator.prototype.__push = function(record){ - this._.count_written++ - if(this.options.sleep > 0){ - setTimeout( () => { - this.push(record) - }, this.options.sleep) - }else{ - this.push(record) - } -} -// Generate an ASCII value. -Generator.ascii = function(gen){ - // Column - const column = [] - const nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength) - for(let i=0; i; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/lib/stream.js b/node_modules/csv-generate/lib/stream.js new file mode 100644 index 0000000..38ca139 --- /dev/null +++ b/node_modules/csv-generate/lib/stream.js @@ -0,0 +1,23 @@ + +import { + ReadableStream, +} from 'node:stream/web'; +import {normalize_options, init_state, read} from './api/index.js'; + +const generate = (opts) => { + const options = normalize_options(opts || {}); + const state = init_state(options); + return new ReadableStream({ + async pull(controller) { + read(options, state, 1024, function(chunk) { + chunk = Buffer.from(chunk); + controller.enqueue(chunk); + }, function(){ + controller.close(); + }); + } + }, {highWaterMark: 1024}); + // return new Generator(options || {}) +}; + +export {generate}; diff --git a/node_modules/csv-generate/lib/sync.d.ts b/node_modules/csv-generate/lib/sync.d.ts new file mode 100644 index 0000000..965ad63 --- /dev/null +++ b/node_modules/csv-generate/lib/sync.d.ts @@ -0,0 +1,6 @@ + +import { Options } from './index.js'; + +declare function generate(options: number | Options): string & Array; +// export default generate; +export { generate, Options }; diff --git a/node_modules/csv-generate/lib/sync.js b/node_modules/csv-generate/lib/sync.js index cd90a0a..be42baa 100644 --- a/node_modules/csv-generate/lib/sync.js +++ b/node_modules/csv-generate/lib/sync.js @@ -6,41 +6,38 @@ Please look at the [project documentation](https://csv.js.org/generate/) for additional information. */ -const generate = require('.') +import { Generator } from './index.js'; -module.exports = function(options){ +const generate = function(options){ if(typeof options === 'string' && /\d+/.test(options)){ - options = parseInt(options) + options = parseInt(options); } if(Number.isInteger(options)){ - options = {length: options} + options = {length: options}; }else if(typeof options !== 'object' || options === null){ - throw Error('Invalid Argument: options must be an o object or a integer') + throw Error('Invalid Argument: options must be an object or an integer'); } if(!Number.isInteger(options.length)){ - throw Error('Invalid Argument: length is not defined') + throw Error('Invalid Argument: length is not defined'); } - const chunks = [] - let work = true - // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options - options.highWaterMark = options.objectMode ? 16 : 16384 - const generator = new generate.Generator(options) + const chunks = []; + let work = true; + const generator = new Generator(options); generator.push = function(chunk){ if(chunk === null){ - return work = false + return work = false; } - if(options.objectMode){ - chunks.push(chunk) - }else{ - chunks.push(chunk) - } - } + chunks.push(chunk); + }; while(work){ - generator._read(options.highWaterMark) + generator.__read(options.highWaterMark); } if(!options.objectMode){ - return chunks.join('') + return chunks.join(''); }else{ - return chunks + return chunks; } -} +}; + +// export default generate +export {generate}; diff --git a/node_modules/csv-generate/package.json b/node_modules/csv-generate/package.json index 31b3ffb..365da74 100644 --- a/node_modules/csv-generate/package.json +++ b/node_modules/csv-generate/package.json @@ -1,74 +1,129 @@ { - "version": "3.4.3", + "version": "4.4.0", "name": "csv-generate", "description": "CSV and object generation implementing the Node.js `stream.Readable` API", "keywords": [ "stream", "generate", "csv", - "object" + "object", + "backend", + "frontend" ], - "license": "MIT", - "repository": { - "type": "git", - "url": "http://www.github.com/adaltas/node-csv-generate" - }, - "homepage": "https://csv.js.org/generate/", "bugs": "https://github.com/adaltas/node-csv-generate/issues", "author": "David Worms (https://www.adaltas.com)", - "coffeelintConfig": { - "indentation": { - "level": "error", - "value": 2 - }, - "line_endings": { - "level": "error", - "value": "unix" - }, - "max_line_length": { - "level": "ignore" - } - }, "devDependencies": { - "@babel/cli": "^7.14.8", - "@babel/core": "^7.15.0", - "@babel/preset-env": "^7.15.0", - "@types/mocha": "^9.0.0", - "@types/node": "^16.7.8", + "@rollup/plugin-eslint": "^9.0.4", + "@rollup/plugin-node-resolve": "^15.2.1", + "@types/mocha": "^10.0.1", + "@types/node": "^20.5.6", "@types/should": "^13.0.0", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "coffeescript": "~2.5.1", - "each": "^1.2.2", - "mocha": "~9.1.1", + "coffeescript": "~2.7.0", + "each": "^2.4.0", + "eslint": "^8.47.0", + "mocha": "~10.2.0", + "rollup": "^3.28.1", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", "should": "~13.2.3", - "ts-node": "^10.2.1", - "typescript": "^4.4.2" + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./sync": { + "import": { + "types": "./lib/sync.d.ts", + "default": "./lib/sync.js" + }, + "require": { + "types": "./dist/cjs/sync.d.cts", + "default": "./dist/cjs/sync.cjs" + } + }, + "./stream": { + "import": { + "types": "./lib/stream.d.ts", + "default": "./lib/stream.js" + }, + "require": { + "types": "./dist/cjs/stream.d.cts", + "default": "./dist/cjs/stream.cjs" + } + }, + "./browser/esm": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "./browser/esm/sync": { + "types": "./dist/esm/sync.d.ts", + "default": "./dist/esm/sync.js" + } }, "files": [ - "/lib" + "dist", + "lib" ], - "main": "./lib", + "homepage": "https://csv.js.org/generate", + "license": "MIT", + "main": "./dist/cjs/index.cjs", "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "coffeescript/register", - "ts-node/register" - ], "inline-diffs": true, - "timeout": 40000, + "loader": "./test/loaders/all.js", + "recursive": true, "reporter": "spec", - "recursive": true + "require": [ + "should" + ], + "throw-deprecation": true, + "timeout": 40000 + }, + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-csv.git", + "directory": "packages/csv-generate" }, "scripts": { - "build:babel": "cd lib && babel *.js -d es5 && cd ..", - "build:browserify": "browserify lib/index.js --transform babelify --standalone parse > lib/browser/index.js && browserify lib/sync.js --transform babelify --standalone parse > lib/browser/sync.js", - "build": "npm run build:babel && npm run build:browserify", - "preversion": "cp lib/*.ts lib/es5 && git add lib/es5/*.ts", + "build": "npm run build:rollup && npm run build:ts", + "build:rollup": "npx rollup -c", + "build:ts": "cp lib/index.d.ts dist/cjs/index.d.cts && cp lib/stream.d.ts dist/cjs/stream.d.cts && cp lib/sync.d.ts dist/cjs/sync.d.cts && cp lib/*.ts dist/esm", + "postbuild:ts": "find dist/cjs -name '*.d.cts' -exec sh -c \"sed -i \"s/\\.js'/\\.cjs'/g\" {} || sed -i '' \"s/\\.js'/\\.cjs'/g\" {}\" \\;", + "lint": "npm run lint:lib && npm run lint:samples && npm run lint:test", + "postlint": "tsc --noEmit true", + "lint:lib": "eslint --fix lib/*.js", + "lint:samples": "eslint --fix samples/*.js", + "lint:test": "coffeelint --fix test/*.coffee", + "preversion": "npm run build && git add dist", "pretest": "npm run build", - "test": "mocha test/**/*.{coffee,ts}" + "test": "mocha 'test/**/*.{coffee,ts}'", + "test:legacy": "mocha --ignore test/api.web_stream.coffee --loader=./test/loaders/legacy/all.js 'test/**/*.{coffee,ts}'" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "typesVersions": { + "*": { + ".": [ + "dist/esm/index.d.ts" + ], + "sync": [ + "dist/esm/sync.d.ts" + ], + "browser/esm": [ + "dist/esm/index.d.ts" + ], + "browser/esm/sync": [ + "dist/esm/sync.d.ts" + ] + } }, - "types": "./lib/index.d.ts", - "gitHead": "0fd5209b6862655c384cda052abf38019b959e70" + "gitHead": "6575fc60ef848fb7fd3acbf5ff32130345fe1524" } diff --git a/node_modules/csv-parse/README.md b/node_modules/csv-parse/README.md index 9d8c28e..e6ad762 100644 --- a/node_modules/csv-parse/README.md +++ b/node_modules/csv-parse/README.md @@ -1,27 +1,86 @@ -# CSV Parser for Node.js +# CSV parser for Node.js and the web -[![Build Status](https://api.travis-ci.org/adaltas/node-csv-parse.svg)](https://travis-ci.org/#!/adaltas/node-csv-parse) [![NPM](https://img.shields.io/npm/dm/csv-parse)](https://www.npmjs.com/package/csv-parse) [![NPM](https://img.shields.io/npm/v/csv-parse)](https://www.npmjs.com/package/csv-parse) +[![Build Status](https://img.shields.io/github/actions/workflow/status/adaltas/node-csv/nodejs.yml?branch=master)](https://github.com/adaltas/node-csv/actions) +[![NPM](https://img.shields.io/npm/dm/csv-parse)](https://www.npmjs.com/package/csv-parse) +[![NPM](https://img.shields.io/npm/v/csv-parse)](https://www.npmjs.com/package/csv-parse) + +The [`csv-parse` package](https://csv.js.org/parse/) is a parser converting CSV text input into arrays or objects. It is part of the [CSV project](https://csv.js.org/). -Part of the [CSV module](https://csv.js.org/), this project is a parser converting CSV text input into arrays or objects. It implements the Node.js [`stream.Transform` API](http://nodejs.org/api/stream.html#stream_class_stream_transform). It also provides a simple callback-based API for convenience. It is both extremely easy to use and powerful. It was first released in 2010 and is used against big data sets by a large community. +It implements the Node.js [`stream.Transform` API](http://nodejs.org/api/stream.html#stream_class_stream_transform). It also provides a simple callback-based API for convenience. It is both extremely easy to use and powerful. It was first released in 2010 and is used against big data sets by a large community. ## Documentation -* [Project homepage](http://csv.js.org/parse/) -* [API](http://csv.js.org/parse/api/) -* [Options](http://csv.js.org/parse/options/) -* [Info properties](http://csv.js.org/parse/info/) -* [Common errors](http://csv.js.org/parse/errors/) -* [Examples](http://csv.js.org/project/examples/) +* [Project homepage](https://csv.js.org/parse/) +* [API](https://csv.js.org/parse/api/) +* [Options](https://csv.js.org/parse/options/) +* [Info properties](https://csv.js.org/parse/info/) +* [Common errors](https://csv.js.org/parse/errors/) +* [Examples](https://csv.js.org/project/examples/) -## Features +## Main features +* Flexible with lot of [options](https://csv.js.org/parse/options/) +* Multiple [distributions](https://csv.js.org/parse/distributions/): Node.js, Web, ECMAScript modules and CommonJS * Follow the Node.js streaming API * Simplicity with the optional callback API * Support delimiters, quotes, escape characters and comments * Line breaks discovery * Support big datasets -* Complete test coverage and samples for inspiration +* Complete test coverage and lot of samples for inspiration * No external dependencies * Work nicely with the [csv-generate](https://csv.js.org/generate/), [stream-transform](https://csv.js.org/transform/) and [csv-stringify](https://csv.js.org/stringify/) packages * MIT License + +## Usage + +Run `npm install csv` to install the full CSV module or run `npm install csv-parse` if you are only interested by the CSV parser. + +Use the callback and sync APIs for simplicity or the stream based API for scalability. + +## Example + +The [API](https://csv.js.org/parse/api/) is available in multiple flavors. This example illustrates the stream API. + +```js +import assert from 'assert'; +import { parse } from 'csv-parse'; + +const records = []; +// Initialize the parser +const parser = parse({ + delimiter: ':' +}); +// Use the readable stream api to consume records +parser.on('readable', function(){ + let record; + while ((record = parser.read()) !== null) { + records.push(record); + } +}); +// Catch any error +parser.on('error', function(err){ + console.error(err.message); +}); +// Test that the parsed records matched the expected records +parser.on('end', function(){ + assert.deepStrictEqual( + records, + [ + [ 'root','x','0','0','root','/root','/bin/bash' ], + [ 'someone','x','1022','1022','','/home/someone','/bin/bash' ] + ] + ); +}); +// Write data to the stream +parser.write("root:x:0:0:root:/root:/bin/bash\n"); +parser.write("someone:x:1022:1022::/home/someone:/bin/bash\n"); +// Close the readable stream +parser.end(); +``` + +## Contributors + +The project is sponsored by [Adaltas](https://www.adaltas.com), an Big Data consulting firm based in Paris, France. + +* David Worms: diff --git a/node_modules/csv-parse/dist/cjs/index.cjs b/node_modules/csv-parse/dist/cjs/index.cjs new file mode 100644 index 0000000..b3313f5 --- /dev/null +++ b/node_modules/csv-parse/dist/cjs/index.cjs @@ -0,0 +1,1424 @@ +'use strict'; + +var stream = require('stream'); + +const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(Buffer.isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!Buffer.isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!Buffer.isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(Buffer.isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!Buffer.isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +class Parser extends stream.Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } +} + +const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; +}; + +exports.CsvError = CsvError; +exports.Parser = Parser; +exports.parse = parse; diff --git a/node_modules/csv-parse/dist/cjs/index.d.cts b/node_modules/csv-parse/dist/cjs/index.d.cts new file mode 100644 index 0000000..ec8aa02 --- /dev/null +++ b/node_modules/csv-parse/dist/cjs/index.d.cts @@ -0,0 +1,283 @@ +// Original definitions in https://github.com/DefinitelyTyped/DefinitelyTyped by: David Muller + +/// + +import * as stream from "stream"; + +export type Callback = (err: CsvError | undefined, records: any | undefined, info: Info) => void; + +export interface Parser extends stream.Transform {} + +export class Parser { + constructor(options: Options); + + __push(line: any): any; + + __write(chars: any, end: any, callback: any): any; + + readonly options: Options + + readonly info: Info; +} + +export interface CastingContext { + readonly column: number | string; + readonly empty_lines: number; + readonly error: CsvError; + readonly header: boolean; + readonly index: number; + readonly quoting: boolean; + readonly lines: number; + readonly records: number; + readonly invalid_field_length: number; +} + +export type CastingFunction = (value: string, context: CastingContext) => any; + +export type CastingDateFunction = (value: string, context: CastingContext) => Date; + +export type ColumnOption = string | undefined | null | false | { name: string }; + +/* +Note, could not `extends stream.TransformOptions` because encoding can be +BufferEncoding and undefined as well as null which is not defined in the +extended type. +*/ +export interface Options { + /** + * If true, the parser will attempt to convert read data types to native types. + * @deprecated Use {@link cast} + */ + auto_parse?: boolean | CastingFunction; + autoParse?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. + * @deprecated Use {@link cast_date} + */ + auto_parse_date?: boolean | CastingDateFunction; + autoParseDate?: boolean | CastingDateFunction; + /** + * If true, detect and exclude the byte order mark (BOM) from the CSV input if present. + */ + bom?: boolean; + /** + * If true, the parser will attempt to convert input string to native types. + * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below. + */ + cast?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert input string to dates. + * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse. + */ + cast_date?: boolean | CastingDateFunction; + castDate?: boolean | CastingDateFunction; + /** + * List of fields as an array, + * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, + * default to null, + * affect the result data set in the sense that records will be objects instead of arrays. + */ + columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]); + /** + * Convert values into an array of values when columns are activated and + * when multiple columns of the same name are found. + */ + group_columns_by_name?: boolean; + groupColumnsByName?: boolean; + /** + * Treat all the characters after this one as a comment, default to '' (disabled). + */ + comment?: string; + /** + * Restrict the definition of comments to a full line. Comment characters + * defined in the middle of the line are not interpreted as such. The + * option require the activation of comments. + */ + comment_no_infix?: boolean; + /** + * Set the field delimiter. One character only, defaults to comma. + */ + delimiter?: string | string[] | Buffer; + /** + * Set the source and destination encoding, a value of `null` returns buffer instead of strings. + */ + encoding?: BufferEncoding | undefined; + /** + * Set the escape character, one character only, defaults to double quotes. + */ + escape?: string | null | false | Buffer; + /** + * Start handling records from the requested number of records. + */ + from?: number; + /** + * Start handling records from the requested line number. + */ + from_line?: number; + fromLine?: number; + /** + * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`. + */ + ignore_last_delimiters?: boolean | number; + /** + * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object. + */ + info?: boolean; + /** + * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + ltrim?: boolean; + /** + * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, + * used to guard against a wrong delimiter or record_delimiter, + * default to 128000 characters. + */ + max_record_size?: number; + maxRecordSize?: number; + /** + * Name of header-record title to name objects by. + */ + objname?: string; + /** + * Alter and filter records by executing a user defined function. + */ + on_record?: (record: any, context: CastingContext) => any; + onRecord?: (record: any, context: CastingContext) => any; + /** + * Optional character surrounding a field, one character only, defaults to double quotes. + */ + quote?: string | boolean | Buffer | null; + /** + * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object. + */ + raw?: boolean; + /** + * Discard inconsistent columns count, default to false. + */ + relax_column_count?: boolean; + relaxColumnCount?: boolean; + /** + * Discard inconsistent columns count when the record contains less fields than expected, default to false. + */ + relax_column_count_less?: boolean; + relaxColumnCountLess?: boolean; + /** + * Discard inconsistent columns count when the record contains more fields than expected, default to false. + */ + relax_column_count_more?: boolean; + relaxColumnCountMore?: boolean; + /** + * Preserve quotes inside unquoted field. + */ + relax_quotes?: boolean; + relaxQuotes?: boolean; + /** + * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided. + * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters. + */ + record_delimiter?: string | string[] | Buffer | Buffer[]; + recordDelimiter?: string | string[] | Buffer | Buffer[]; + /** + * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + rtrim?: boolean; + /** + * Dont generate empty values for empty lines. + * Defaults to false + */ + skip_empty_lines?: boolean; + skipEmptyLines?: boolean; + /** + * Skip a line with error found inside and directly go process the next line. + */ + skip_records_with_error?: boolean; + skipRecordsWithError?: boolean; + /** + * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false. + */ + skip_records_with_empty_values?: boolean; + skipRecordsWithEmptyValues?: boolean; + /** + * Stop handling records after the requested number of records. + */ + to?: number; + /** + * Stop handling records after the requested line number. + */ + to_line?: number; + toLine?: number; + /** + * If true, ignore whitespace immediately around the delimiter, defaults to false. + * Does not remove whitespace in a quoted field. + */ + trim?: boolean; +} + +export interface Info { + /** + * Count the number of lines being fully commented. + */ + readonly comment_lines: number; + /** + * Count the number of processed empty lines. + */ + readonly empty_lines: number; + /** + * The number of lines encountered in the source dataset, start at 1 for the first line. + */ + readonly lines: number; + /** + * Count the number of processed records. + */ + readonly records: number; + /** + * Count of the number of processed bytes. + */ + readonly bytes: number; + /** + * Number of non uniform records when `relax_column_count` is true. + */ + readonly invalid_field_length: number; + /** + * Normalized verion of `options.columns` when `options.columns` is true, boolean otherwise. + */ + readonly columns: boolean | { name: string }[] | { disabled: true }[]; +} + +export type CsvErrorCode = + 'CSV_INVALID_OPTION_BOM' + | 'CSV_INVALID_OPTION_CAST' + | 'CSV_INVALID_OPTION_CAST_DATE' + | 'CSV_INVALID_OPTION_COLUMNS' + | 'CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME' + | 'CSV_INVALID_OPTION_COMMENT' + | 'CSV_INVALID_OPTION_DELIMITER' + | 'CSV_INVALID_OPTION_ON_RECORD' + | 'CSV_INVALID_CLOSING_QUOTE' + | 'INVALID_OPENING_QUOTE' + | 'CSV_INVALID_COLUMN_MAPPING' + | 'CSV_INVALID_ARGUMENT' + | 'CSV_INVALID_COLUMN_DEFINITION' + | 'CSV_MAX_RECORD_SIZE' + | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE' + | 'CSV_QUOTE_NOT_CLOSED' + | 'CSV_RECORD_INCONSISTENT_FIELDS_LENGTH' + | 'CSV_RECORD_INCONSISTENT_COLUMNS' + | 'CSV_OPTION_COLUMNS_MISSING_NAME' + +export class CsvError extends Error { + readonly code: CsvErrorCode; + [key: string]: any; + + constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]); +} + +declare function parse(input: Buffer | string, options?: Options, callback?: Callback): Parser; +declare function parse(input: Buffer | string, callback?: Callback): Parser; +declare function parse(options?: Options, callback?: Callback): Parser; +declare function parse(callback?: Callback): Parser; + +// export default parse; +export { parse } diff --git a/node_modules/csv-parse/dist/cjs/sync.cjs b/node_modules/csv-parse/dist/cjs/sync.cjs new file mode 100644 index 0000000..f05e6aa --- /dev/null +++ b/node_modules/csv-parse/dist/cjs/sync.cjs @@ -0,0 +1,1336 @@ +'use strict'; + +class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(Buffer.isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!Buffer.isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!Buffer.isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(Buffer.isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!Buffer.isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; +}; + +exports.CsvError = CsvError; +exports.parse = parse; diff --git a/node_modules/csv-parse/dist/cjs/sync.d.cts b/node_modules/csv-parse/dist/cjs/sync.d.cts new file mode 100644 index 0000000..835666e --- /dev/null +++ b/node_modules/csv-parse/dist/cjs/sync.d.cts @@ -0,0 +1,11 @@ + +import { Options } from './index.cjs'; + +declare function parse(input: Buffer | string, options?: Options): any; +// export default parse; +export { parse }; + +export { + CastingContext, CastingFunction, CastingDateFunction, + ColumnOption, Options, Info, CsvErrorCode, CsvError +} from './index.cjs'; diff --git a/node_modules/csv-parse/dist/esm/index.d.ts b/node_modules/csv-parse/dist/esm/index.d.ts new file mode 100644 index 0000000..ec8aa02 --- /dev/null +++ b/node_modules/csv-parse/dist/esm/index.d.ts @@ -0,0 +1,283 @@ +// Original definitions in https://github.com/DefinitelyTyped/DefinitelyTyped by: David Muller + +/// + +import * as stream from "stream"; + +export type Callback = (err: CsvError | undefined, records: any | undefined, info: Info) => void; + +export interface Parser extends stream.Transform {} + +export class Parser { + constructor(options: Options); + + __push(line: any): any; + + __write(chars: any, end: any, callback: any): any; + + readonly options: Options + + readonly info: Info; +} + +export interface CastingContext { + readonly column: number | string; + readonly empty_lines: number; + readonly error: CsvError; + readonly header: boolean; + readonly index: number; + readonly quoting: boolean; + readonly lines: number; + readonly records: number; + readonly invalid_field_length: number; +} + +export type CastingFunction = (value: string, context: CastingContext) => any; + +export type CastingDateFunction = (value: string, context: CastingContext) => Date; + +export type ColumnOption = string | undefined | null | false | { name: string }; + +/* +Note, could not `extends stream.TransformOptions` because encoding can be +BufferEncoding and undefined as well as null which is not defined in the +extended type. +*/ +export interface Options { + /** + * If true, the parser will attempt to convert read data types to native types. + * @deprecated Use {@link cast} + */ + auto_parse?: boolean | CastingFunction; + autoParse?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. + * @deprecated Use {@link cast_date} + */ + auto_parse_date?: boolean | CastingDateFunction; + autoParseDate?: boolean | CastingDateFunction; + /** + * If true, detect and exclude the byte order mark (BOM) from the CSV input if present. + */ + bom?: boolean; + /** + * If true, the parser will attempt to convert input string to native types. + * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below. + */ + cast?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert input string to dates. + * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse. + */ + cast_date?: boolean | CastingDateFunction; + castDate?: boolean | CastingDateFunction; + /** + * List of fields as an array, + * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, + * default to null, + * affect the result data set in the sense that records will be objects instead of arrays. + */ + columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]); + /** + * Convert values into an array of values when columns are activated and + * when multiple columns of the same name are found. + */ + group_columns_by_name?: boolean; + groupColumnsByName?: boolean; + /** + * Treat all the characters after this one as a comment, default to '' (disabled). + */ + comment?: string; + /** + * Restrict the definition of comments to a full line. Comment characters + * defined in the middle of the line are not interpreted as such. The + * option require the activation of comments. + */ + comment_no_infix?: boolean; + /** + * Set the field delimiter. One character only, defaults to comma. + */ + delimiter?: string | string[] | Buffer; + /** + * Set the source and destination encoding, a value of `null` returns buffer instead of strings. + */ + encoding?: BufferEncoding | undefined; + /** + * Set the escape character, one character only, defaults to double quotes. + */ + escape?: string | null | false | Buffer; + /** + * Start handling records from the requested number of records. + */ + from?: number; + /** + * Start handling records from the requested line number. + */ + from_line?: number; + fromLine?: number; + /** + * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`. + */ + ignore_last_delimiters?: boolean | number; + /** + * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object. + */ + info?: boolean; + /** + * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + ltrim?: boolean; + /** + * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, + * used to guard against a wrong delimiter or record_delimiter, + * default to 128000 characters. + */ + max_record_size?: number; + maxRecordSize?: number; + /** + * Name of header-record title to name objects by. + */ + objname?: string; + /** + * Alter and filter records by executing a user defined function. + */ + on_record?: (record: any, context: CastingContext) => any; + onRecord?: (record: any, context: CastingContext) => any; + /** + * Optional character surrounding a field, one character only, defaults to double quotes. + */ + quote?: string | boolean | Buffer | null; + /** + * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object. + */ + raw?: boolean; + /** + * Discard inconsistent columns count, default to false. + */ + relax_column_count?: boolean; + relaxColumnCount?: boolean; + /** + * Discard inconsistent columns count when the record contains less fields than expected, default to false. + */ + relax_column_count_less?: boolean; + relaxColumnCountLess?: boolean; + /** + * Discard inconsistent columns count when the record contains more fields than expected, default to false. + */ + relax_column_count_more?: boolean; + relaxColumnCountMore?: boolean; + /** + * Preserve quotes inside unquoted field. + */ + relax_quotes?: boolean; + relaxQuotes?: boolean; + /** + * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided. + * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters. + */ + record_delimiter?: string | string[] | Buffer | Buffer[]; + recordDelimiter?: string | string[] | Buffer | Buffer[]; + /** + * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + rtrim?: boolean; + /** + * Dont generate empty values for empty lines. + * Defaults to false + */ + skip_empty_lines?: boolean; + skipEmptyLines?: boolean; + /** + * Skip a line with error found inside and directly go process the next line. + */ + skip_records_with_error?: boolean; + skipRecordsWithError?: boolean; + /** + * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false. + */ + skip_records_with_empty_values?: boolean; + skipRecordsWithEmptyValues?: boolean; + /** + * Stop handling records after the requested number of records. + */ + to?: number; + /** + * Stop handling records after the requested line number. + */ + to_line?: number; + toLine?: number; + /** + * If true, ignore whitespace immediately around the delimiter, defaults to false. + * Does not remove whitespace in a quoted field. + */ + trim?: boolean; +} + +export interface Info { + /** + * Count the number of lines being fully commented. + */ + readonly comment_lines: number; + /** + * Count the number of processed empty lines. + */ + readonly empty_lines: number; + /** + * The number of lines encountered in the source dataset, start at 1 for the first line. + */ + readonly lines: number; + /** + * Count the number of processed records. + */ + readonly records: number; + /** + * Count of the number of processed bytes. + */ + readonly bytes: number; + /** + * Number of non uniform records when `relax_column_count` is true. + */ + readonly invalid_field_length: number; + /** + * Normalized verion of `options.columns` when `options.columns` is true, boolean otherwise. + */ + readonly columns: boolean | { name: string }[] | { disabled: true }[]; +} + +export type CsvErrorCode = + 'CSV_INVALID_OPTION_BOM' + | 'CSV_INVALID_OPTION_CAST' + | 'CSV_INVALID_OPTION_CAST_DATE' + | 'CSV_INVALID_OPTION_COLUMNS' + | 'CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME' + | 'CSV_INVALID_OPTION_COMMENT' + | 'CSV_INVALID_OPTION_DELIMITER' + | 'CSV_INVALID_OPTION_ON_RECORD' + | 'CSV_INVALID_CLOSING_QUOTE' + | 'INVALID_OPENING_QUOTE' + | 'CSV_INVALID_COLUMN_MAPPING' + | 'CSV_INVALID_ARGUMENT' + | 'CSV_INVALID_COLUMN_DEFINITION' + | 'CSV_MAX_RECORD_SIZE' + | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE' + | 'CSV_QUOTE_NOT_CLOSED' + | 'CSV_RECORD_INCONSISTENT_FIELDS_LENGTH' + | 'CSV_RECORD_INCONSISTENT_COLUMNS' + | 'CSV_OPTION_COLUMNS_MISSING_NAME' + +export class CsvError extends Error { + readonly code: CsvErrorCode; + [key: string]: any; + + constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]); +} + +declare function parse(input: Buffer | string, options?: Options, callback?: Callback): Parser; +declare function parse(input: Buffer | string, callback?: Callback): Parser; +declare function parse(options?: Options, callback?: Callback): Parser; +declare function parse(callback?: Callback): Parser; + +// export default parse; +export { parse } diff --git a/node_modules/csv-parse/dist/esm/index.js b/node_modules/csv-parse/dist/esm/index.js new file mode 100644 index 0000000..bfffcfd --- /dev/null +++ b/node_modules/csv-parse/dist/esm/index.js @@ -0,0 +1,6544 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } +} + +const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; +}; + +export { CsvError, Parser, parse }; diff --git a/node_modules/csv-parse/dist/esm/sync.d.ts b/node_modules/csv-parse/dist/esm/sync.d.ts new file mode 100644 index 0000000..b507e8b --- /dev/null +++ b/node_modules/csv-parse/dist/esm/sync.d.ts @@ -0,0 +1,11 @@ + +import { Options } from './index.js'; + +declare function parse(input: Buffer | string, options?: Options): any; +// export default parse; +export { parse }; + +export { + CastingContext, CastingFunction, CastingDateFunction, + ColumnOption, Options, Info, CsvErrorCode, CsvError +} from './index.js'; diff --git a/node_modules/csv-parse/dist/esm/sync.js b/node_modules/csv-parse/dist/esm/sync.js new file mode 100644 index 0000000..09a250d --- /dev/null +++ b/node_modules/csv-parse/dist/esm/sync.js @@ -0,0 +1,3305 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; +}; + +export { CsvError, parse }; diff --git a/node_modules/csv-parse/dist/iife/index.js b/node_modules/csv-parse/dist/iife/index.js new file mode 100644 index 0000000..43810dc --- /dev/null +++ b/node_modules/csv-parse/dist/iife/index.js @@ -0,0 +1,6553 @@ +var csv_parse = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } + } + + const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; + }; + + exports.CsvError = CsvError; + exports.Parser = Parser; + exports.parse = parse; + + return exports; + +})({}); diff --git a/node_modules/csv-parse/dist/iife/sync.js b/node_modules/csv-parse/dist/iife/sync.js new file mode 100644 index 0000000..1b5ce0d --- /dev/null +++ b/node_modules/csv-parse/dist/iife/sync.js @@ -0,0 +1,3313 @@ +var csv_parse_sync = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; + }; + + exports.CsvError = CsvError; + exports.parse = parse; + + return exports; + +})({}); diff --git a/node_modules/csv-parse/dist/umd/index.js b/node_modules/csv-parse/dist/umd/index.js new file mode 100644 index 0000000..8ecfc7c --- /dev/null +++ b/node_modules/csv-parse/dist/umd/index.js @@ -0,0 +1,6554 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_parse = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } + } + + const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; + }; + + exports.CsvError = CsvError; + exports.Parser = Parser; + exports.parse = parse; + +})); diff --git a/node_modules/csv-parse/dist/umd/sync.js b/node_modules/csv-parse/dist/umd/sync.js new file mode 100644 index 0000000..ebe39aa --- /dev/null +++ b/node_modules/csv-parse/dist/umd/sync.js @@ -0,0 +1,3314 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_parse_sync = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer(options.escape) && isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; + }; + + exports.CsvError = CsvError; + exports.parse = parse; + +})); diff --git a/node_modules/csv-parse/lib/ResizeableBuffer.js b/node_modules/csv-parse/lib/ResizeableBuffer.js deleted file mode 100644 index 467422c..0000000 --- a/node_modules/csv-parse/lib/ResizeableBuffer.js +++ /dev/null @@ -1,65 +0,0 @@ - - -class ResizeableBuffer{ - constructor(size=100){ - this.size = size - this.length = 0 - this.buf = Buffer.alloc(size) - } - prepend(val){ - if(Buffer.isBuffer(val)){ - const length = this.length + val.length - if(length >= this.size){ - this.resize() - if(length >= this.size){ - throw Error('INVALID_BUFFER_STATE') - } - } - const buf = this.buf - this.buf = Buffer.alloc(this.size) - val.copy(this.buf, 0) - buf.copy(this.buf, val.length) - this.length += val.length - }else{ - const length = this.length++ - if(length === this.size){ - this.resize() - } - const buf = this.clone() - this.buf[0] = val - buf.copy(this.buf,1, 0, length) - } - } - append(val){ - const length = this.length++ - if(length === this.size){ - this.resize() - } - this.buf[length] = val - } - clone(){ - return Buffer.from(this.buf.slice(0, this.length)) - } - resize(){ - const length = this.length - this.size = this.size * 2 - const buf = Buffer.alloc(this.size) - this.buf.copy(buf,0, 0, length) - this.buf = buf - } - toString(encoding){ - if(encoding){ - return this.buf.slice(0, this.length).toString(encoding) - }else{ - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)) - } - } - toJSON(){ - return this.toString('utf8') - } - reset(){ - this.length = 0 - } -} - -module.exports = ResizeableBuffer diff --git a/node_modules/csv-parse/lib/api/CsvError.js b/node_modules/csv-parse/lib/api/CsvError.js new file mode 100644 index 0000000..1af8353 --- /dev/null +++ b/node_modules/csv-parse/lib/api/CsvError.js @@ -0,0 +1,19 @@ + +class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +export {CsvError}; diff --git a/node_modules/csv-parse/lib/api/index.js b/node_modules/csv-parse/lib/api/index.js new file mode 100644 index 0000000..0fc5e3f --- /dev/null +++ b/node_modules/csv-parse/lib/api/index.js @@ -0,0 +1,729 @@ + +import {normalize_columns_array} from './normalize_columns_array.js'; +import {init_state} from './init_state.js'; +import {normalize_options} from './normalize_options.js'; +import {CsvError} from './CsvError.js'; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else{ + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else{ + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else{ + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else{ + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else{ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else{ + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else{ + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else{ + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else{ + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else{ + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else{ + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else{ + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else{ + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else{ + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else{ + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else{ + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else{ + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + + +export {transform, CsvError}; diff --git a/node_modules/csv-parse/lib/api/init_state.js b/node_modules/csv-parse/lib/api/init_state.js new file mode 100644 index 0000000..e2a68c3 --- /dev/null +++ b/node_modules/csv-parse/lib/api/init_state.js @@ -0,0 +1,58 @@ + +import ResizeableBuffer from '../utils/ResizeableBuffer.js'; + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +export {init_state}; diff --git a/node_modules/csv-parse/lib/api/normalize_columns_array.js b/node_modules/csv-parse/lib/api/normalize_columns_array.js new file mode 100644 index 0000000..5d1f5e4 --- /dev/null +++ b/node_modules/csv-parse/lib/api/normalize_columns_array.js @@ -0,0 +1,33 @@ + +import {CsvError} from './CsvError.js'; +import {is_object} from '../utils/is_object.js'; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else{ + throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +export {normalize_columns_array}; diff --git a/node_modules/csv-parse/lib/api/normalize_options.js b/node_modules/csv-parse/lib/api/normalize_options.js new file mode 100644 index 0000000..fa58388 --- /dev/null +++ b/node_modules/csv-parse/lib/api/normalize_options.js @@ -0,0 +1,448 @@ + +import {normalize_columns_array} from './normalize_columns_array.js'; +import {CsvError} from './CsvError.js'; +import {underscore} from '../utils/underscore.js'; + +const normalize_options = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else{ + throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else{ + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!Buffer.isBuffer(options.comment)){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!Buffer.isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else{ + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else{ + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else{ + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else{ + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0){ + // Great, nothing to do + }else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else{ + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(Buffer.isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null){ + // Don't call `toString`, leave objname as a buffer + }else{ + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number'){ + // if(options.objname.length === 0){ + // throw new Error(`Invalid Option: objname must be a non empty string`); + // } + // Great, nothing to do + }else{ + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else{ // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else{ + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!Buffer.isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean'){ + // Great, nothing to do + }else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else{ + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean'){ + // Great, nothing to do + }else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else{ + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean'){ + // Great, nothing to do + }else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else{ + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean'){ + // Great, nothing to do + }else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else{ + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean'){ + // Great, nothing to do + }else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else{ + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean'){ + // Great, nothing to do + }else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else{ + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean'){ + // Great, nothing to do + }else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else{ + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else{ + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else{ + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else{ + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else{ + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +export {normalize_options}; diff --git a/node_modules/csv-parse/lib/browser/index.js b/node_modules/csv-parse/lib/browser/index.js deleted file mode 100644 index 14610cf..0000000 --- a/node_modules/csv-parse/lib/browser/index.js +++ /dev/null @@ -1,8131 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0 && arguments[0] !== undefined ? arguments[0] : 100; - - _classCallCheck(this, ResizeableBuffer); - - this.size = size; - this.length = 0; - this.buf = Buffer.alloc(size); - } - - _createClass(ResizeableBuffer, [{ - key: "prepend", - value: function prepend(val) { - if (Buffer.isBuffer(val)) { - var length = this.length + val.length; - - if (length >= this.size) { - this.resize(); - - if (length >= this.size) { - throw Error('INVALID_BUFFER_STATE'); - } - } - - var buf = this.buf; - this.buf = Buffer.alloc(this.size); - val.copy(this.buf, 0); - buf.copy(this.buf, val.length); - this.length += val.length; - } else { - var _length = this.length++; - - if (_length === this.size) { - this.resize(); - } - - var _buf = this.clone(); - - this.buf[0] = val; - - _buf.copy(this.buf, 1, 0, _length); - } - } - }, { - key: "append", - value: function append(val) { - var length = this.length++; - - if (length === this.size) { - this.resize(); - } - - this.buf[length] = val; - } - }, { - key: "clone", - value: function clone() { - return Buffer.from(this.buf.slice(0, this.length)); - } - }, { - key: "resize", - value: function resize() { - var length = this.length; - this.size = this.size * 2; - var buf = Buffer.alloc(this.size); - this.buf.copy(buf, 0, 0, length); - this.buf = buf; - } - }, { - key: "toString", - value: function toString(encoding) { - if (encoding) { - return this.buf.slice(0, this.length).toString(encoding); - } else { - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); - } - } - }, { - key: "toJSON", - value: function toJSON() { - return this.toString('utf8'); - } - }, { - key: "reset", - value: function reset() { - this.length = 0; - } - }]); - - return ResizeableBuffer; -}(); - -module.exports = ResizeableBuffer; - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":5}],2:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ -"use strict"; - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Parse - -Please look at the [project documentation](https://csv.js.org/parse/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var ResizeableBuffer = require('./ResizeableBuffer'); // white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff - - -var tab = 9; -var nl = 10; // \n, 0x0A in hexadecimal, 10 in decimal - -var np = 12; -var cr = 13; // \r, 0x0D in hexadécimal, 13 in decimal - -var space = 32; -var boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -}; - -var Parser = /*#__PURE__*/function (_Transform) { - _inherits(Parser, _Transform); - - var _super = _createSuper(Parser); - - function Parser() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Parser); - - _this = _super.call(this, _objectSpread(_objectSpread(_objectSpread({}, { - readableObjectMode: true - }), opts), {}, { - encoding: null - })); - _this.__originalOptions = opts; - - _this.__normalizeOptions(opts); - - return _this; - } - - _createClass(Parser, [{ - key: "__normalizeOptions", - value: function __normalizeOptions(opts) { - var options = {}; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - - - if (options.encoding === undefined || options.encoding === true) { - options.encoding = 'utf8'; - } else if (options.encoding === null || options.encoding === false) { - options.encoding = null; - } else if (typeof options.encoding !== 'string' && options.encoding !== null) { - throw new CsvError('CSV_INVALID_OPTION_ENCODING', ['Invalid option encoding:', 'encoding must be a string or null to return a buffer,', "got ".concat(JSON.stringify(options.encoding))], options); - } // Normalize option `bom` - - - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - throw new CsvError('CSV_INVALID_OPTION_BOM', ['Invalid option bom:', 'bom must be true,', "got ".concat(JSON.stringify(options.bom))], options); - } // Normalize option `cast` - - - var fnCastField = null; - - if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === '') { - options.cast = undefined; - } else if (typeof options.cast === 'function') { - fnCastField = options.cast; - options.cast = true; - } else if (options.cast !== true) { - throw new CsvError('CSV_INVALID_OPTION_CAST', ['Invalid option cast:', 'cast must be true or a function,', "got ".concat(JSON.stringify(options.cast))], options); - } // Normalize option `cast_date` - - - if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === '') { - options.cast_date = false; - } else if (options.cast_date === true) { - options.cast_date = function (value) { - var date = Date.parse(value); - return !isNaN(date) ? new Date(date) : value; - }; - } else { - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', ['Invalid option cast_date:', 'cast_date must be true or a function,', "got ".concat(JSON.stringify(options.cast_date))], options); - } // Normalize option `columns` - - - var fnFirstLineToHeaders = null; - - if (options.columns === true) { - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined; - } else if (typeof options.columns === 'function') { - fnFirstLineToHeaders = options.columns; - options.columns = true; - } else if (Array.isArray(options.columns)) { - options.columns = normalizeColumnsArray(options.columns); - } else if (options.columns === undefined || options.columns === null || options.columns === false) { - options.columns = false; - } else { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', ['Invalid option columns:', 'expect an array, a function or true,', "got ".concat(JSON.stringify(options.columns))], options); - } // Normalize option `columns_duplicates_to_array` - - - if (options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false) { - options.columns_duplicates_to_array = false; - } else if (options.columns_duplicates_to_array !== true) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'expect an boolean,', "got ".concat(JSON.stringify(options.columns_duplicates_to_array))], options); - } else if (options.columns === false) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'the `columns` mode must be activated.'], options); - } // Normalize option `comment` - - - if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === '') { - options.comment = null; - } else { - if (typeof options.comment === 'string') { - options.comment = Buffer.from(options.comment, options.encoding); - } - - if (!Buffer.isBuffer(options.comment)) { - throw new CsvError('CSV_INVALID_OPTION_COMMENT', ['Invalid option comment:', 'comment must be a buffer or a string,', "got ".concat(JSON.stringify(options.comment))], options); - } - } // Normalize option `delimiter` - - - var delimiter_json = JSON.stringify(options.delimiter); - if (!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; - - if (options.delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - options.delimiter = options.delimiter.map(function (delimiter) { - if (delimiter === undefined || delimiter === null || delimiter === false) { - return Buffer.from(',', options.encoding); - } - - if (typeof delimiter === 'string') { - delimiter = Buffer.from(delimiter, options.encoding); - } - - if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - return delimiter; - }); // Normalize option `escape` - - if (options.escape === undefined || options.escape === true) { - options.escape = Buffer.from('"', options.encoding); - } else if (typeof options.escape === 'string') { - options.escape = Buffer.from(options.escape, options.encoding); - } else if (options.escape === null || options.escape === false) { - options.escape = null; - } - - if (options.escape !== null) { - if (!Buffer.isBuffer(options.escape)) { - throw new Error("Invalid Option: escape must be a buffer, a string or a boolean, got ".concat(JSON.stringify(options.escape))); - } - } // Normalize option `from` - - - if (options.from === undefined || options.from === null) { - options.from = 1; - } else { - if (typeof options.from === 'string' && /\d+/.test(options.from)) { - options.from = parseInt(options.from); - } - - if (Number.isInteger(options.from)) { - if (options.from < 0) { - throw new Error("Invalid Option: from must be a positive integer, got ".concat(JSON.stringify(opts.from))); - } - } else { - throw new Error("Invalid Option: from must be an integer, got ".concat(JSON.stringify(options.from))); - } - } // Normalize option `from_line` - - - if (options.from_line === undefined || options.from_line === null) { - options.from_line = 1; - } else { - if (typeof options.from_line === 'string' && /\d+/.test(options.from_line)) { - options.from_line = parseInt(options.from_line); - } - - if (Number.isInteger(options.from_line)) { - if (options.from_line <= 0) { - throw new Error("Invalid Option: from_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.from_line))); - } - } else { - throw new Error("Invalid Option: from_line must be an integer, got ".concat(JSON.stringify(opts.from_line))); - } - } // Normalize options `ignore_last_delimiters` - - - if (options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null) { - options.ignore_last_delimiters = false; - } else if (typeof options.ignore_last_delimiters === 'number') { - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); - - if (options.ignore_last_delimiters === 0) { - options.ignore_last_delimiters = false; - } - } else if (typeof options.ignore_last_delimiters !== 'boolean') { - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', ['Invalid option `ignore_last_delimiters`:', 'the value must be a boolean value or an integer,', "got ".concat(JSON.stringify(options.ignore_last_delimiters))], options); - } - - if (options.ignore_last_delimiters === true && options.columns === false) { - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', ['The option `ignore_last_delimiters`', 'requires the activation of the `columns` option'], options); - } // Normalize option `info` - - - if (options.info === undefined || options.info === null || options.info === false) { - options.info = false; - } else if (options.info !== true) { - throw new Error("Invalid Option: info must be true, got ".concat(JSON.stringify(options.info))); - } // Normalize option `max_record_size` - - - if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) { - options.max_record_size = 0; - } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {// Great, nothing to do - } else if (typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)) { - options.max_record_size = parseInt(options.max_record_size); - } else { - throw new Error("Invalid Option: max_record_size must be a positive integer, got ".concat(JSON.stringify(options.max_record_size))); - } // Normalize option `objname` - - - if (options.objname === undefined || options.objname === null || options.objname === false) { - options.objname = undefined; - } else if (Buffer.isBuffer(options.objname)) { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty buffer"); - } - - if (options.encoding === null) {// Don't call `toString`, leave objname as a buffer - } else { - options.objname = options.objname.toString(options.encoding); - } - } else if (typeof options.objname === 'string') { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty string"); - } // Great, nothing to do - - } else { - throw new Error("Invalid Option: objname must be a string or a buffer, got ".concat(options.objname)); - } // Normalize option `on_record` - - - if (options.on_record === undefined || options.on_record === null) { - options.on_record = undefined; - } else if (typeof options.on_record !== 'function') { - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', ['Invalid option `on_record`:', 'expect a function,', "got ".concat(JSON.stringify(options.on_record))], options); - } // Normalize option `quote` - - - if (options.quote === null || options.quote === false || options.quote === '') { - options.quote = null; - } else { - if (options.quote === undefined || options.quote === true) { - options.quote = Buffer.from('"', options.encoding); - } else if (typeof options.quote === 'string') { - options.quote = Buffer.from(options.quote, options.encoding); - } - - if (!Buffer.isBuffer(options.quote)) { - throw new Error("Invalid Option: quote must be a buffer or a string, got ".concat(JSON.stringify(options.quote))); - } - } // Normalize option `raw` - - - if (options.raw === undefined || options.raw === null || options.raw === false) { - options.raw = false; - } else if (options.raw !== true) { - throw new Error("Invalid Option: raw must be true, got ".concat(JSON.stringify(options.raw))); - } // Normalize option `record_delimiter` - - - if (!options.record_delimiter) { - options.record_delimiter = []; - } else if (!Array.isArray(options.record_delimiter)) { - options.record_delimiter = [options.record_delimiter]; - } - - options.record_delimiter = options.record_delimiter.map(function (rd) { - if (typeof rd === 'string') { - rd = Buffer.from(rd, options.encoding); - } - - return rd; - }); // Normalize option `relax` - - if (typeof options.relax === 'boolean') {// Great, nothing to do - } else if (options.relax === undefined || options.relax === null) { - options.relax = false; - } else { - throw new Error("Invalid Option: relax must be a boolean, got ".concat(JSON.stringify(options.relax))); - } // Normalize option `relax_column_count` - - - if (typeof options.relax_column_count === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count === undefined || options.relax_column_count === null) { - options.relax_column_count = false; - } else { - throw new Error("Invalid Option: relax_column_count must be a boolean, got ".concat(JSON.stringify(options.relax_column_count))); - } - - if (typeof options.relax_column_count_less === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) { - options.relax_column_count_less = false; - } else { - throw new Error("Invalid Option: relax_column_count_less must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_less))); - } - - if (typeof options.relax_column_count_more === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) { - options.relax_column_count_more = false; - } else { - throw new Error("Invalid Option: relax_column_count_more must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_more))); - } // Normalize option `skip_empty_lines` - - - if (typeof options.skip_empty_lines === 'boolean') {// Great, nothing to do - } else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) { - options.skip_empty_lines = false; - } else { - throw new Error("Invalid Option: skip_empty_lines must be a boolean, got ".concat(JSON.stringify(options.skip_empty_lines))); - } // Normalize option `skip_lines_with_empty_values` - - - if (typeof options.skip_lines_with_empty_values === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null) { - options.skip_lines_with_empty_values = false; - } else { - throw new Error("Invalid Option: skip_lines_with_empty_values must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_empty_values))); - } // Normalize option `skip_lines_with_error` - - - if (typeof options.skip_lines_with_error === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_error === undefined || options.skip_lines_with_error === null) { - options.skip_lines_with_error = false; - } else { - throw new Error("Invalid Option: skip_lines_with_error must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_error))); - } // Normalize option `rtrim` - - - if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) { - options.rtrim = false; - } else if (options.rtrim !== true) { - throw new Error("Invalid Option: rtrim must be a boolean, got ".concat(JSON.stringify(options.rtrim))); - } // Normalize option `ltrim` - - - if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) { - options.ltrim = false; - } else if (options.ltrim !== true) { - throw new Error("Invalid Option: ltrim must be a boolean, got ".concat(JSON.stringify(options.ltrim))); - } // Normalize option `trim` - - - if (options.trim === undefined || options.trim === null || options.trim === false) { - options.trim = false; - } else if (options.trim !== true) { - throw new Error("Invalid Option: trim must be a boolean, got ".concat(JSON.stringify(options.trim))); - } // Normalize options `trim`, `ltrim` and `rtrim` - - - if (options.trim === true && opts.ltrim !== false) { - options.ltrim = true; - } else if (options.ltrim !== true) { - options.ltrim = false; - } - - if (options.trim === true && opts.rtrim !== false) { - options.rtrim = true; - } else if (options.rtrim !== true) { - options.rtrim = false; - } // Normalize option `to` - - - if (options.to === undefined || options.to === null) { - options.to = -1; - } else { - if (typeof options.to === 'string' && /\d+/.test(options.to)) { - options.to = parseInt(options.to); - } - - if (Number.isInteger(options.to)) { - if (options.to <= 0) { - throw new Error("Invalid Option: to must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to))); - } - } else { - throw new Error("Invalid Option: to must be an integer, got ".concat(JSON.stringify(opts.to))); - } - } // Normalize option `to_line` - - - if (options.to_line === undefined || options.to_line === null) { - options.to_line = -1; - } else { - if (typeof options.to_line === 'string' && /\d+/.test(options.to_line)) { - options.to_line = parseInt(options.to_line); - } - - if (Number.isInteger(options.to_line)) { - if (options.to_line <= 0) { - throw new Error("Invalid Option: to_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to_line))); - } - } else { - throw new Error("Invalid Option: to_line must be an integer, got ".concat(JSON.stringify(opts.to_line))); - } - } - - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - }; - this.options = options; - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max.apply(Math, [// Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0].concat(_toConsumableArray(options.delimiter.map(function (delimiter) { - return delimiter.length; - })), [// Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0])), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max.apply(Math, _toConsumableArray(options.record_delimiter.map(function (v) { - return v.length; - }))), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - }; - } // Implementation of `Transform._transform` - - }, { - key: "_transform", - value: function _transform(buf, encoding, callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(buf, false); - - if (err !== undefined) { - this.state.stop = true; - } - - callback(err); - } // Implementation of `Transform._flush` - - }, { - key: "_flush", - value: function _flush(callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(undefined, true); - - callback(err); - } // Central parser implementation - - }, { - key: "__parse", - value: function __parse(nextBuf, end) { - var _this$options = this.options, - bom = _this$options.bom, - comment = _this$options.comment, - escape = _this$options.escape, - from_line = _this$options.from_line, - ltrim = _this$options.ltrim, - max_record_size = _this$options.max_record_size, - quote = _this$options.quote, - raw = _this$options.raw, - relax = _this$options.relax, - rtrim = _this$options.rtrim, - skip_empty_lines = _this$options.skip_empty_lines, - to = _this$options.to, - to_line = _this$options.to_line; - var record_delimiter = this.options.record_delimiter; - var _this$state = this.state, - bomSkipped = _this$state.bomSkipped, - previousBuf = _this$state.previousBuf, - rawBuffer = _this$state.rawBuffer, - escapeIsQuote = _this$state.escapeIsQuote; - var buf; - - if (previousBuf === undefined) { - if (nextBuf === undefined) { - // Handle empty string - this.push(null); - return; - } else { - buf = nextBuf; - } - } else if (previousBuf !== undefined && nextBuf === undefined) { - buf = previousBuf; - } else { - buf = Buffer.concat([previousBuf, nextBuf]); - } // Handle UTF BOM - - - if (bomSkipped === false) { - if (bom === false) { - this.state.bomSkipped = true; - } else if (buf.length < 3) { - // No enough data - if (end === false) { - // Wait for more data - this.state.previousBuf = buf; - return; - } - } else { - for (var encoding in boms) { - if (boms[encoding].compare(buf, 0, boms[encoding].length) === 0) { - // Skip BOM - var bomLength = boms[encoding].length; - this.state.bufBytesStart += bomLength; - buf = buf.slice(bomLength); // Renormalize original options with the new encoding - - this.__normalizeOptions(_objectSpread(_objectSpread({}, this.__originalOptions), {}, { - encoding: encoding - })); - - break; - } - } - - this.state.bomSkipped = true; - } - } - - var bufLen = buf.length; - var pos; - - for (pos = 0; pos < bufLen; pos++) { - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if (this.__needMoreData(pos, bufLen, end)) { - break; - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - - if (to_line !== -1 && this.info.lines > to_line) { - this.state.stop = true; - this.push(null); - return; - } // Auto discovery of record_delimiter, unix, mac and windows supported - - - if (this.state.quoting === false && record_delimiter.length === 0) { - var record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); - - if (record_delimiterCount) { - record_delimiter = this.options.record_delimiter; - } - } - - var chr = buf[pos]; - - if (raw === true) { - rawBuffer.append(chr); - } - - if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) { - this.state.wasRowDelimiter = true; - } // Previous char was a valid escape char - // treat the current char as a regular char - - - if (this.state.escaping === true) { - this.state.escaping = false; - } else { - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) { - if (escapeIsQuote) { - if (this.__isQuote(buf, pos + escape.length)) { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } else { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - - - if (this.state.commenting === false && this.__isQuote(buf, pos)) { - if (this.state.quoting === true) { - var nextChr = buf[pos + quote.length]; - - var isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr); - - var isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr); - - var isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr); - - var isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length); // Escape a quote - // Treat next char as a regular character - - if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) { - pos += escape.length - 1; - } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) { - this.state.quoting = false; - this.state.wasQuoting = true; - pos += quote.length - 1; - continue; - } else if (relax === false) { - var err = this.__error(new CsvError('CSV_INVALID_CLOSING_QUOTE', ['Invalid Closing Quote:', "got \"".concat(String.fromCharCode(nextChr), "\""), "at line ".concat(this.info.lines), 'instead of delimiter, record delimiter, trimable character', '(if activated) or comment'], this.options, this.__infoField())); - - if (err !== undefined) return err; - } else { - this.state.quoting = false; - this.state.wasQuoting = true; - this.state.field.prepend(quote); - pos += quote.length - 1; - } - } else { - if (this.state.field.length !== 0) { - // In relax mode, treat opening quote preceded by chrs as regular - if (relax === false) { - var _err = this.__error(new CsvError('INVALID_OPENING_QUOTE', ['Invalid Opening Quote:', "a quote is found inside a field at line ".concat(this.info.lines)], this.options, this.__infoField(), { - field: this.state.field - })); - - if (_err !== undefined) return _err; - } - } else { - this.state.quoting = true; - pos += quote.length - 1; - continue; - } - } - } - - if (this.state.quoting === false) { - var recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); - - if (recordDelimiterLength !== 0) { - // Do not emit comments which take a full line - var skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0; - - if (skipCommentLine) { - this.info.comment_lines++; // Skip full comment line - } else { - // Activate records emition if above from_line - if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) { - this.state.enabled = true; - - this.__resetField(); - - this.__resetRecord(); - - pos += recordDelimiterLength - 1; - continue; - } // Skip if line is empty and skip_empty_lines activated - - - if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) { - this.info.empty_lines++; - pos += recordDelimiterLength - 1; - continue; - } - - this.info.bytes = this.state.bufBytesStart + pos; - - var errField = this.__onField(); - - if (errField !== undefined) return errField; - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - - var errRecord = this.__onRecord(); - - if (errRecord !== undefined) return errRecord; - - if (to !== -1 && this.info.records >= to) { - this.state.stop = true; - this.push(null); - return; - } - } - - this.state.commenting = false; - pos += recordDelimiterLength - 1; - continue; - } - - if (this.state.commenting) { - continue; - } - - var commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr); - - if (commentCount !== 0) { - this.state.commenting = true; - continue; - } - - var delimiterLength = this.__isDelimiter(buf, pos, chr); - - if (delimiterLength !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField = this.__onField(); - - if (_errField !== undefined) return _errField; - pos += delimiterLength - 1; - continue; - } - } - } - - if (this.state.commenting === false) { - if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) { - var _err2 = this.__error(new CsvError('CSV_MAX_RECORD_SIZE', ['Max Record Size:', 'record exceed the maximum number of tolerated bytes', "of ".concat(max_record_size), "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err2 !== undefined) return _err2; - } - } - - var lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr); // rtrim in non quoting is handle in __onField - - var rappend = rtrim === false || this.state.wasQuoting === false; - - if (lappend === true && rappend === true) { - this.state.field.append(chr); - } else if (rtrim === true && !this.__isCharTrimable(chr)) { - var _err3 = this.__error(new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', ['Invalid Closing Quote:', 'found non trimable byte after quote', "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err3 !== undefined) return _err3; - } - } - - if (end === true) { - // Ensure we are not ending in a quoting state - if (this.state.quoting === true) { - var _err4 = this.__error(new CsvError('CSV_QUOTE_NOT_CLOSED', ['Quote Not Closed:', "the parsing is finished with an opening quote at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err4 !== undefined) return _err4; - } else { - // Skip last line if it has no characters - if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField2 = this.__onField(); - - if (_errField2 !== undefined) return _errField2; - - var _errRecord = this.__onRecord(); - - if (_errRecord !== undefined) return _errRecord; - } else if (this.state.wasRowDelimiter === true) { - this.info.empty_lines++; - } else if (this.state.commenting === true) { - this.info.comment_lines++; - } - } - } else { - this.state.bufBytesStart += pos; - this.state.previousBuf = buf.slice(pos); - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - } - }, { - key: "__onRecord", - value: function __onRecord() { - var _this$options2 = this.options, - columns = _this$options2.columns, - columns_duplicates_to_array = _this$options2.columns_duplicates_to_array, - encoding = _this$options2.encoding, - info = _this$options2.info, - from = _this$options2.from, - relax_column_count = _this$options2.relax_column_count, - relax_column_count_less = _this$options2.relax_column_count_less, - relax_column_count_more = _this$options2.relax_column_count_more, - raw = _this$options2.raw, - skip_lines_with_empty_values = _this$options2.skip_lines_with_empty_values; - var _this$state2 = this.state, - enabled = _this$state2.enabled, - record = _this$state2.record; - - if (enabled === false) { - return this.__resetRecord(); - } // Convert the first line into column names - - - var recordLength = record.length; - - if (columns === true) { - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - return this.__firstLineToColumns(record); - } - - if (columns === false && this.info.records === 0) { - this.state.expectedRecordLength = recordLength; - } - - if (recordLength !== this.state.expectedRecordLength) { - var err = columns === false ? // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', ['Invalid Record Length:', "expect ".concat(this.state.expectedRecordLength, ","), "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }) : // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', ['Invalid Record Length:', "columns length is ".concat(columns.length, ","), // rename columns - "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }); - - if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) { - this.info.invalid_field_length++; - this.state.error = err; // Error is undefined with skip_lines_with_error - } else { - var finalErr = this.__error(err); - - if (finalErr) return finalErr; - } - } - - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - if (this.state.recordHasError === true) { - this.__resetRecord(); - - this.state.recordHasError = false; - return; - } - - this.info.records++; - - if (from === 1 || this.info.records >= from) { - // With columns, records are object - if (columns !== false) { - var obj = {}; // Transform record array to an object - - for (var i = 0, l = record.length; i < l; i++) { - if (columns[i] === undefined || columns[i].disabled) continue; // Turn duplicate columns into an array - - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]); - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]]; - } - } else { - obj[columns[i].name] = record[i]; - } - } - - var objname = this.options.objname; // Without objname (default) - - if (objname === undefined) { - if (raw === true || info === true) { - var _err5 = this.__push(Object.assign({ - record: obj - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err5) { - return _err5; - } - } else { - var _err6 = this.__push(obj); - - if (_err6) { - return _err6; - } - } // With objname (default) - - } else { - if (raw === true || info === true) { - var _err7 = this.__push(Object.assign({ - record: [obj[objname], obj] - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err7) { - return _err7; - } - } else { - var _err8 = this.__push([obj[objname], obj]); - - if (_err8) { - return _err8; - } - } - } // Without columns, records are array - - } else { - if (raw === true || info === true) { - var _err9 = this.__push(Object.assign({ - record: record - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err9) { - return _err9; - } - } else { - var _err10 = this.__push(record); - - if (_err10) { - return _err10; - } - } - } - } - - this.__resetRecord(); - } - }, { - key: "__firstLineToColumns", - value: function __firstLineToColumns(record) { - var firstLineToHeaders = this.state.firstLineToHeaders; - - try { - var headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); - - if (!Array.isArray(headers)) { - return this.__error(new CsvError('CSV_INVALID_COLUMN_MAPPING', ['Invalid Column Mapping:', 'expect an array from column function,', "got ".concat(JSON.stringify(headers))], this.options, this.__infoField(), { - headers: headers - })); - } - - var normalizedHeaders = normalizeColumnsArray(headers); - this.state.expectedRecordLength = normalizedHeaders.length; - this.options.columns = normalizedHeaders; - - this.__resetRecord(); - - return; - } catch (err) { - return err; - } - } - }, { - key: "__resetRecord", - value: function __resetRecord() { - if (this.options.raw === true) { - this.state.rawBuffer.reset(); - } - - this.state.error = undefined; - this.state.record = []; - this.state.record_length = 0; - } - }, { - key: "__onField", - value: function __onField() { - var _this$options3 = this.options, - cast = _this$options3.cast, - encoding = _this$options3.encoding, - rtrim = _this$options3.rtrim, - max_record_size = _this$options3.max_record_size; - var _this$state3 = this.state, - enabled = _this$state3.enabled, - wasQuoting = _this$state3.wasQuoting; // Short circuit for the from_line options - - if (enabled === false) { - return this.__resetField(); - } - - var field = this.state.field.toString(encoding); - - if (rtrim === true && wasQuoting === false) { - field = field.trimRight(); - } - - if (cast === true) { - var _this$__cast = this.__cast(field), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - f = _this$__cast2[1]; - - if (err !== undefined) return err; - field = f; - } - - this.state.record.push(field); // Increment record length if record size must not exceed a limit - - if (max_record_size !== 0 && typeof field === 'string') { - this.state.record_length += field.length; - } - - this.__resetField(); - } - }, { - key: "__resetField", - value: function __resetField() { - this.state.field.reset(); - this.state.wasQuoting = false; - } - }, { - key: "__push", - value: function __push(record) { - var on_record = this.options.on_record; - - if (on_record !== undefined) { - var info = this.__infoRecord(); - - try { - record = on_record.call(null, record, info); - } catch (err) { - return err; - } - - if (record === undefined || record === null) { - return; - } - } - - this.push(record); - } // Return a tuple with the error and the casted value - - }, { - key: "__cast", - value: function __cast(field) { - var _this$options4 = this.options, - columns = _this$options4.columns, - relax_column_count = _this$options4.relax_column_count; - var isColumns = Array.isArray(columns); // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - - if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) { - return [undefined, undefined]; - } - - if (this.state.castField !== null) { - try { - var info = this.__infoField(); - - return [undefined, this.state.castField.call(null, field, info)]; - } catch (err) { - return [err]; - } - } - - if (this.__isFloat(field)) { - return [undefined, parseFloat(field)]; - } else if (this.options.cast_date !== false) { - var _info = this.__infoField(); - - return [undefined, this.options.cast_date.call(null, field, _info)]; - } - - return [undefined, field]; - } // Helper to test if a character is a space or a line delimiter - - }, { - key: "__isCharTrimable", - value: function __isCharTrimable(chr) { - return chr === space || chr === tab || chr === cr || chr === nl || chr === np; - } // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - - }, { - key: "__isFloat", - value: function __isFloat(value) { - return value - parseFloat(value) + 1 >= 0; // Borrowed from jquery - } - }, { - key: "__compareBytes", - value: function __compareBytes(sourceBuf, targetBuf, targetPos, firstByte) { - if (sourceBuf[0] !== firstByte) return 0; - var sourceLength = sourceBuf.length; - - for (var i = 1; i < sourceLength; i++) { - if (sourceBuf[i] !== targetBuf[targetPos + i]) return 0; - } - - return sourceLength; - } - }, { - key: "__needMoreData", - value: function __needMoreData(i, bufLen, end) { - if (end) return false; - var quote = this.options.quote; - var _this$state4 = this.state, - quoting = _this$state4.quoting, - needMoreDataSize = _this$state4.needMoreDataSize, - recordDelimiterMaxLength = _this$state4.recordDelimiterMaxLength; - var numOfCharLeft = bufLen - i - 1; - var requiredLength = Math.max(needMoreDataSize, // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? quote.length + recordDelimiterMaxLength : 0); - return numOfCharLeft < requiredLength; - } - }, { - key: "__isDelimiter", - value: function __isDelimiter(buf, pos, chr) { - var _this$options5 = this.options, - delimiter = _this$options5.delimiter, - ignore_last_delimiters = _this$options5.ignore_last_delimiters; - - if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) { - return 0; - } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1) { - return 0; - } - - loop1: for (var i = 0; i < delimiter.length; i++) { - var del = delimiter[i]; - - if (del[0] === chr) { - for (var j = 1; j < del.length; j++) { - if (del[j] !== buf[pos + j]) continue loop1; - } - - return del.length; - } - } - - return 0; - } - }, { - key: "__isRecordDelimiter", - value: function __isRecordDelimiter(chr, buf, pos) { - var record_delimiter = this.options.record_delimiter; - var recordDelimiterLength = record_delimiter.length; - - loop1: for (var i = 0; i < recordDelimiterLength; i++) { - var rd = record_delimiter[i]; - var rdLength = rd.length; - - if (rd[0] !== chr) { - continue; - } - - for (var j = 1; j < rdLength; j++) { - if (rd[j] !== buf[pos + j]) { - continue loop1; - } - } - - return rd.length; - } - - return 0; - } - }, { - key: "__isEscape", - value: function __isEscape(buf, pos, chr) { - var escape = this.options.escape; - if (escape === null) return false; - var l = escape.length; - - if (escape[0] === chr) { - for (var i = 0; i < l; i++) { - if (escape[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - - return false; - } - }, { - key: "__isQuote", - value: function __isQuote(buf, pos) { - var quote = this.options.quote; - if (quote === null) return false; - var l = quote.length; - - for (var i = 0; i < l; i++) { - if (quote[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - }, { - key: "__autoDiscoverRecordDelimiter", - value: function __autoDiscoverRecordDelimiter(buf, pos) { - var encoding = this.options.encoding; - var chr = buf[pos]; - - if (chr === cr) { - if (buf[pos + 1] === nl) { - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)); - this.state.recordDelimiterMaxLength = 2; - return 2; - } else { - this.options.record_delimiter.push(Buffer.from('\r', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - } else if (chr === nl) { - this.options.record_delimiter.push(Buffer.from('\n', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - - return 0; - } - }, { - key: "__error", - value: function __error(msg) { - var skip_lines_with_error = this.options.skip_lines_with_error; - var err = typeof msg === 'string' ? new Error(msg) : msg; - - if (skip_lines_with_error) { - this.state.recordHasError = true; - this.emit('skip', err); - return undefined; - } else { - return err; - } - } - }, { - key: "__infoDataSet", - value: function __infoDataSet() { - return _objectSpread(_objectSpread({}, this.info), {}, { - columns: this.options.columns - }); - } - }, { - key: "__infoRecord", - value: function __infoRecord() { - var columns = this.options.columns; - return _objectSpread(_objectSpread({}, this.__infoDataSet()), {}, { - error: this.state.error, - header: columns === true, - index: this.state.record.length - }); - } - }, { - key: "__infoField", - value: function __infoField() { - var columns = this.options.columns; - var isColumns = Array.isArray(columns); - return _objectSpread(_objectSpread({}, this.__infoRecord()), {}, { - column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length, - quoting: this.state.wasQuoting - }); - } - }]); - - return Parser; -}(Transform); - -var parse = function parse() { - var data, options, callback; - - for (var i in arguments) { - var argument = arguments[i]; - - var type = _typeof(argument); - - if (data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(i)], options || {}); - } - } - - var parser = new Parser(options); - - if (callback) { - var records = options === undefined || options.objname === undefined ? [] : {}; - parser.on('readable', function () { - var record; - - while ((record = this.read()) !== null) { - if (options === undefined || options.objname === undefined) { - records.push(record); - } else { - records[record[0]] = record[1]; - } - } - }); - parser.on('error', function (err) { - callback(err, undefined, parser.__infoDataSet()); - }); - parser.on('end', function () { - callback(undefined, records, parser.__infoDataSet()); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - parser.write(data); - parser.end(); - }); - } else { - parser.write(data); - parser.end(); - } - } - - return parser; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message, options) { - var _this2; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this2 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this2), CsvError); - } - - _this2.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { - contexts[_key - 3] = arguments[_key]; - } - - for (var _i2 = 0, _contexts = contexts; _i2 < _contexts.length; _i2++) { - var context = _contexts[_i2]; - - for (var key in context) { - var value = context[key]; - _this2[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this2; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -parse.Parser = Parser; -parse.CsvError = CsvError; -module.exports = parse; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var isRecordEmpty = function isRecordEmpty(record) { - return record.every(function (field) { - return field == null || field.toString && field.toString().trim() === ''; - }); -}; - -var normalizeColumnsArray = function normalizeColumnsArray(columns) { - var normalizedColumns = []; - - for (var i = 0, l = columns.length; i < l; i++) { - var column = columns[i]; - - if (column === undefined || column === null || column === false) { - normalizedColumns[i] = { - disabled: true - }; - } else if (typeof column === 'string') { - normalizedColumns[i] = { - name: column - }; - } else if (isObject(column)) { - if (typeof column.name !== 'string') { - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', ['Option columns missing name:', "property \"name\" is required at position ".concat(i), 'when column is an object literal']); - } - - normalizedColumns[i] = column; - } else { - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', ['Invalid column definition:', 'expect a string or a literal object,', "got ".concat(JSON.stringify(column), " at position ").concat(i)]); - } - } - - return normalizedColumns; -}; - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"./ResizeableBuffer":1,"buffer":5,"stream":11,"timers":27}],3:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],4:[function(require,module,exports){ - -},{}],5:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":3,"buffer":5,"ieee754":7}],6:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],7:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],8:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],9:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],10:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":5}],11:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":6,"inherits":8,"readable-stream/lib/_stream_duplex.js":13,"readable-stream/lib/_stream_passthrough.js":14,"readable-stream/lib/_stream_readable.js":15,"readable-stream/lib/_stream_transform.js":16,"readable-stream/lib/_stream_writable.js":17,"readable-stream/lib/internal/streams/end-of-stream.js":21,"readable-stream/lib/internal/streams/pipeline.js":23}],12:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],13:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":15,"./_stream_writable":17,"_process":9,"inherits":8}],14:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":16,"inherits":8}],15:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":12,"./_stream_duplex":13,"./internal/streams/async_iterator":18,"./internal/streams/buffer_list":19,"./internal/streams/destroy":20,"./internal/streams/from":22,"./internal/streams/state":24,"./internal/streams/stream":25,"_process":9,"buffer":5,"events":6,"inherits":8,"string_decoder/":26,"util":4}],16:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":12,"./_stream_duplex":13,"inherits":8}],17:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":12,"./_stream_duplex":13,"./internal/streams/destroy":20,"./internal/streams/state":24,"./internal/streams/stream":25,"_process":9,"buffer":5,"inherits":8,"util-deprecate":28}],18:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":21,"_process":9}],19:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":5,"util":4}],20:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":9}],21:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":12}],22:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],23:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":12,"./end-of-stream":21}],24:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":12}],25:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":6}],26:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":10}],27:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":9,"timers":27}],28:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[2])(2) -}); diff --git a/node_modules/csv-parse/lib/browser/sync.js b/node_modules/csv-parse/lib/browser/sync.js deleted file mode 100644 index 9fa8e1c..0000000 --- a/node_modules/csv-parse/lib/browser/sync.js +++ /dev/null @@ -1,8168 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i 0 && arguments[0] !== undefined ? arguments[0] : 100; - - _classCallCheck(this, ResizeableBuffer); - - this.size = size; - this.length = 0; - this.buf = Buffer.alloc(size); - } - - _createClass(ResizeableBuffer, [{ - key: "prepend", - value: function prepend(val) { - if (Buffer.isBuffer(val)) { - var length = this.length + val.length; - - if (length >= this.size) { - this.resize(); - - if (length >= this.size) { - throw Error('INVALID_BUFFER_STATE'); - } - } - - var buf = this.buf; - this.buf = Buffer.alloc(this.size); - val.copy(this.buf, 0); - buf.copy(this.buf, val.length); - this.length += val.length; - } else { - var _length = this.length++; - - if (_length === this.size) { - this.resize(); - } - - var _buf = this.clone(); - - this.buf[0] = val; - - _buf.copy(this.buf, 1, 0, _length); - } - } - }, { - key: "append", - value: function append(val) { - var length = this.length++; - - if (length === this.size) { - this.resize(); - } - - this.buf[length] = val; - } - }, { - key: "clone", - value: function clone() { - return Buffer.from(this.buf.slice(0, this.length)); - } - }, { - key: "resize", - value: function resize() { - var length = this.length; - this.size = this.size * 2; - var buf = Buffer.alloc(this.size); - this.buf.copy(buf, 0, 0, length); - this.buf = buf; - } - }, { - key: "toString", - value: function toString(encoding) { - if (encoding) { - return this.buf.slice(0, this.length).toString(encoding); - } else { - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); - } - } - }, { - key: "toJSON", - value: function toJSON() { - return this.toString('utf8'); - } - }, { - key: "reset", - value: function reset() { - this.length = 0; - } - }]); - - return ResizeableBuffer; -}(); - -module.exports = ResizeableBuffer; - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":6}],2:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ -"use strict"; - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Parse - -Please look at the [project documentation](https://csv.js.org/parse/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var ResizeableBuffer = require('./ResizeableBuffer'); // white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff - - -var tab = 9; -var nl = 10; // \n, 0x0A in hexadecimal, 10 in decimal - -var np = 12; -var cr = 13; // \r, 0x0D in hexadécimal, 13 in decimal - -var space = 32; -var boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -}; - -var Parser = /*#__PURE__*/function (_Transform) { - _inherits(Parser, _Transform); - - var _super = _createSuper(Parser); - - function Parser() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Parser); - - _this = _super.call(this, _objectSpread(_objectSpread(_objectSpread({}, { - readableObjectMode: true - }), opts), {}, { - encoding: null - })); - _this.__originalOptions = opts; - - _this.__normalizeOptions(opts); - - return _this; - } - - _createClass(Parser, [{ - key: "__normalizeOptions", - value: function __normalizeOptions(opts) { - var options = {}; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - - - if (options.encoding === undefined || options.encoding === true) { - options.encoding = 'utf8'; - } else if (options.encoding === null || options.encoding === false) { - options.encoding = null; - } else if (typeof options.encoding !== 'string' && options.encoding !== null) { - throw new CsvError('CSV_INVALID_OPTION_ENCODING', ['Invalid option encoding:', 'encoding must be a string or null to return a buffer,', "got ".concat(JSON.stringify(options.encoding))], options); - } // Normalize option `bom` - - - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - throw new CsvError('CSV_INVALID_OPTION_BOM', ['Invalid option bom:', 'bom must be true,', "got ".concat(JSON.stringify(options.bom))], options); - } // Normalize option `cast` - - - var fnCastField = null; - - if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === '') { - options.cast = undefined; - } else if (typeof options.cast === 'function') { - fnCastField = options.cast; - options.cast = true; - } else if (options.cast !== true) { - throw new CsvError('CSV_INVALID_OPTION_CAST', ['Invalid option cast:', 'cast must be true or a function,', "got ".concat(JSON.stringify(options.cast))], options); - } // Normalize option `cast_date` - - - if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === '') { - options.cast_date = false; - } else if (options.cast_date === true) { - options.cast_date = function (value) { - var date = Date.parse(value); - return !isNaN(date) ? new Date(date) : value; - }; - } else { - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', ['Invalid option cast_date:', 'cast_date must be true or a function,', "got ".concat(JSON.stringify(options.cast_date))], options); - } // Normalize option `columns` - - - var fnFirstLineToHeaders = null; - - if (options.columns === true) { - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined; - } else if (typeof options.columns === 'function') { - fnFirstLineToHeaders = options.columns; - options.columns = true; - } else if (Array.isArray(options.columns)) { - options.columns = normalizeColumnsArray(options.columns); - } else if (options.columns === undefined || options.columns === null || options.columns === false) { - options.columns = false; - } else { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', ['Invalid option columns:', 'expect an array, a function or true,', "got ".concat(JSON.stringify(options.columns))], options); - } // Normalize option `columns_duplicates_to_array` - - - if (options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false) { - options.columns_duplicates_to_array = false; - } else if (options.columns_duplicates_to_array !== true) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'expect an boolean,', "got ".concat(JSON.stringify(options.columns_duplicates_to_array))], options); - } else if (options.columns === false) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'the `columns` mode must be activated.'], options); - } // Normalize option `comment` - - - if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === '') { - options.comment = null; - } else { - if (typeof options.comment === 'string') { - options.comment = Buffer.from(options.comment, options.encoding); - } - - if (!Buffer.isBuffer(options.comment)) { - throw new CsvError('CSV_INVALID_OPTION_COMMENT', ['Invalid option comment:', 'comment must be a buffer or a string,', "got ".concat(JSON.stringify(options.comment))], options); - } - } // Normalize option `delimiter` - - - var delimiter_json = JSON.stringify(options.delimiter); - if (!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; - - if (options.delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - options.delimiter = options.delimiter.map(function (delimiter) { - if (delimiter === undefined || delimiter === null || delimiter === false) { - return Buffer.from(',', options.encoding); - } - - if (typeof delimiter === 'string') { - delimiter = Buffer.from(delimiter, options.encoding); - } - - if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - return delimiter; - }); // Normalize option `escape` - - if (options.escape === undefined || options.escape === true) { - options.escape = Buffer.from('"', options.encoding); - } else if (typeof options.escape === 'string') { - options.escape = Buffer.from(options.escape, options.encoding); - } else if (options.escape === null || options.escape === false) { - options.escape = null; - } - - if (options.escape !== null) { - if (!Buffer.isBuffer(options.escape)) { - throw new Error("Invalid Option: escape must be a buffer, a string or a boolean, got ".concat(JSON.stringify(options.escape))); - } - } // Normalize option `from` - - - if (options.from === undefined || options.from === null) { - options.from = 1; - } else { - if (typeof options.from === 'string' && /\d+/.test(options.from)) { - options.from = parseInt(options.from); - } - - if (Number.isInteger(options.from)) { - if (options.from < 0) { - throw new Error("Invalid Option: from must be a positive integer, got ".concat(JSON.stringify(opts.from))); - } - } else { - throw new Error("Invalid Option: from must be an integer, got ".concat(JSON.stringify(options.from))); - } - } // Normalize option `from_line` - - - if (options.from_line === undefined || options.from_line === null) { - options.from_line = 1; - } else { - if (typeof options.from_line === 'string' && /\d+/.test(options.from_line)) { - options.from_line = parseInt(options.from_line); - } - - if (Number.isInteger(options.from_line)) { - if (options.from_line <= 0) { - throw new Error("Invalid Option: from_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.from_line))); - } - } else { - throw new Error("Invalid Option: from_line must be an integer, got ".concat(JSON.stringify(opts.from_line))); - } - } // Normalize options `ignore_last_delimiters` - - - if (options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null) { - options.ignore_last_delimiters = false; - } else if (typeof options.ignore_last_delimiters === 'number') { - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); - - if (options.ignore_last_delimiters === 0) { - options.ignore_last_delimiters = false; - } - } else if (typeof options.ignore_last_delimiters !== 'boolean') { - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', ['Invalid option `ignore_last_delimiters`:', 'the value must be a boolean value or an integer,', "got ".concat(JSON.stringify(options.ignore_last_delimiters))], options); - } - - if (options.ignore_last_delimiters === true && options.columns === false) { - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', ['The option `ignore_last_delimiters`', 'requires the activation of the `columns` option'], options); - } // Normalize option `info` - - - if (options.info === undefined || options.info === null || options.info === false) { - options.info = false; - } else if (options.info !== true) { - throw new Error("Invalid Option: info must be true, got ".concat(JSON.stringify(options.info))); - } // Normalize option `max_record_size` - - - if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) { - options.max_record_size = 0; - } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {// Great, nothing to do - } else if (typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)) { - options.max_record_size = parseInt(options.max_record_size); - } else { - throw new Error("Invalid Option: max_record_size must be a positive integer, got ".concat(JSON.stringify(options.max_record_size))); - } // Normalize option `objname` - - - if (options.objname === undefined || options.objname === null || options.objname === false) { - options.objname = undefined; - } else if (Buffer.isBuffer(options.objname)) { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty buffer"); - } - - if (options.encoding === null) {// Don't call `toString`, leave objname as a buffer - } else { - options.objname = options.objname.toString(options.encoding); - } - } else if (typeof options.objname === 'string') { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty string"); - } // Great, nothing to do - - } else { - throw new Error("Invalid Option: objname must be a string or a buffer, got ".concat(options.objname)); - } // Normalize option `on_record` - - - if (options.on_record === undefined || options.on_record === null) { - options.on_record = undefined; - } else if (typeof options.on_record !== 'function') { - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', ['Invalid option `on_record`:', 'expect a function,', "got ".concat(JSON.stringify(options.on_record))], options); - } // Normalize option `quote` - - - if (options.quote === null || options.quote === false || options.quote === '') { - options.quote = null; - } else { - if (options.quote === undefined || options.quote === true) { - options.quote = Buffer.from('"', options.encoding); - } else if (typeof options.quote === 'string') { - options.quote = Buffer.from(options.quote, options.encoding); - } - - if (!Buffer.isBuffer(options.quote)) { - throw new Error("Invalid Option: quote must be a buffer or a string, got ".concat(JSON.stringify(options.quote))); - } - } // Normalize option `raw` - - - if (options.raw === undefined || options.raw === null || options.raw === false) { - options.raw = false; - } else if (options.raw !== true) { - throw new Error("Invalid Option: raw must be true, got ".concat(JSON.stringify(options.raw))); - } // Normalize option `record_delimiter` - - - if (!options.record_delimiter) { - options.record_delimiter = []; - } else if (!Array.isArray(options.record_delimiter)) { - options.record_delimiter = [options.record_delimiter]; - } - - options.record_delimiter = options.record_delimiter.map(function (rd) { - if (typeof rd === 'string') { - rd = Buffer.from(rd, options.encoding); - } - - return rd; - }); // Normalize option `relax` - - if (typeof options.relax === 'boolean') {// Great, nothing to do - } else if (options.relax === undefined || options.relax === null) { - options.relax = false; - } else { - throw new Error("Invalid Option: relax must be a boolean, got ".concat(JSON.stringify(options.relax))); - } // Normalize option `relax_column_count` - - - if (typeof options.relax_column_count === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count === undefined || options.relax_column_count === null) { - options.relax_column_count = false; - } else { - throw new Error("Invalid Option: relax_column_count must be a boolean, got ".concat(JSON.stringify(options.relax_column_count))); - } - - if (typeof options.relax_column_count_less === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) { - options.relax_column_count_less = false; - } else { - throw new Error("Invalid Option: relax_column_count_less must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_less))); - } - - if (typeof options.relax_column_count_more === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) { - options.relax_column_count_more = false; - } else { - throw new Error("Invalid Option: relax_column_count_more must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_more))); - } // Normalize option `skip_empty_lines` - - - if (typeof options.skip_empty_lines === 'boolean') {// Great, nothing to do - } else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) { - options.skip_empty_lines = false; - } else { - throw new Error("Invalid Option: skip_empty_lines must be a boolean, got ".concat(JSON.stringify(options.skip_empty_lines))); - } // Normalize option `skip_lines_with_empty_values` - - - if (typeof options.skip_lines_with_empty_values === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null) { - options.skip_lines_with_empty_values = false; - } else { - throw new Error("Invalid Option: skip_lines_with_empty_values must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_empty_values))); - } // Normalize option `skip_lines_with_error` - - - if (typeof options.skip_lines_with_error === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_error === undefined || options.skip_lines_with_error === null) { - options.skip_lines_with_error = false; - } else { - throw new Error("Invalid Option: skip_lines_with_error must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_error))); - } // Normalize option `rtrim` - - - if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) { - options.rtrim = false; - } else if (options.rtrim !== true) { - throw new Error("Invalid Option: rtrim must be a boolean, got ".concat(JSON.stringify(options.rtrim))); - } // Normalize option `ltrim` - - - if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) { - options.ltrim = false; - } else if (options.ltrim !== true) { - throw new Error("Invalid Option: ltrim must be a boolean, got ".concat(JSON.stringify(options.ltrim))); - } // Normalize option `trim` - - - if (options.trim === undefined || options.trim === null || options.trim === false) { - options.trim = false; - } else if (options.trim !== true) { - throw new Error("Invalid Option: trim must be a boolean, got ".concat(JSON.stringify(options.trim))); - } // Normalize options `trim`, `ltrim` and `rtrim` - - - if (options.trim === true && opts.ltrim !== false) { - options.ltrim = true; - } else if (options.ltrim !== true) { - options.ltrim = false; - } - - if (options.trim === true && opts.rtrim !== false) { - options.rtrim = true; - } else if (options.rtrim !== true) { - options.rtrim = false; - } // Normalize option `to` - - - if (options.to === undefined || options.to === null) { - options.to = -1; - } else { - if (typeof options.to === 'string' && /\d+/.test(options.to)) { - options.to = parseInt(options.to); - } - - if (Number.isInteger(options.to)) { - if (options.to <= 0) { - throw new Error("Invalid Option: to must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to))); - } - } else { - throw new Error("Invalid Option: to must be an integer, got ".concat(JSON.stringify(opts.to))); - } - } // Normalize option `to_line` - - - if (options.to_line === undefined || options.to_line === null) { - options.to_line = -1; - } else { - if (typeof options.to_line === 'string' && /\d+/.test(options.to_line)) { - options.to_line = parseInt(options.to_line); - } - - if (Number.isInteger(options.to_line)) { - if (options.to_line <= 0) { - throw new Error("Invalid Option: to_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to_line))); - } - } else { - throw new Error("Invalid Option: to_line must be an integer, got ".concat(JSON.stringify(opts.to_line))); - } - } - - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - }; - this.options = options; - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max.apply(Math, [// Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0].concat(_toConsumableArray(options.delimiter.map(function (delimiter) { - return delimiter.length; - })), [// Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0])), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max.apply(Math, _toConsumableArray(options.record_delimiter.map(function (v) { - return v.length; - }))), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - }; - } // Implementation of `Transform._transform` - - }, { - key: "_transform", - value: function _transform(buf, encoding, callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(buf, false); - - if (err !== undefined) { - this.state.stop = true; - } - - callback(err); - } // Implementation of `Transform._flush` - - }, { - key: "_flush", - value: function _flush(callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(undefined, true); - - callback(err); - } // Central parser implementation - - }, { - key: "__parse", - value: function __parse(nextBuf, end) { - var _this$options = this.options, - bom = _this$options.bom, - comment = _this$options.comment, - escape = _this$options.escape, - from_line = _this$options.from_line, - ltrim = _this$options.ltrim, - max_record_size = _this$options.max_record_size, - quote = _this$options.quote, - raw = _this$options.raw, - relax = _this$options.relax, - rtrim = _this$options.rtrim, - skip_empty_lines = _this$options.skip_empty_lines, - to = _this$options.to, - to_line = _this$options.to_line; - var record_delimiter = this.options.record_delimiter; - var _this$state = this.state, - bomSkipped = _this$state.bomSkipped, - previousBuf = _this$state.previousBuf, - rawBuffer = _this$state.rawBuffer, - escapeIsQuote = _this$state.escapeIsQuote; - var buf; - - if (previousBuf === undefined) { - if (nextBuf === undefined) { - // Handle empty string - this.push(null); - return; - } else { - buf = nextBuf; - } - } else if (previousBuf !== undefined && nextBuf === undefined) { - buf = previousBuf; - } else { - buf = Buffer.concat([previousBuf, nextBuf]); - } // Handle UTF BOM - - - if (bomSkipped === false) { - if (bom === false) { - this.state.bomSkipped = true; - } else if (buf.length < 3) { - // No enough data - if (end === false) { - // Wait for more data - this.state.previousBuf = buf; - return; - } - } else { - for (var encoding in boms) { - if (boms[encoding].compare(buf, 0, boms[encoding].length) === 0) { - // Skip BOM - var bomLength = boms[encoding].length; - this.state.bufBytesStart += bomLength; - buf = buf.slice(bomLength); // Renormalize original options with the new encoding - - this.__normalizeOptions(_objectSpread(_objectSpread({}, this.__originalOptions), {}, { - encoding: encoding - })); - - break; - } - } - - this.state.bomSkipped = true; - } - } - - var bufLen = buf.length; - var pos; - - for (pos = 0; pos < bufLen; pos++) { - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if (this.__needMoreData(pos, bufLen, end)) { - break; - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - - if (to_line !== -1 && this.info.lines > to_line) { - this.state.stop = true; - this.push(null); - return; - } // Auto discovery of record_delimiter, unix, mac and windows supported - - - if (this.state.quoting === false && record_delimiter.length === 0) { - var record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); - - if (record_delimiterCount) { - record_delimiter = this.options.record_delimiter; - } - } - - var chr = buf[pos]; - - if (raw === true) { - rawBuffer.append(chr); - } - - if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) { - this.state.wasRowDelimiter = true; - } // Previous char was a valid escape char - // treat the current char as a regular char - - - if (this.state.escaping === true) { - this.state.escaping = false; - } else { - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) { - if (escapeIsQuote) { - if (this.__isQuote(buf, pos + escape.length)) { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } else { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - - - if (this.state.commenting === false && this.__isQuote(buf, pos)) { - if (this.state.quoting === true) { - var nextChr = buf[pos + quote.length]; - - var isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr); - - var isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr); - - var isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr); - - var isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length); // Escape a quote - // Treat next char as a regular character - - if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) { - pos += escape.length - 1; - } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) { - this.state.quoting = false; - this.state.wasQuoting = true; - pos += quote.length - 1; - continue; - } else if (relax === false) { - var err = this.__error(new CsvError('CSV_INVALID_CLOSING_QUOTE', ['Invalid Closing Quote:', "got \"".concat(String.fromCharCode(nextChr), "\""), "at line ".concat(this.info.lines), 'instead of delimiter, record delimiter, trimable character', '(if activated) or comment'], this.options, this.__infoField())); - - if (err !== undefined) return err; - } else { - this.state.quoting = false; - this.state.wasQuoting = true; - this.state.field.prepend(quote); - pos += quote.length - 1; - } - } else { - if (this.state.field.length !== 0) { - // In relax mode, treat opening quote preceded by chrs as regular - if (relax === false) { - var _err = this.__error(new CsvError('INVALID_OPENING_QUOTE', ['Invalid Opening Quote:', "a quote is found inside a field at line ".concat(this.info.lines)], this.options, this.__infoField(), { - field: this.state.field - })); - - if (_err !== undefined) return _err; - } - } else { - this.state.quoting = true; - pos += quote.length - 1; - continue; - } - } - } - - if (this.state.quoting === false) { - var recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); - - if (recordDelimiterLength !== 0) { - // Do not emit comments which take a full line - var skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0; - - if (skipCommentLine) { - this.info.comment_lines++; // Skip full comment line - } else { - // Activate records emition if above from_line - if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) { - this.state.enabled = true; - - this.__resetField(); - - this.__resetRecord(); - - pos += recordDelimiterLength - 1; - continue; - } // Skip if line is empty and skip_empty_lines activated - - - if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) { - this.info.empty_lines++; - pos += recordDelimiterLength - 1; - continue; - } - - this.info.bytes = this.state.bufBytesStart + pos; - - var errField = this.__onField(); - - if (errField !== undefined) return errField; - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - - var errRecord = this.__onRecord(); - - if (errRecord !== undefined) return errRecord; - - if (to !== -1 && this.info.records >= to) { - this.state.stop = true; - this.push(null); - return; - } - } - - this.state.commenting = false; - pos += recordDelimiterLength - 1; - continue; - } - - if (this.state.commenting) { - continue; - } - - var commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr); - - if (commentCount !== 0) { - this.state.commenting = true; - continue; - } - - var delimiterLength = this.__isDelimiter(buf, pos, chr); - - if (delimiterLength !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField = this.__onField(); - - if (_errField !== undefined) return _errField; - pos += delimiterLength - 1; - continue; - } - } - } - - if (this.state.commenting === false) { - if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) { - var _err2 = this.__error(new CsvError('CSV_MAX_RECORD_SIZE', ['Max Record Size:', 'record exceed the maximum number of tolerated bytes', "of ".concat(max_record_size), "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err2 !== undefined) return _err2; - } - } - - var lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr); // rtrim in non quoting is handle in __onField - - var rappend = rtrim === false || this.state.wasQuoting === false; - - if (lappend === true && rappend === true) { - this.state.field.append(chr); - } else if (rtrim === true && !this.__isCharTrimable(chr)) { - var _err3 = this.__error(new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', ['Invalid Closing Quote:', 'found non trimable byte after quote', "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err3 !== undefined) return _err3; - } - } - - if (end === true) { - // Ensure we are not ending in a quoting state - if (this.state.quoting === true) { - var _err4 = this.__error(new CsvError('CSV_QUOTE_NOT_CLOSED', ['Quote Not Closed:', "the parsing is finished with an opening quote at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err4 !== undefined) return _err4; - } else { - // Skip last line if it has no characters - if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField2 = this.__onField(); - - if (_errField2 !== undefined) return _errField2; - - var _errRecord = this.__onRecord(); - - if (_errRecord !== undefined) return _errRecord; - } else if (this.state.wasRowDelimiter === true) { - this.info.empty_lines++; - } else if (this.state.commenting === true) { - this.info.comment_lines++; - } - } - } else { - this.state.bufBytesStart += pos; - this.state.previousBuf = buf.slice(pos); - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - } - }, { - key: "__onRecord", - value: function __onRecord() { - var _this$options2 = this.options, - columns = _this$options2.columns, - columns_duplicates_to_array = _this$options2.columns_duplicates_to_array, - encoding = _this$options2.encoding, - info = _this$options2.info, - from = _this$options2.from, - relax_column_count = _this$options2.relax_column_count, - relax_column_count_less = _this$options2.relax_column_count_less, - relax_column_count_more = _this$options2.relax_column_count_more, - raw = _this$options2.raw, - skip_lines_with_empty_values = _this$options2.skip_lines_with_empty_values; - var _this$state2 = this.state, - enabled = _this$state2.enabled, - record = _this$state2.record; - - if (enabled === false) { - return this.__resetRecord(); - } // Convert the first line into column names - - - var recordLength = record.length; - - if (columns === true) { - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - return this.__firstLineToColumns(record); - } - - if (columns === false && this.info.records === 0) { - this.state.expectedRecordLength = recordLength; - } - - if (recordLength !== this.state.expectedRecordLength) { - var err = columns === false ? // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', ['Invalid Record Length:', "expect ".concat(this.state.expectedRecordLength, ","), "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }) : // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', ['Invalid Record Length:', "columns length is ".concat(columns.length, ","), // rename columns - "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }); - - if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) { - this.info.invalid_field_length++; - this.state.error = err; // Error is undefined with skip_lines_with_error - } else { - var finalErr = this.__error(err); - - if (finalErr) return finalErr; - } - } - - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - if (this.state.recordHasError === true) { - this.__resetRecord(); - - this.state.recordHasError = false; - return; - } - - this.info.records++; - - if (from === 1 || this.info.records >= from) { - // With columns, records are object - if (columns !== false) { - var obj = {}; // Transform record array to an object - - for (var i = 0, l = record.length; i < l; i++) { - if (columns[i] === undefined || columns[i].disabled) continue; // Turn duplicate columns into an array - - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]); - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]]; - } - } else { - obj[columns[i].name] = record[i]; - } - } - - var objname = this.options.objname; // Without objname (default) - - if (objname === undefined) { - if (raw === true || info === true) { - var _err5 = this.__push(Object.assign({ - record: obj - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err5) { - return _err5; - } - } else { - var _err6 = this.__push(obj); - - if (_err6) { - return _err6; - } - } // With objname (default) - - } else { - if (raw === true || info === true) { - var _err7 = this.__push(Object.assign({ - record: [obj[objname], obj] - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err7) { - return _err7; - } - } else { - var _err8 = this.__push([obj[objname], obj]); - - if (_err8) { - return _err8; - } - } - } // Without columns, records are array - - } else { - if (raw === true || info === true) { - var _err9 = this.__push(Object.assign({ - record: record - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err9) { - return _err9; - } - } else { - var _err10 = this.__push(record); - - if (_err10) { - return _err10; - } - } - } - } - - this.__resetRecord(); - } - }, { - key: "__firstLineToColumns", - value: function __firstLineToColumns(record) { - var firstLineToHeaders = this.state.firstLineToHeaders; - - try { - var headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); - - if (!Array.isArray(headers)) { - return this.__error(new CsvError('CSV_INVALID_COLUMN_MAPPING', ['Invalid Column Mapping:', 'expect an array from column function,', "got ".concat(JSON.stringify(headers))], this.options, this.__infoField(), { - headers: headers - })); - } - - var normalizedHeaders = normalizeColumnsArray(headers); - this.state.expectedRecordLength = normalizedHeaders.length; - this.options.columns = normalizedHeaders; - - this.__resetRecord(); - - return; - } catch (err) { - return err; - } - } - }, { - key: "__resetRecord", - value: function __resetRecord() { - if (this.options.raw === true) { - this.state.rawBuffer.reset(); - } - - this.state.error = undefined; - this.state.record = []; - this.state.record_length = 0; - } - }, { - key: "__onField", - value: function __onField() { - var _this$options3 = this.options, - cast = _this$options3.cast, - encoding = _this$options3.encoding, - rtrim = _this$options3.rtrim, - max_record_size = _this$options3.max_record_size; - var _this$state3 = this.state, - enabled = _this$state3.enabled, - wasQuoting = _this$state3.wasQuoting; // Short circuit for the from_line options - - if (enabled === false) { - return this.__resetField(); - } - - var field = this.state.field.toString(encoding); - - if (rtrim === true && wasQuoting === false) { - field = field.trimRight(); - } - - if (cast === true) { - var _this$__cast = this.__cast(field), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - f = _this$__cast2[1]; - - if (err !== undefined) return err; - field = f; - } - - this.state.record.push(field); // Increment record length if record size must not exceed a limit - - if (max_record_size !== 0 && typeof field === 'string') { - this.state.record_length += field.length; - } - - this.__resetField(); - } - }, { - key: "__resetField", - value: function __resetField() { - this.state.field.reset(); - this.state.wasQuoting = false; - } - }, { - key: "__push", - value: function __push(record) { - var on_record = this.options.on_record; - - if (on_record !== undefined) { - var info = this.__infoRecord(); - - try { - record = on_record.call(null, record, info); - } catch (err) { - return err; - } - - if (record === undefined || record === null) { - return; - } - } - - this.push(record); - } // Return a tuple with the error and the casted value - - }, { - key: "__cast", - value: function __cast(field) { - var _this$options4 = this.options, - columns = _this$options4.columns, - relax_column_count = _this$options4.relax_column_count; - var isColumns = Array.isArray(columns); // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - - if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) { - return [undefined, undefined]; - } - - if (this.state.castField !== null) { - try { - var info = this.__infoField(); - - return [undefined, this.state.castField.call(null, field, info)]; - } catch (err) { - return [err]; - } - } - - if (this.__isFloat(field)) { - return [undefined, parseFloat(field)]; - } else if (this.options.cast_date !== false) { - var _info = this.__infoField(); - - return [undefined, this.options.cast_date.call(null, field, _info)]; - } - - return [undefined, field]; - } // Helper to test if a character is a space or a line delimiter - - }, { - key: "__isCharTrimable", - value: function __isCharTrimable(chr) { - return chr === space || chr === tab || chr === cr || chr === nl || chr === np; - } // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - - }, { - key: "__isFloat", - value: function __isFloat(value) { - return value - parseFloat(value) + 1 >= 0; // Borrowed from jquery - } - }, { - key: "__compareBytes", - value: function __compareBytes(sourceBuf, targetBuf, targetPos, firstByte) { - if (sourceBuf[0] !== firstByte) return 0; - var sourceLength = sourceBuf.length; - - for (var i = 1; i < sourceLength; i++) { - if (sourceBuf[i] !== targetBuf[targetPos + i]) return 0; - } - - return sourceLength; - } - }, { - key: "__needMoreData", - value: function __needMoreData(i, bufLen, end) { - if (end) return false; - var quote = this.options.quote; - var _this$state4 = this.state, - quoting = _this$state4.quoting, - needMoreDataSize = _this$state4.needMoreDataSize, - recordDelimiterMaxLength = _this$state4.recordDelimiterMaxLength; - var numOfCharLeft = bufLen - i - 1; - var requiredLength = Math.max(needMoreDataSize, // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? quote.length + recordDelimiterMaxLength : 0); - return numOfCharLeft < requiredLength; - } - }, { - key: "__isDelimiter", - value: function __isDelimiter(buf, pos, chr) { - var _this$options5 = this.options, - delimiter = _this$options5.delimiter, - ignore_last_delimiters = _this$options5.ignore_last_delimiters; - - if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) { - return 0; - } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1) { - return 0; - } - - loop1: for (var i = 0; i < delimiter.length; i++) { - var del = delimiter[i]; - - if (del[0] === chr) { - for (var j = 1; j < del.length; j++) { - if (del[j] !== buf[pos + j]) continue loop1; - } - - return del.length; - } - } - - return 0; - } - }, { - key: "__isRecordDelimiter", - value: function __isRecordDelimiter(chr, buf, pos) { - var record_delimiter = this.options.record_delimiter; - var recordDelimiterLength = record_delimiter.length; - - loop1: for (var i = 0; i < recordDelimiterLength; i++) { - var rd = record_delimiter[i]; - var rdLength = rd.length; - - if (rd[0] !== chr) { - continue; - } - - for (var j = 1; j < rdLength; j++) { - if (rd[j] !== buf[pos + j]) { - continue loop1; - } - } - - return rd.length; - } - - return 0; - } - }, { - key: "__isEscape", - value: function __isEscape(buf, pos, chr) { - var escape = this.options.escape; - if (escape === null) return false; - var l = escape.length; - - if (escape[0] === chr) { - for (var i = 0; i < l; i++) { - if (escape[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - - return false; - } - }, { - key: "__isQuote", - value: function __isQuote(buf, pos) { - var quote = this.options.quote; - if (quote === null) return false; - var l = quote.length; - - for (var i = 0; i < l; i++) { - if (quote[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - }, { - key: "__autoDiscoverRecordDelimiter", - value: function __autoDiscoverRecordDelimiter(buf, pos) { - var encoding = this.options.encoding; - var chr = buf[pos]; - - if (chr === cr) { - if (buf[pos + 1] === nl) { - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)); - this.state.recordDelimiterMaxLength = 2; - return 2; - } else { - this.options.record_delimiter.push(Buffer.from('\r', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - } else if (chr === nl) { - this.options.record_delimiter.push(Buffer.from('\n', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - - return 0; - } - }, { - key: "__error", - value: function __error(msg) { - var skip_lines_with_error = this.options.skip_lines_with_error; - var err = typeof msg === 'string' ? new Error(msg) : msg; - - if (skip_lines_with_error) { - this.state.recordHasError = true; - this.emit('skip', err); - return undefined; - } else { - return err; - } - } - }, { - key: "__infoDataSet", - value: function __infoDataSet() { - return _objectSpread(_objectSpread({}, this.info), {}, { - columns: this.options.columns - }); - } - }, { - key: "__infoRecord", - value: function __infoRecord() { - var columns = this.options.columns; - return _objectSpread(_objectSpread({}, this.__infoDataSet()), {}, { - error: this.state.error, - header: columns === true, - index: this.state.record.length - }); - } - }, { - key: "__infoField", - value: function __infoField() { - var columns = this.options.columns; - var isColumns = Array.isArray(columns); - return _objectSpread(_objectSpread({}, this.__infoRecord()), {}, { - column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length, - quoting: this.state.wasQuoting - }); - } - }]); - - return Parser; -}(Transform); - -var parse = function parse() { - var data, options, callback; - - for (var i in arguments) { - var argument = arguments[i]; - - var type = _typeof(argument); - - if (data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(i)], options || {}); - } - } - - var parser = new Parser(options); - - if (callback) { - var records = options === undefined || options.objname === undefined ? [] : {}; - parser.on('readable', function () { - var record; - - while ((record = this.read()) !== null) { - if (options === undefined || options.objname === undefined) { - records.push(record); - } else { - records[record[0]] = record[1]; - } - } - }); - parser.on('error', function (err) { - callback(err, undefined, parser.__infoDataSet()); - }); - parser.on('end', function () { - callback(undefined, records, parser.__infoDataSet()); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - parser.write(data); - parser.end(); - }); - } else { - parser.write(data); - parser.end(); - } - } - - return parser; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message, options) { - var _this2; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this2 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this2), CsvError); - } - - _this2.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { - contexts[_key - 3] = arguments[_key]; - } - - for (var _i2 = 0, _contexts = contexts; _i2 < _contexts.length; _i2++) { - var context = _contexts[_i2]; - - for (var key in context) { - var value = context[key]; - _this2[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this2; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -parse.Parser = Parser; -parse.CsvError = CsvError; -module.exports = parse; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var isRecordEmpty = function isRecordEmpty(record) { - return record.every(function (field) { - return field == null || field.toString && field.toString().trim() === ''; - }); -}; - -var normalizeColumnsArray = function normalizeColumnsArray(columns) { - var normalizedColumns = []; - - for (var i = 0, l = columns.length; i < l; i++) { - var column = columns[i]; - - if (column === undefined || column === null || column === false) { - normalizedColumns[i] = { - disabled: true - }; - } else if (typeof column === 'string') { - normalizedColumns[i] = { - name: column - }; - } else if (isObject(column)) { - if (typeof column.name !== 'string') { - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', ['Option columns missing name:', "property \"name\" is required at position ".concat(i), 'when column is an object literal']); - } - - normalizedColumns[i] = column; - } else { - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', ['Invalid column definition:', 'expect a string or a literal object,', "got ".concat(JSON.stringify(column), " at position ").concat(i)]); - } - } - - return normalizedColumns; -}; - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"./ResizeableBuffer":1,"buffer":6,"stream":12,"timers":28}],3:[function(require,module,exports){ -(function (Buffer){(function (){ -"use strict"; - -var parse = require('.'); - -module.exports = function (data) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if (typeof data === 'string') { - data = Buffer.from(data); - } - - var records = options && options.objname ? {} : []; - var parser = new parse.Parser(options); - - parser.push = function (record) { - if (record === null) { - return; - } - - if (options.objname === undefined) records.push(record);else { - records[record[0]] = record[1]; - } - }; - - var err1 = parser.__parse(data, false); - - if (err1 !== undefined) throw err1; - - var err2 = parser.__parse(undefined, true); - - if (err2 !== undefined) throw err2; - return records; -}; - -}).call(this)}).call(this,require("buffer").Buffer) -},{".":2,"buffer":6}],4:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],5:[function(require,module,exports){ - -},{}],6:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":4,"buffer":6,"ieee754":8}],7:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],8:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],9:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],10:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],11:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":6}],12:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":7,"inherits":9,"readable-stream/lib/_stream_duplex.js":14,"readable-stream/lib/_stream_passthrough.js":15,"readable-stream/lib/_stream_readable.js":16,"readable-stream/lib/_stream_transform.js":17,"readable-stream/lib/_stream_writable.js":18,"readable-stream/lib/internal/streams/end-of-stream.js":22,"readable-stream/lib/internal/streams/pipeline.js":24}],13:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],14:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":16,"./_stream_writable":18,"_process":10,"inherits":9}],15:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":17,"inherits":9}],16:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":13,"./_stream_duplex":14,"./internal/streams/async_iterator":19,"./internal/streams/buffer_list":20,"./internal/streams/destroy":21,"./internal/streams/from":23,"./internal/streams/state":25,"./internal/streams/stream":26,"_process":10,"buffer":6,"events":7,"inherits":9,"string_decoder/":27,"util":5}],17:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":13,"./_stream_duplex":14,"inherits":9}],18:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":13,"./_stream_duplex":14,"./internal/streams/destroy":21,"./internal/streams/state":25,"./internal/streams/stream":26,"_process":10,"buffer":6,"inherits":9,"util-deprecate":29}],19:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":22,"_process":10}],20:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":6,"util":5}],21:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":10}],22:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":13}],23:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],24:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":13,"./end-of-stream":22}],25:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":13}],26:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":7}],27:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":11}],28:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":10,"timers":28}],29:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[3])(3) -}); diff --git a/node_modules/csv-parse/lib/es5/ResizeableBuffer.js b/node_modules/csv-parse/lib/es5/ResizeableBuffer.js deleted file mode 100644 index 8df1db3..0000000 --- a/node_modules/csv-parse/lib/es5/ResizeableBuffer.js +++ /dev/null @@ -1,102 +0,0 @@ -"use strict"; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var ResizeableBuffer = /*#__PURE__*/function () { - function ResizeableBuffer() { - var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 100; - - _classCallCheck(this, ResizeableBuffer); - - this.size = size; - this.length = 0; - this.buf = Buffer.alloc(size); - } - - _createClass(ResizeableBuffer, [{ - key: "prepend", - value: function prepend(val) { - if (Buffer.isBuffer(val)) { - var length = this.length + val.length; - - if (length >= this.size) { - this.resize(); - - if (length >= this.size) { - throw Error('INVALID_BUFFER_STATE'); - } - } - - var buf = this.buf; - this.buf = Buffer.alloc(this.size); - val.copy(this.buf, 0); - buf.copy(this.buf, val.length); - this.length += val.length; - } else { - var _length = this.length++; - - if (_length === this.size) { - this.resize(); - } - - var _buf = this.clone(); - - this.buf[0] = val; - - _buf.copy(this.buf, 1, 0, _length); - } - } - }, { - key: "append", - value: function append(val) { - var length = this.length++; - - if (length === this.size) { - this.resize(); - } - - this.buf[length] = val; - } - }, { - key: "clone", - value: function clone() { - return Buffer.from(this.buf.slice(0, this.length)); - } - }, { - key: "resize", - value: function resize() { - var length = this.length; - this.size = this.size * 2; - var buf = Buffer.alloc(this.size); - this.buf.copy(buf, 0, 0, length); - this.buf = buf; - } - }, { - key: "toString", - value: function toString(encoding) { - if (encoding) { - return this.buf.slice(0, this.length).toString(encoding); - } else { - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); - } - } - }, { - key: "toJSON", - value: function toJSON() { - return this.toString('utf8'); - } - }, { - key: "reset", - value: function reset() { - this.length = 0; - } - }]); - - return ResizeableBuffer; -}(); - -module.exports = ResizeableBuffer; \ No newline at end of file diff --git a/node_modules/csv-parse/lib/es5/index.d.ts b/node_modules/csv-parse/lib/es5/index.d.ts deleted file mode 100644 index 60d6b3c..0000000 --- a/node_modules/csv-parse/lib/es5/index.d.ts +++ /dev/null @@ -1,268 +0,0 @@ -// Original definitions in https://github.com/DefinitelyTyped/DefinitelyTyped by: David Muller - -/// - -import * as stream from "stream"; - -export = parse; - -declare function parse(input: Buffer | string, options?: parse.Options, callback?: parse.Callback): parse.Parser; -declare function parse(input: Buffer | string, callback?: parse.Callback): parse.Parser; -declare function parse(options?: parse.Options, callback?: parse.Callback): parse.Parser; -declare function parse(callback?: parse.Callback): parse.Parser; -declare namespace parse { - - type Callback = (err: Error | undefined, records: any | undefined, info: Info) => void; - - interface Parser extends stream.Transform {} - - class Parser { - constructor(options: Options); - - __push(line: any): any; - - __write(chars: any, end: any, callback: any): any; - - readonly options: Options - - readonly info: Info; - } - - interface CastingContext { - readonly column: number | string; - readonly empty_lines: number; - readonly error: CsvError; - readonly header: boolean; - readonly index: number; - readonly quoting: boolean; - readonly lines: number; - readonly records: number; - readonly invalid_field_length: number; - } - - type CastingFunction = (value: string, context: CastingContext) => any; - - type CastingDateFunction = (value: string, context: CastingContext) => Date; - - type ColumnOption = string | undefined | null | false | { name: string }; - - interface Options { - /** - * If true, the parser will attempt to convert read data types to native types. - * @deprecated Use {@link cast} - */ - auto_parse?: boolean | CastingFunction; - autoParse?: boolean | CastingFunction; - /** - * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. - * @deprecated Use {@link cast_date} - */ - auto_parse_date?: boolean | CastingDateFunction; - autoParseDate?: boolean | CastingDateFunction; - /** - * If true, detect and exclude the byte order mark (BOM) from the CSV input if present. - */ - bom?: boolean; - /** - * If true, the parser will attempt to convert input string to native types. - * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below. - */ - cast?: boolean | CastingFunction; - /** - * If true, the parser will attempt to convert input string to dates. - * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse. - */ - cast_date?: boolean | CastingDateFunction; - castDate?: boolean | CastingDateFunction; - /** - * List of fields as an array, - * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, - * default to null, - * affect the result data set in the sense that records will be objects instead of arrays. - */ - columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]); - /** - * Convert values into an array of values when columns are activated and - * when multiple columns of the same name are found. - */ - columns_duplicates_to_array?: boolean; - columnsDuplicatesToArray?: boolean; - /** - * Treat all the characters after this one as a comment, default to '' (disabled). - */ - comment?: string; - /** - * Set the field delimiter. One character only, defaults to comma. - */ - delimiter?: string | string[] | Buffer; - /** - * Set the source and destination encoding, a value of `null` returns buffer instead of strings. - */ - encoding?: string | null; - /** - * Set the escape character, one character only, defaults to double quotes. - */ - escape?: string | null | false | Buffer; - /** - * Start handling records from the requested number of records. - */ - from?: number; - /** - * Start handling records from the requested line number. - */ - from_line?: number; - fromLine?: number; - /** - * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`. - */ - ignore_last_delimiters?: boolean | number; - /** - * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object. - */ - info?: boolean; - /** - * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. - * Does not remove whitespace in a quoted field. - */ - ltrim?: boolean; - /** - * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, - * used to guard against a wrong delimiter or record_delimiter, - * default to 128000 characters. - */ - max_record_size?: number; - maxRecordSize?: number; - /** - * Name of header-record title to name objects by. - */ - objname?: string; - /** - * Alter and filter records by executing a user defined function. - */ - on_record?: (record: any, context: CastingContext) => any; - onRecord?: (record: any, context: CastingContext) => any; - /** - * Optional character surrounding a field, one character only, defaults to double quotes. - */ - quote?: string | boolean | Buffer | null; - /** - * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object. - */ - raw?: boolean; - /** - * Preserve quotes inside unquoted field. - */ - relax?: boolean; - /** - * Discard inconsistent columns count, default to false. - */ - relax_column_count?: boolean; - relaxColumnCount?: boolean; - /** - * Discard inconsistent columns count when the record contains less fields than expected, default to false. - */ - relax_column_count_less?: boolean; - relaxColumnCountLess?: boolean; - /** - * Discard inconsistent columns count when the record contains more fields than expected, default to false. - */ - relax_column_count_more?: boolean; - relaxColumnCountMore?: boolean; - /** - * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided. - * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters. - */ - record_delimiter?: string | string[] | Buffer | Buffer[]; - recordDelimiter?: string | string[] | Buffer | Buffer[]; - /** - * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. - * Does not remove whitespace in a quoted field. - */ - rtrim?: boolean; - /** - * Dont generate empty values for empty lines. - * Defaults to false - */ - skip_empty_lines?: boolean; - skipEmptyLines?: boolean; - /** - * Skip a line with error found inside and directly go process the next line. - */ - skip_lines_with_error?: boolean; - skipLinesWithError?: boolean; - /** - * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false. - */ - skip_lines_with_empty_values?: boolean; - skipLinesWithEmptyValues?: boolean; - /** - * Stop handling records after the requested number of records. - */ - to?: number; - /** - * Stop handling records after the requested line number. - */ - to_line?: number; - toLine?: number; - /** - * If true, ignore whitespace immediately around the delimiter, defaults to false. - * Does not remove whitespace in a quoted field. - */ - trim?: boolean; - } - - interface Info { - /** - * Count the number of lines being fully commented. - */ - readonly comment_lines: number; - /** - * Count the number of processed empty lines. - */ - readonly empty_lines: number; - /** - * The number of lines encountered in the source dataset, start at 1 for the first line. - */ - readonly lines: number; - /** - * Count the number of processed records. - */ - readonly records: number; - /** - * Count of the number of processed bytes. - */ - readonly bytes: number; - /** - * Number of non uniform records when `relax_column_count` is true. - */ - readonly invalid_field_length: number; - } - - class CsvError extends Error { - readonly code: CsvErrorCode; - [key: string]: any; - - constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]); - } - - type CsvErrorCode = - 'CSV_INVALID_OPTION_BOM' - | 'CSV_INVALID_OPTION_CAST' - | 'CSV_INVALID_OPTION_CAST_DATE' - | 'CSV_INVALID_OPTION_COLUMNS' - | 'CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY' - | 'CSV_INVALID_OPTION_COMMENT' - | 'CSV_INVALID_OPTION_DELIMITER' - | 'CSV_INVALID_OPTION_ON_RECORD' - | 'CSV_INVALID_CLOSING_QUOTE' - | 'INVALID_OPENING_QUOTE' - | 'CSV_INVALID_COLUMN_MAPPING' - | 'CSV_INVALID_ARGUMENT' - | 'CSV_INVALID_COLUMN_DEFINITION' - | 'CSV_MAX_RECORD_SIZE' - | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE' - | 'CSV_QUOTE_NOT_CLOSED' - | 'CSV_INCONSISTENT_RECORD_LENGTH' - | 'CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH' - | 'CSV_OPTION_COLUMNS_MISSING_NAME' -} diff --git a/node_modules/csv-parse/lib/es5/index.js b/node_modules/csv-parse/lib/es5/index.js deleted file mode 100644 index 5031200..0000000 --- a/node_modules/csv-parse/lib/es5/index.js +++ /dev/null @@ -1,1530 +0,0 @@ -"use strict"; - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } - -function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } - -function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Parse - -Please look at the [project documentation](https://csv.js.org/parse/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var ResizeableBuffer = require('./ResizeableBuffer'); // white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff - - -var tab = 9; -var nl = 10; // \n, 0x0A in hexadecimal, 10 in decimal - -var np = 12; -var cr = 13; // \r, 0x0D in hexadécimal, 13 in decimal - -var space = 32; -var boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -}; - -var Parser = /*#__PURE__*/function (_Transform) { - _inherits(Parser, _Transform); - - var _super = _createSuper(Parser); - - function Parser() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Parser); - - _this = _super.call(this, _objectSpread(_objectSpread(_objectSpread({}, { - readableObjectMode: true - }), opts), {}, { - encoding: null - })); - _this.__originalOptions = opts; - - _this.__normalizeOptions(opts); - - return _this; - } - - _createClass(Parser, [{ - key: "__normalizeOptions", - value: function __normalizeOptions(opts) { - var options = {}; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - - - if (options.encoding === undefined || options.encoding === true) { - options.encoding = 'utf8'; - } else if (options.encoding === null || options.encoding === false) { - options.encoding = null; - } else if (typeof options.encoding !== 'string' && options.encoding !== null) { - throw new CsvError('CSV_INVALID_OPTION_ENCODING', ['Invalid option encoding:', 'encoding must be a string or null to return a buffer,', "got ".concat(JSON.stringify(options.encoding))], options); - } // Normalize option `bom` - - - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - throw new CsvError('CSV_INVALID_OPTION_BOM', ['Invalid option bom:', 'bom must be true,', "got ".concat(JSON.stringify(options.bom))], options); - } // Normalize option `cast` - - - var fnCastField = null; - - if (options.cast === undefined || options.cast === null || options.cast === false || options.cast === '') { - options.cast = undefined; - } else if (typeof options.cast === 'function') { - fnCastField = options.cast; - options.cast = true; - } else if (options.cast !== true) { - throw new CsvError('CSV_INVALID_OPTION_CAST', ['Invalid option cast:', 'cast must be true or a function,', "got ".concat(JSON.stringify(options.cast))], options); - } // Normalize option `cast_date` - - - if (options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === '') { - options.cast_date = false; - } else if (options.cast_date === true) { - options.cast_date = function (value) { - var date = Date.parse(value); - return !isNaN(date) ? new Date(date) : value; - }; - } else { - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', ['Invalid option cast_date:', 'cast_date must be true or a function,', "got ".concat(JSON.stringify(options.cast_date))], options); - } // Normalize option `columns` - - - var fnFirstLineToHeaders = null; - - if (options.columns === true) { - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined; - } else if (typeof options.columns === 'function') { - fnFirstLineToHeaders = options.columns; - options.columns = true; - } else if (Array.isArray(options.columns)) { - options.columns = normalizeColumnsArray(options.columns); - } else if (options.columns === undefined || options.columns === null || options.columns === false) { - options.columns = false; - } else { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', ['Invalid option columns:', 'expect an array, a function or true,', "got ".concat(JSON.stringify(options.columns))], options); - } // Normalize option `columns_duplicates_to_array` - - - if (options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false) { - options.columns_duplicates_to_array = false; - } else if (options.columns_duplicates_to_array !== true) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'expect an boolean,', "got ".concat(JSON.stringify(options.columns_duplicates_to_array))], options); - } else if (options.columns === false) { - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', ['Invalid option columns_duplicates_to_array:', 'the `columns` mode must be activated.'], options); - } // Normalize option `comment` - - - if (options.comment === undefined || options.comment === null || options.comment === false || options.comment === '') { - options.comment = null; - } else { - if (typeof options.comment === 'string') { - options.comment = Buffer.from(options.comment, options.encoding); - } - - if (!Buffer.isBuffer(options.comment)) { - throw new CsvError('CSV_INVALID_OPTION_COMMENT', ['Invalid option comment:', 'comment must be a buffer or a string,', "got ".concat(JSON.stringify(options.comment))], options); - } - } // Normalize option `delimiter` - - - var delimiter_json = JSON.stringify(options.delimiter); - if (!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; - - if (options.delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - options.delimiter = options.delimiter.map(function (delimiter) { - if (delimiter === undefined || delimiter === null || delimiter === false) { - return Buffer.from(',', options.encoding); - } - - if (typeof delimiter === 'string') { - delimiter = Buffer.from(delimiter, options.encoding); - } - - if (!Buffer.isBuffer(delimiter) || delimiter.length === 0) { - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', ['Invalid option delimiter:', 'delimiter must be a non empty string or buffer or array of string|buffer,', "got ".concat(delimiter_json)], options); - } - - return delimiter; - }); // Normalize option `escape` - - if (options.escape === undefined || options.escape === true) { - options.escape = Buffer.from('"', options.encoding); - } else if (typeof options.escape === 'string') { - options.escape = Buffer.from(options.escape, options.encoding); - } else if (options.escape === null || options.escape === false) { - options.escape = null; - } - - if (options.escape !== null) { - if (!Buffer.isBuffer(options.escape)) { - throw new Error("Invalid Option: escape must be a buffer, a string or a boolean, got ".concat(JSON.stringify(options.escape))); - } - } // Normalize option `from` - - - if (options.from === undefined || options.from === null) { - options.from = 1; - } else { - if (typeof options.from === 'string' && /\d+/.test(options.from)) { - options.from = parseInt(options.from); - } - - if (Number.isInteger(options.from)) { - if (options.from < 0) { - throw new Error("Invalid Option: from must be a positive integer, got ".concat(JSON.stringify(opts.from))); - } - } else { - throw new Error("Invalid Option: from must be an integer, got ".concat(JSON.stringify(options.from))); - } - } // Normalize option `from_line` - - - if (options.from_line === undefined || options.from_line === null) { - options.from_line = 1; - } else { - if (typeof options.from_line === 'string' && /\d+/.test(options.from_line)) { - options.from_line = parseInt(options.from_line); - } - - if (Number.isInteger(options.from_line)) { - if (options.from_line <= 0) { - throw new Error("Invalid Option: from_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.from_line))); - } - } else { - throw new Error("Invalid Option: from_line must be an integer, got ".concat(JSON.stringify(opts.from_line))); - } - } // Normalize options `ignore_last_delimiters` - - - if (options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null) { - options.ignore_last_delimiters = false; - } else if (typeof options.ignore_last_delimiters === 'number') { - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); - - if (options.ignore_last_delimiters === 0) { - options.ignore_last_delimiters = false; - } - } else if (typeof options.ignore_last_delimiters !== 'boolean') { - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', ['Invalid option `ignore_last_delimiters`:', 'the value must be a boolean value or an integer,', "got ".concat(JSON.stringify(options.ignore_last_delimiters))], options); - } - - if (options.ignore_last_delimiters === true && options.columns === false) { - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', ['The option `ignore_last_delimiters`', 'requires the activation of the `columns` option'], options); - } // Normalize option `info` - - - if (options.info === undefined || options.info === null || options.info === false) { - options.info = false; - } else if (options.info !== true) { - throw new Error("Invalid Option: info must be true, got ".concat(JSON.stringify(options.info))); - } // Normalize option `max_record_size` - - - if (options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false) { - options.max_record_size = 0; - } else if (Number.isInteger(options.max_record_size) && options.max_record_size >= 0) {// Great, nothing to do - } else if (typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)) { - options.max_record_size = parseInt(options.max_record_size); - } else { - throw new Error("Invalid Option: max_record_size must be a positive integer, got ".concat(JSON.stringify(options.max_record_size))); - } // Normalize option `objname` - - - if (options.objname === undefined || options.objname === null || options.objname === false) { - options.objname = undefined; - } else if (Buffer.isBuffer(options.objname)) { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty buffer"); - } - - if (options.encoding === null) {// Don't call `toString`, leave objname as a buffer - } else { - options.objname = options.objname.toString(options.encoding); - } - } else if (typeof options.objname === 'string') { - if (options.objname.length === 0) { - throw new Error("Invalid Option: objname must be a non empty string"); - } // Great, nothing to do - - } else { - throw new Error("Invalid Option: objname must be a string or a buffer, got ".concat(options.objname)); - } // Normalize option `on_record` - - - if (options.on_record === undefined || options.on_record === null) { - options.on_record = undefined; - } else if (typeof options.on_record !== 'function') { - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', ['Invalid option `on_record`:', 'expect a function,', "got ".concat(JSON.stringify(options.on_record))], options); - } // Normalize option `quote` - - - if (options.quote === null || options.quote === false || options.quote === '') { - options.quote = null; - } else { - if (options.quote === undefined || options.quote === true) { - options.quote = Buffer.from('"', options.encoding); - } else if (typeof options.quote === 'string') { - options.quote = Buffer.from(options.quote, options.encoding); - } - - if (!Buffer.isBuffer(options.quote)) { - throw new Error("Invalid Option: quote must be a buffer or a string, got ".concat(JSON.stringify(options.quote))); - } - } // Normalize option `raw` - - - if (options.raw === undefined || options.raw === null || options.raw === false) { - options.raw = false; - } else if (options.raw !== true) { - throw new Error("Invalid Option: raw must be true, got ".concat(JSON.stringify(options.raw))); - } // Normalize option `record_delimiter` - - - if (!options.record_delimiter) { - options.record_delimiter = []; - } else if (!Array.isArray(options.record_delimiter)) { - options.record_delimiter = [options.record_delimiter]; - } - - options.record_delimiter = options.record_delimiter.map(function (rd) { - if (typeof rd === 'string') { - rd = Buffer.from(rd, options.encoding); - } - - return rd; - }); // Normalize option `relax` - - if (typeof options.relax === 'boolean') {// Great, nothing to do - } else if (options.relax === undefined || options.relax === null) { - options.relax = false; - } else { - throw new Error("Invalid Option: relax must be a boolean, got ".concat(JSON.stringify(options.relax))); - } // Normalize option `relax_column_count` - - - if (typeof options.relax_column_count === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count === undefined || options.relax_column_count === null) { - options.relax_column_count = false; - } else { - throw new Error("Invalid Option: relax_column_count must be a boolean, got ".concat(JSON.stringify(options.relax_column_count))); - } - - if (typeof options.relax_column_count_less === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_less === undefined || options.relax_column_count_less === null) { - options.relax_column_count_less = false; - } else { - throw new Error("Invalid Option: relax_column_count_less must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_less))); - } - - if (typeof options.relax_column_count_more === 'boolean') {// Great, nothing to do - } else if (options.relax_column_count_more === undefined || options.relax_column_count_more === null) { - options.relax_column_count_more = false; - } else { - throw new Error("Invalid Option: relax_column_count_more must be a boolean, got ".concat(JSON.stringify(options.relax_column_count_more))); - } // Normalize option `skip_empty_lines` - - - if (typeof options.skip_empty_lines === 'boolean') {// Great, nothing to do - } else if (options.skip_empty_lines === undefined || options.skip_empty_lines === null) { - options.skip_empty_lines = false; - } else { - throw new Error("Invalid Option: skip_empty_lines must be a boolean, got ".concat(JSON.stringify(options.skip_empty_lines))); - } // Normalize option `skip_lines_with_empty_values` - - - if (typeof options.skip_lines_with_empty_values === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null) { - options.skip_lines_with_empty_values = false; - } else { - throw new Error("Invalid Option: skip_lines_with_empty_values must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_empty_values))); - } // Normalize option `skip_lines_with_error` - - - if (typeof options.skip_lines_with_error === 'boolean') {// Great, nothing to do - } else if (options.skip_lines_with_error === undefined || options.skip_lines_with_error === null) { - options.skip_lines_with_error = false; - } else { - throw new Error("Invalid Option: skip_lines_with_error must be a boolean, got ".concat(JSON.stringify(options.skip_lines_with_error))); - } // Normalize option `rtrim` - - - if (options.rtrim === undefined || options.rtrim === null || options.rtrim === false) { - options.rtrim = false; - } else if (options.rtrim !== true) { - throw new Error("Invalid Option: rtrim must be a boolean, got ".concat(JSON.stringify(options.rtrim))); - } // Normalize option `ltrim` - - - if (options.ltrim === undefined || options.ltrim === null || options.ltrim === false) { - options.ltrim = false; - } else if (options.ltrim !== true) { - throw new Error("Invalid Option: ltrim must be a boolean, got ".concat(JSON.stringify(options.ltrim))); - } // Normalize option `trim` - - - if (options.trim === undefined || options.trim === null || options.trim === false) { - options.trim = false; - } else if (options.trim !== true) { - throw new Error("Invalid Option: trim must be a boolean, got ".concat(JSON.stringify(options.trim))); - } // Normalize options `trim`, `ltrim` and `rtrim` - - - if (options.trim === true && opts.ltrim !== false) { - options.ltrim = true; - } else if (options.ltrim !== true) { - options.ltrim = false; - } - - if (options.trim === true && opts.rtrim !== false) { - options.rtrim = true; - } else if (options.rtrim !== true) { - options.rtrim = false; - } // Normalize option `to` - - - if (options.to === undefined || options.to === null) { - options.to = -1; - } else { - if (typeof options.to === 'string' && /\d+/.test(options.to)) { - options.to = parseInt(options.to); - } - - if (Number.isInteger(options.to)) { - if (options.to <= 0) { - throw new Error("Invalid Option: to must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to))); - } - } else { - throw new Error("Invalid Option: to must be an integer, got ".concat(JSON.stringify(opts.to))); - } - } // Normalize option `to_line` - - - if (options.to_line === undefined || options.to_line === null) { - options.to_line = -1; - } else { - if (typeof options.to_line === 'string' && /\d+/.test(options.to_line)) { - options.to_line = parseInt(options.to_line); - } - - if (Number.isInteger(options.to_line)) { - if (options.to_line <= 0) { - throw new Error("Invalid Option: to_line must be a positive integer greater than 0, got ".concat(JSON.stringify(opts.to_line))); - } - } else { - throw new Error("Invalid Option: to_line must be an integer, got ".concat(JSON.stringify(opts.to_line))); - } - } - - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - }; - this.options = options; - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max.apply(Math, [// Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0].concat(_toConsumableArray(options.delimiter.map(function (delimiter) { - return delimiter.length; - })), [// Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0])), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max.apply(Math, _toConsumableArray(options.record_delimiter.map(function (v) { - return v.length; - }))), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - }; - } // Implementation of `Transform._transform` - - }, { - key: "_transform", - value: function _transform(buf, encoding, callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(buf, false); - - if (err !== undefined) { - this.state.stop = true; - } - - callback(err); - } // Implementation of `Transform._flush` - - }, { - key: "_flush", - value: function _flush(callback) { - if (this.state.stop === true) { - return; - } - - var err = this.__parse(undefined, true); - - callback(err); - } // Central parser implementation - - }, { - key: "__parse", - value: function __parse(nextBuf, end) { - var _this$options = this.options, - bom = _this$options.bom, - comment = _this$options.comment, - escape = _this$options.escape, - from_line = _this$options.from_line, - ltrim = _this$options.ltrim, - max_record_size = _this$options.max_record_size, - quote = _this$options.quote, - raw = _this$options.raw, - relax = _this$options.relax, - rtrim = _this$options.rtrim, - skip_empty_lines = _this$options.skip_empty_lines, - to = _this$options.to, - to_line = _this$options.to_line; - var record_delimiter = this.options.record_delimiter; - var _this$state = this.state, - bomSkipped = _this$state.bomSkipped, - previousBuf = _this$state.previousBuf, - rawBuffer = _this$state.rawBuffer, - escapeIsQuote = _this$state.escapeIsQuote; - var buf; - - if (previousBuf === undefined) { - if (nextBuf === undefined) { - // Handle empty string - this.push(null); - return; - } else { - buf = nextBuf; - } - } else if (previousBuf !== undefined && nextBuf === undefined) { - buf = previousBuf; - } else { - buf = Buffer.concat([previousBuf, nextBuf]); - } // Handle UTF BOM - - - if (bomSkipped === false) { - if (bom === false) { - this.state.bomSkipped = true; - } else if (buf.length < 3) { - // No enough data - if (end === false) { - // Wait for more data - this.state.previousBuf = buf; - return; - } - } else { - for (var encoding in boms) { - if (boms[encoding].compare(buf, 0, boms[encoding].length) === 0) { - // Skip BOM - var bomLength = boms[encoding].length; - this.state.bufBytesStart += bomLength; - buf = buf.slice(bomLength); // Renormalize original options with the new encoding - - this.__normalizeOptions(_objectSpread(_objectSpread({}, this.__originalOptions), {}, { - encoding: encoding - })); - - break; - } - } - - this.state.bomSkipped = true; - } - } - - var bufLen = buf.length; - var pos; - - for (pos = 0; pos < bufLen; pos++) { - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if (this.__needMoreData(pos, bufLen, end)) { - break; - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - - if (to_line !== -1 && this.info.lines > to_line) { - this.state.stop = true; - this.push(null); - return; - } // Auto discovery of record_delimiter, unix, mac and windows supported - - - if (this.state.quoting === false && record_delimiter.length === 0) { - var record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); - - if (record_delimiterCount) { - record_delimiter = this.options.record_delimiter; - } - } - - var chr = buf[pos]; - - if (raw === true) { - rawBuffer.append(chr); - } - - if ((chr === cr || chr === nl) && this.state.wasRowDelimiter === false) { - this.state.wasRowDelimiter = true; - } // Previous char was a valid escape char - // treat the current char as a regular char - - - if (this.state.escaping === true) { - this.state.escaping = false; - } else { - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if (escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen) { - if (escapeIsQuote) { - if (this.__isQuote(buf, pos + escape.length)) { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } else { - this.state.escaping = true; - pos += escape.length - 1; - continue; - } - } // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - - - if (this.state.commenting === false && this.__isQuote(buf, pos)) { - if (this.state.quoting === true) { - var nextChr = buf[pos + quote.length]; - - var isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr); - - var isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos + quote.length, nextChr); - - var isNextChrDelimiter = this.__isDelimiter(buf, pos + quote.length, nextChr); - - var isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos + quote.length) : this.__isRecordDelimiter(nextChr, buf, pos + quote.length); // Escape a quote - // Treat next char as a regular character - - if (escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)) { - pos += escape.length - 1; - } else if (!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable) { - this.state.quoting = false; - this.state.wasQuoting = true; - pos += quote.length - 1; - continue; - } else if (relax === false) { - var err = this.__error(new CsvError('CSV_INVALID_CLOSING_QUOTE', ['Invalid Closing Quote:', "got \"".concat(String.fromCharCode(nextChr), "\""), "at line ".concat(this.info.lines), 'instead of delimiter, record delimiter, trimable character', '(if activated) or comment'], this.options, this.__infoField())); - - if (err !== undefined) return err; - } else { - this.state.quoting = false; - this.state.wasQuoting = true; - this.state.field.prepend(quote); - pos += quote.length - 1; - } - } else { - if (this.state.field.length !== 0) { - // In relax mode, treat opening quote preceded by chrs as regular - if (relax === false) { - var _err = this.__error(new CsvError('INVALID_OPENING_QUOTE', ['Invalid Opening Quote:', "a quote is found inside a field at line ".concat(this.info.lines)], this.options, this.__infoField(), { - field: this.state.field - })); - - if (_err !== undefined) return _err; - } - } else { - this.state.quoting = true; - pos += quote.length - 1; - continue; - } - } - } - - if (this.state.quoting === false) { - var recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); - - if (recordDelimiterLength !== 0) { - // Do not emit comments which take a full line - var skipCommentLine = this.state.commenting && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0; - - if (skipCommentLine) { - this.info.comment_lines++; // Skip full comment line - } else { - // Activate records emition if above from_line - if (this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1 : 0) >= from_line) { - this.state.enabled = true; - - this.__resetField(); - - this.__resetRecord(); - - pos += recordDelimiterLength - 1; - continue; - } // Skip if line is empty and skip_empty_lines activated - - - if (skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) { - this.info.empty_lines++; - pos += recordDelimiterLength - 1; - continue; - } - - this.info.bytes = this.state.bufBytesStart + pos; - - var errField = this.__onField(); - - if (errField !== undefined) return errField; - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - - var errRecord = this.__onRecord(); - - if (errRecord !== undefined) return errRecord; - - if (to !== -1 && this.info.records >= to) { - this.state.stop = true; - this.push(null); - return; - } - } - - this.state.commenting = false; - pos += recordDelimiterLength - 1; - continue; - } - - if (this.state.commenting) { - continue; - } - - var commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr); - - if (commentCount !== 0) { - this.state.commenting = true; - continue; - } - - var delimiterLength = this.__isDelimiter(buf, pos, chr); - - if (delimiterLength !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField = this.__onField(); - - if (_errField !== undefined) return _errField; - pos += delimiterLength - 1; - continue; - } - } - } - - if (this.state.commenting === false) { - if (max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size) { - var _err2 = this.__error(new CsvError('CSV_MAX_RECORD_SIZE', ['Max Record Size:', 'record exceed the maximum number of tolerated bytes', "of ".concat(max_record_size), "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err2 !== undefined) return _err2; - } - } - - var lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr); // rtrim in non quoting is handle in __onField - - var rappend = rtrim === false || this.state.wasQuoting === false; - - if (lappend === true && rappend === true) { - this.state.field.append(chr); - } else if (rtrim === true && !this.__isCharTrimable(chr)) { - var _err3 = this.__error(new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', ['Invalid Closing Quote:', 'found non trimable byte after quote', "at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err3 !== undefined) return _err3; - } - } - - if (end === true) { - // Ensure we are not ending in a quoting state - if (this.state.quoting === true) { - var _err4 = this.__error(new CsvError('CSV_QUOTE_NOT_CLOSED', ['Quote Not Closed:', "the parsing is finished with an opening quote at line ".concat(this.info.lines)], this.options, this.__infoField())); - - if (_err4 !== undefined) return _err4; - } else { - // Skip last line if it has no characters - if (this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0) { - this.info.bytes = this.state.bufBytesStart + pos; - - var _errField2 = this.__onField(); - - if (_errField2 !== undefined) return _errField2; - - var _errRecord = this.__onRecord(); - - if (_errRecord !== undefined) return _errRecord; - } else if (this.state.wasRowDelimiter === true) { - this.info.empty_lines++; - } else if (this.state.commenting === true) { - this.info.comment_lines++; - } - } - } else { - this.state.bufBytesStart += pos; - this.state.previousBuf = buf.slice(pos); - } - - if (this.state.wasRowDelimiter === true) { - this.info.lines++; - this.state.wasRowDelimiter = false; - } - } - }, { - key: "__onRecord", - value: function __onRecord() { - var _this$options2 = this.options, - columns = _this$options2.columns, - columns_duplicates_to_array = _this$options2.columns_duplicates_to_array, - encoding = _this$options2.encoding, - info = _this$options2.info, - from = _this$options2.from, - relax_column_count = _this$options2.relax_column_count, - relax_column_count_less = _this$options2.relax_column_count_less, - relax_column_count_more = _this$options2.relax_column_count_more, - raw = _this$options2.raw, - skip_lines_with_empty_values = _this$options2.skip_lines_with_empty_values; - var _this$state2 = this.state, - enabled = _this$state2.enabled, - record = _this$state2.record; - - if (enabled === false) { - return this.__resetRecord(); - } // Convert the first line into column names - - - var recordLength = record.length; - - if (columns === true) { - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - return this.__firstLineToColumns(record); - } - - if (columns === false && this.info.records === 0) { - this.state.expectedRecordLength = recordLength; - } - - if (recordLength !== this.state.expectedRecordLength) { - var err = columns === false ? // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', ['Invalid Record Length:', "expect ".concat(this.state.expectedRecordLength, ","), "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }) : // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', ['Invalid Record Length:', "columns length is ".concat(columns.length, ","), // rename columns - "got ".concat(recordLength, " on line ").concat(this.info.lines)], this.options, this.__infoField(), { - record: record - }); - - if (relax_column_count === true || relax_column_count_less === true && recordLength < this.state.expectedRecordLength || relax_column_count_more === true && recordLength > this.state.expectedRecordLength) { - this.info.invalid_field_length++; - this.state.error = err; // Error is undefined with skip_lines_with_error - } else { - var finalErr = this.__error(err); - - if (finalErr) return finalErr; - } - } - - if (skip_lines_with_empty_values === true && isRecordEmpty(record)) { - this.__resetRecord(); - - return; - } - - if (this.state.recordHasError === true) { - this.__resetRecord(); - - this.state.recordHasError = false; - return; - } - - this.info.records++; - - if (from === 1 || this.info.records >= from) { - // With columns, records are object - if (columns !== false) { - var obj = {}; // Transform record array to an object - - for (var i = 0, l = record.length; i < l; i++) { - if (columns[i] === undefined || columns[i].disabled) continue; // Turn duplicate columns into an array - - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]); - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]]; - } - } else { - obj[columns[i].name] = record[i]; - } - } - - var objname = this.options.objname; // Without objname (default) - - if (objname === undefined) { - if (raw === true || info === true) { - var _err5 = this.__push(Object.assign({ - record: obj - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err5) { - return _err5; - } - } else { - var _err6 = this.__push(obj); - - if (_err6) { - return _err6; - } - } // With objname (default) - - } else { - if (raw === true || info === true) { - var _err7 = this.__push(Object.assign({ - record: [obj[objname], obj] - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err7) { - return _err7; - } - } else { - var _err8 = this.__push([obj[objname], obj]); - - if (_err8) { - return _err8; - } - } - } // Without columns, records are array - - } else { - if (raw === true || info === true) { - var _err9 = this.__push(Object.assign({ - record: record - }, raw === true ? { - raw: this.state.rawBuffer.toString(encoding) - } : {}, info === true ? { - info: this.__infoRecord() - } : {})); - - if (_err9) { - return _err9; - } - } else { - var _err10 = this.__push(record); - - if (_err10) { - return _err10; - } - } - } - } - - this.__resetRecord(); - } - }, { - key: "__firstLineToColumns", - value: function __firstLineToColumns(record) { - var firstLineToHeaders = this.state.firstLineToHeaders; - - try { - var headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); - - if (!Array.isArray(headers)) { - return this.__error(new CsvError('CSV_INVALID_COLUMN_MAPPING', ['Invalid Column Mapping:', 'expect an array from column function,', "got ".concat(JSON.stringify(headers))], this.options, this.__infoField(), { - headers: headers - })); - } - - var normalizedHeaders = normalizeColumnsArray(headers); - this.state.expectedRecordLength = normalizedHeaders.length; - this.options.columns = normalizedHeaders; - - this.__resetRecord(); - - return; - } catch (err) { - return err; - } - } - }, { - key: "__resetRecord", - value: function __resetRecord() { - if (this.options.raw === true) { - this.state.rawBuffer.reset(); - } - - this.state.error = undefined; - this.state.record = []; - this.state.record_length = 0; - } - }, { - key: "__onField", - value: function __onField() { - var _this$options3 = this.options, - cast = _this$options3.cast, - encoding = _this$options3.encoding, - rtrim = _this$options3.rtrim, - max_record_size = _this$options3.max_record_size; - var _this$state3 = this.state, - enabled = _this$state3.enabled, - wasQuoting = _this$state3.wasQuoting; // Short circuit for the from_line options - - if (enabled === false) { - return this.__resetField(); - } - - var field = this.state.field.toString(encoding); - - if (rtrim === true && wasQuoting === false) { - field = field.trimRight(); - } - - if (cast === true) { - var _this$__cast = this.__cast(field), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - f = _this$__cast2[1]; - - if (err !== undefined) return err; - field = f; - } - - this.state.record.push(field); // Increment record length if record size must not exceed a limit - - if (max_record_size !== 0 && typeof field === 'string') { - this.state.record_length += field.length; - } - - this.__resetField(); - } - }, { - key: "__resetField", - value: function __resetField() { - this.state.field.reset(); - this.state.wasQuoting = false; - } - }, { - key: "__push", - value: function __push(record) { - var on_record = this.options.on_record; - - if (on_record !== undefined) { - var info = this.__infoRecord(); - - try { - record = on_record.call(null, record, info); - } catch (err) { - return err; - } - - if (record === undefined || record === null) { - return; - } - } - - this.push(record); - } // Return a tuple with the error and the casted value - - }, { - key: "__cast", - value: function __cast(field) { - var _this$options4 = this.options, - columns = _this$options4.columns, - relax_column_count = _this$options4.relax_column_count; - var isColumns = Array.isArray(columns); // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - - if (isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length) { - return [undefined, undefined]; - } - - if (this.state.castField !== null) { - try { - var info = this.__infoField(); - - return [undefined, this.state.castField.call(null, field, info)]; - } catch (err) { - return [err]; - } - } - - if (this.__isFloat(field)) { - return [undefined, parseFloat(field)]; - } else if (this.options.cast_date !== false) { - var _info = this.__infoField(); - - return [undefined, this.options.cast_date.call(null, field, _info)]; - } - - return [undefined, field]; - } // Helper to test if a character is a space or a line delimiter - - }, { - key: "__isCharTrimable", - value: function __isCharTrimable(chr) { - return chr === space || chr === tab || chr === cr || chr === nl || chr === np; - } // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - - }, { - key: "__isFloat", - value: function __isFloat(value) { - return value - parseFloat(value) + 1 >= 0; // Borrowed from jquery - } - }, { - key: "__compareBytes", - value: function __compareBytes(sourceBuf, targetBuf, targetPos, firstByte) { - if (sourceBuf[0] !== firstByte) return 0; - var sourceLength = sourceBuf.length; - - for (var i = 1; i < sourceLength; i++) { - if (sourceBuf[i] !== targetBuf[targetPos + i]) return 0; - } - - return sourceLength; - } - }, { - key: "__needMoreData", - value: function __needMoreData(i, bufLen, end) { - if (end) return false; - var quote = this.options.quote; - var _this$state4 = this.state, - quoting = _this$state4.quoting, - needMoreDataSize = _this$state4.needMoreDataSize, - recordDelimiterMaxLength = _this$state4.recordDelimiterMaxLength; - var numOfCharLeft = bufLen - i - 1; - var requiredLength = Math.max(needMoreDataSize, // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? quote.length + recordDelimiterMaxLength : 0); - return numOfCharLeft < requiredLength; - } - }, { - key: "__isDelimiter", - value: function __isDelimiter(buf, pos, chr) { - var _this$options5 = this.options, - delimiter = _this$options5.delimiter, - ignore_last_delimiters = _this$options5.ignore_last_delimiters; - - if (ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1) { - return 0; - } else if (ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1) { - return 0; - } - - loop1: for (var i = 0; i < delimiter.length; i++) { - var del = delimiter[i]; - - if (del[0] === chr) { - for (var j = 1; j < del.length; j++) { - if (del[j] !== buf[pos + j]) continue loop1; - } - - return del.length; - } - } - - return 0; - } - }, { - key: "__isRecordDelimiter", - value: function __isRecordDelimiter(chr, buf, pos) { - var record_delimiter = this.options.record_delimiter; - var recordDelimiterLength = record_delimiter.length; - - loop1: for (var i = 0; i < recordDelimiterLength; i++) { - var rd = record_delimiter[i]; - var rdLength = rd.length; - - if (rd[0] !== chr) { - continue; - } - - for (var j = 1; j < rdLength; j++) { - if (rd[j] !== buf[pos + j]) { - continue loop1; - } - } - - return rd.length; - } - - return 0; - } - }, { - key: "__isEscape", - value: function __isEscape(buf, pos, chr) { - var escape = this.options.escape; - if (escape === null) return false; - var l = escape.length; - - if (escape[0] === chr) { - for (var i = 0; i < l; i++) { - if (escape[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - - return false; - } - }, { - key: "__isQuote", - value: function __isQuote(buf, pos) { - var quote = this.options.quote; - if (quote === null) return false; - var l = quote.length; - - for (var i = 0; i < l; i++) { - if (quote[i] !== buf[pos + i]) { - return false; - } - } - - return true; - } - }, { - key: "__autoDiscoverRecordDelimiter", - value: function __autoDiscoverRecordDelimiter(buf, pos) { - var encoding = this.options.encoding; - var chr = buf[pos]; - - if (chr === cr) { - if (buf[pos + 1] === nl) { - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)); - this.state.recordDelimiterMaxLength = 2; - return 2; - } else { - this.options.record_delimiter.push(Buffer.from('\r', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - } else if (chr === nl) { - this.options.record_delimiter.push(Buffer.from('\n', encoding)); - this.state.recordDelimiterMaxLength = 1; - return 1; - } - - return 0; - } - }, { - key: "__error", - value: function __error(msg) { - var skip_lines_with_error = this.options.skip_lines_with_error; - var err = typeof msg === 'string' ? new Error(msg) : msg; - - if (skip_lines_with_error) { - this.state.recordHasError = true; - this.emit('skip', err); - return undefined; - } else { - return err; - } - } - }, { - key: "__infoDataSet", - value: function __infoDataSet() { - return _objectSpread(_objectSpread({}, this.info), {}, { - columns: this.options.columns - }); - } - }, { - key: "__infoRecord", - value: function __infoRecord() { - var columns = this.options.columns; - return _objectSpread(_objectSpread({}, this.__infoDataSet()), {}, { - error: this.state.error, - header: columns === true, - index: this.state.record.length - }); - } - }, { - key: "__infoField", - value: function __infoField() { - var columns = this.options.columns; - var isColumns = Array.isArray(columns); - return _objectSpread(_objectSpread({}, this.__infoRecord()), {}, { - column: isColumns === true ? columns.length > this.state.record.length ? columns[this.state.record.length].name : null : this.state.record.length, - quoting: this.state.wasQuoting - }); - } - }]); - - return Parser; -}(Transform); - -var parse = function parse() { - var data, options, callback; - - for (var i in arguments) { - var argument = arguments[i]; - - var type = _typeof(argument); - - if (data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(i)], options || {}); - } - } - - var parser = new Parser(options); - - if (callback) { - var records = options === undefined || options.objname === undefined ? [] : {}; - parser.on('readable', function () { - var record; - - while ((record = this.read()) !== null) { - if (options === undefined || options.objname === undefined) { - records.push(record); - } else { - records[record[0]] = record[1]; - } - } - }); - parser.on('error', function (err) { - callback(err, undefined, parser.__infoDataSet()); - }); - parser.on('end', function () { - callback(undefined, records, parser.__infoDataSet()); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - parser.write(data); - parser.end(); - }); - } else { - parser.write(data); - parser.end(); - } - } - - return parser; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message, options) { - var _this2; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this2 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this2), CsvError); - } - - _this2.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) { - contexts[_key - 3] = arguments[_key]; - } - - for (var _i2 = 0, _contexts = contexts; _i2 < _contexts.length; _i2++) { - var context = _contexts[_i2]; - - for (var key in context) { - var value = context[key]; - _this2[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this2; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -parse.Parser = Parser; -parse.CsvError = CsvError; -module.exports = parse; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var isRecordEmpty = function isRecordEmpty(record) { - return record.every(function (field) { - return field == null || field.toString && field.toString().trim() === ''; - }); -}; - -var normalizeColumnsArray = function normalizeColumnsArray(columns) { - var normalizedColumns = []; - - for (var i = 0, l = columns.length; i < l; i++) { - var column = columns[i]; - - if (column === undefined || column === null || column === false) { - normalizedColumns[i] = { - disabled: true - }; - } else if (typeof column === 'string') { - normalizedColumns[i] = { - name: column - }; - } else if (isObject(column)) { - if (typeof column.name !== 'string') { - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', ['Option columns missing name:', "property \"name\" is required at position ".concat(i), 'when column is an object literal']); - } - - normalizedColumns[i] = column; - } else { - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', ['Invalid column definition:', 'expect a string or a literal object,', "got ".concat(JSON.stringify(column), " at position ").concat(i)]); - } - } - - return normalizedColumns; -}; \ No newline at end of file diff --git a/node_modules/csv-parse/lib/es5/sync.d.ts b/node_modules/csv-parse/lib/es5/sync.d.ts deleted file mode 100644 index 7886698..0000000 --- a/node_modules/csv-parse/lib/es5/sync.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as csvParse from './index'; - -export = parse; - -declare function parse(input: Buffer | string, options?: csvParse.Options): any; -declare namespace parse {} \ No newline at end of file diff --git a/node_modules/csv-parse/lib/es5/sync.js b/node_modules/csv-parse/lib/es5/sync.js deleted file mode 100644 index 00106a0..0000000 --- a/node_modules/csv-parse/lib/es5/sync.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; - -var parse = require('.'); - -module.exports = function (data) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - if (typeof data === 'string') { - data = Buffer.from(data); - } - - var records = options && options.objname ? {} : []; - var parser = new parse.Parser(options); - - parser.push = function (record) { - if (record === null) { - return; - } - - if (options.objname === undefined) records.push(record);else { - records[record[0]] = record[1]; - } - }; - - var err1 = parser.__parse(data, false); - - if (err1 !== undefined) throw err1; - - var err2 = parser.__parse(undefined, true); - - if (err2 !== undefined) throw err2; - return records; -}; \ No newline at end of file diff --git a/node_modules/csv-parse/lib/index.d.ts b/node_modules/csv-parse/lib/index.d.ts index 60d6b3c..ec8aa02 100644 --- a/node_modules/csv-parse/lib/index.d.ts +++ b/node_modules/csv-parse/lib/index.d.ts @@ -4,265 +4,280 @@ import * as stream from "stream"; -export = parse; +export type Callback = (err: CsvError | undefined, records: any | undefined, info: Info) => void; -declare function parse(input: Buffer | string, options?: parse.Options, callback?: parse.Callback): parse.Parser; -declare function parse(input: Buffer | string, callback?: parse.Callback): parse.Parser; -declare function parse(options?: parse.Options, callback?: parse.Callback): parse.Parser; -declare function parse(callback?: parse.Callback): parse.Parser; -declare namespace parse { +export interface Parser extends stream.Transform {} - type Callback = (err: Error | undefined, records: any | undefined, info: Info) => void; +export class Parser { + constructor(options: Options); + + __push(line: any): any; + + __write(chars: any, end: any, callback: any): any; + + readonly options: Options + + readonly info: Info; +} + +export interface CastingContext { + readonly column: number | string; + readonly empty_lines: number; + readonly error: CsvError; + readonly header: boolean; + readonly index: number; + readonly quoting: boolean; + readonly lines: number; + readonly records: number; + readonly invalid_field_length: number; +} - interface Parser extends stream.Transform {} +export type CastingFunction = (value: string, context: CastingContext) => any; - class Parser { - constructor(options: Options); - - __push(line: any): any; - - __write(chars: any, end: any, callback: any): any; - - readonly options: Options - - readonly info: Info; - } +export type CastingDateFunction = (value: string, context: CastingContext) => Date; - interface CastingContext { - readonly column: number | string; - readonly empty_lines: number; - readonly error: CsvError; - readonly header: boolean; - readonly index: number; - readonly quoting: boolean; - readonly lines: number; - readonly records: number; - readonly invalid_field_length: number; - } +export type ColumnOption = string | undefined | null | false | { name: string }; - type CastingFunction = (value: string, context: CastingContext) => any; +/* +Note, could not `extends stream.TransformOptions` because encoding can be +BufferEncoding and undefined as well as null which is not defined in the +extended type. +*/ +export interface Options { + /** + * If true, the parser will attempt to convert read data types to native types. + * @deprecated Use {@link cast} + */ + auto_parse?: boolean | CastingFunction; + autoParse?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. + * @deprecated Use {@link cast_date} + */ + auto_parse_date?: boolean | CastingDateFunction; + autoParseDate?: boolean | CastingDateFunction; + /** + * If true, detect and exclude the byte order mark (BOM) from the CSV input if present. + */ + bom?: boolean; + /** + * If true, the parser will attempt to convert input string to native types. + * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below. + */ + cast?: boolean | CastingFunction; + /** + * If true, the parser will attempt to convert input string to dates. + * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse. + */ + cast_date?: boolean | CastingDateFunction; + castDate?: boolean | CastingDateFunction; + /** + * List of fields as an array, + * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, + * default to null, + * affect the result data set in the sense that records will be objects instead of arrays. + */ + columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]); + /** + * Convert values into an array of values when columns are activated and + * when multiple columns of the same name are found. + */ + group_columns_by_name?: boolean; + groupColumnsByName?: boolean; + /** + * Treat all the characters after this one as a comment, default to '' (disabled). + */ + comment?: string; + /** + * Restrict the definition of comments to a full line. Comment characters + * defined in the middle of the line are not interpreted as such. The + * option require the activation of comments. + */ + comment_no_infix?: boolean; + /** + * Set the field delimiter. One character only, defaults to comma. + */ + delimiter?: string | string[] | Buffer; + /** + * Set the source and destination encoding, a value of `null` returns buffer instead of strings. + */ + encoding?: BufferEncoding | undefined; + /** + * Set the escape character, one character only, defaults to double quotes. + */ + escape?: string | null | false | Buffer; + /** + * Start handling records from the requested number of records. + */ + from?: number; + /** + * Start handling records from the requested line number. + */ + from_line?: number; + fromLine?: number; + /** + * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`. + */ + ignore_last_delimiters?: boolean | number; + /** + * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object. + */ + info?: boolean; + /** + * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + ltrim?: boolean; + /** + * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, + * used to guard against a wrong delimiter or record_delimiter, + * default to 128000 characters. + */ + max_record_size?: number; + maxRecordSize?: number; + /** + * Name of header-record title to name objects by. + */ + objname?: string; + /** + * Alter and filter records by executing a user defined function. + */ + on_record?: (record: any, context: CastingContext) => any; + onRecord?: (record: any, context: CastingContext) => any; + /** + * Optional character surrounding a field, one character only, defaults to double quotes. + */ + quote?: string | boolean | Buffer | null; + /** + * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object. + */ + raw?: boolean; + /** + * Discard inconsistent columns count, default to false. + */ + relax_column_count?: boolean; + relaxColumnCount?: boolean; + /** + * Discard inconsistent columns count when the record contains less fields than expected, default to false. + */ + relax_column_count_less?: boolean; + relaxColumnCountLess?: boolean; + /** + * Discard inconsistent columns count when the record contains more fields than expected, default to false. + */ + relax_column_count_more?: boolean; + relaxColumnCountMore?: boolean; + /** + * Preserve quotes inside unquoted field. + */ + relax_quotes?: boolean; + relaxQuotes?: boolean; + /** + * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided. + * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters. + */ + record_delimiter?: string | string[] | Buffer | Buffer[]; + recordDelimiter?: string | string[] | Buffer | Buffer[]; + /** + * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. + * Does not remove whitespace in a quoted field. + */ + rtrim?: boolean; + /** + * Dont generate empty values for empty lines. + * Defaults to false + */ + skip_empty_lines?: boolean; + skipEmptyLines?: boolean; + /** + * Skip a line with error found inside and directly go process the next line. + */ + skip_records_with_error?: boolean; + skipRecordsWithError?: boolean; + /** + * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false. + */ + skip_records_with_empty_values?: boolean; + skipRecordsWithEmptyValues?: boolean; + /** + * Stop handling records after the requested number of records. + */ + to?: number; + /** + * Stop handling records after the requested line number. + */ + to_line?: number; + toLine?: number; + /** + * If true, ignore whitespace immediately around the delimiter, defaults to false. + * Does not remove whitespace in a quoted field. + */ + trim?: boolean; +} - type CastingDateFunction = (value: string, context: CastingContext) => Date; +export interface Info { + /** + * Count the number of lines being fully commented. + */ + readonly comment_lines: number; + /** + * Count the number of processed empty lines. + */ + readonly empty_lines: number; + /** + * The number of lines encountered in the source dataset, start at 1 for the first line. + */ + readonly lines: number; + /** + * Count the number of processed records. + */ + readonly records: number; + /** + * Count of the number of processed bytes. + */ + readonly bytes: number; + /** + * Number of non uniform records when `relax_column_count` is true. + */ + readonly invalid_field_length: number; + /** + * Normalized verion of `options.columns` when `options.columns` is true, boolean otherwise. + */ + readonly columns: boolean | { name: string }[] | { disabled: true }[]; +} - type ColumnOption = string | undefined | null | false | { name: string }; +export type CsvErrorCode = + 'CSV_INVALID_OPTION_BOM' + | 'CSV_INVALID_OPTION_CAST' + | 'CSV_INVALID_OPTION_CAST_DATE' + | 'CSV_INVALID_OPTION_COLUMNS' + | 'CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME' + | 'CSV_INVALID_OPTION_COMMENT' + | 'CSV_INVALID_OPTION_DELIMITER' + | 'CSV_INVALID_OPTION_ON_RECORD' + | 'CSV_INVALID_CLOSING_QUOTE' + | 'INVALID_OPENING_QUOTE' + | 'CSV_INVALID_COLUMN_MAPPING' + | 'CSV_INVALID_ARGUMENT' + | 'CSV_INVALID_COLUMN_DEFINITION' + | 'CSV_MAX_RECORD_SIZE' + | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE' + | 'CSV_QUOTE_NOT_CLOSED' + | 'CSV_RECORD_INCONSISTENT_FIELDS_LENGTH' + | 'CSV_RECORD_INCONSISTENT_COLUMNS' + | 'CSV_OPTION_COLUMNS_MISSING_NAME' - interface Options { - /** - * If true, the parser will attempt to convert read data types to native types. - * @deprecated Use {@link cast} - */ - auto_parse?: boolean | CastingFunction; - autoParse?: boolean | CastingFunction; - /** - * If true, the parser will attempt to convert read data types to dates. It requires the "auto_parse" option. - * @deprecated Use {@link cast_date} - */ - auto_parse_date?: boolean | CastingDateFunction; - autoParseDate?: boolean | CastingDateFunction; - /** - * If true, detect and exclude the byte order mark (BOM) from the CSV input if present. - */ - bom?: boolean; - /** - * If true, the parser will attempt to convert input string to native types. - * If a function, receive the value as first argument, a context as second argument and return a new value. More information about the context properties is available below. - */ - cast?: boolean | CastingFunction; - /** - * If true, the parser will attempt to convert input string to dates. - * If a function, receive the value as argument and return a new value. It requires the "auto_parse" option. Be careful, it relies on Date.parse. - */ - cast_date?: boolean | CastingDateFunction; - castDate?: boolean | CastingDateFunction; - /** - * List of fields as an array, - * a user defined callback accepting the first line and returning the column names or true if autodiscovered in the first CSV line, - * default to null, - * affect the result data set in the sense that records will be objects instead of arrays. - */ - columns?: ColumnOption[] | boolean | ((record: any) => ColumnOption[]); - /** - * Convert values into an array of values when columns are activated and - * when multiple columns of the same name are found. - */ - columns_duplicates_to_array?: boolean; - columnsDuplicatesToArray?: boolean; - /** - * Treat all the characters after this one as a comment, default to '' (disabled). - */ - comment?: string; - /** - * Set the field delimiter. One character only, defaults to comma. - */ - delimiter?: string | string[] | Buffer; - /** - * Set the source and destination encoding, a value of `null` returns buffer instead of strings. - */ - encoding?: string | null; - /** - * Set the escape character, one character only, defaults to double quotes. - */ - escape?: string | null | false | Buffer; - /** - * Start handling records from the requested number of records. - */ - from?: number; - /** - * Start handling records from the requested line number. - */ - from_line?: number; - fromLine?: number; - /** - * Don't interpret delimiters as such in the last field according to the number of fields calculated from the number of columns, the option require the presence of the `column` option when `true`. - */ - ignore_last_delimiters?: boolean | number; - /** - * Generate two properties `info` and `record` where `info` is a snapshot of the info object at the time the record was created and `record` is the parsed array or object. - */ - info?: boolean; - /** - * If true, ignore whitespace immediately following the delimiter (i.e. left-trim all fields), defaults to false. - * Does not remove whitespace in a quoted field. - */ - ltrim?: boolean; - /** - * Maximum numer of characters to be contained in the field and line buffers before an exception is raised, - * used to guard against a wrong delimiter or record_delimiter, - * default to 128000 characters. - */ - max_record_size?: number; - maxRecordSize?: number; - /** - * Name of header-record title to name objects by. - */ - objname?: string; - /** - * Alter and filter records by executing a user defined function. - */ - on_record?: (record: any, context: CastingContext) => any; - onRecord?: (record: any, context: CastingContext) => any; - /** - * Optional character surrounding a field, one character only, defaults to double quotes. - */ - quote?: string | boolean | Buffer | null; - /** - * Generate two properties raw and row where raw is the original CSV row content and row is the parsed array or object. - */ - raw?: boolean; - /** - * Preserve quotes inside unquoted field. - */ - relax?: boolean; - /** - * Discard inconsistent columns count, default to false. - */ - relax_column_count?: boolean; - relaxColumnCount?: boolean; - /** - * Discard inconsistent columns count when the record contains less fields than expected, default to false. - */ - relax_column_count_less?: boolean; - relaxColumnCountLess?: boolean; - /** - * Discard inconsistent columns count when the record contains more fields than expected, default to false. - */ - relax_column_count_more?: boolean; - relaxColumnCountMore?: boolean; - /** - * One or multiple characters used to delimit record rows; defaults to auto discovery if not provided. - * Supported auto discovery method are Linux ("\n"), Apple ("\r") and Windows ("\r\n") row delimiters. - */ - record_delimiter?: string | string[] | Buffer | Buffer[]; - recordDelimiter?: string | string[] | Buffer | Buffer[]; - /** - * If true, ignore whitespace immediately preceding the delimiter (i.e. right-trim all fields), defaults to false. - * Does not remove whitespace in a quoted field. - */ - rtrim?: boolean; - /** - * Dont generate empty values for empty lines. - * Defaults to false - */ - skip_empty_lines?: boolean; - skipEmptyLines?: boolean; - /** - * Skip a line with error found inside and directly go process the next line. - */ - skip_lines_with_error?: boolean; - skipLinesWithError?: boolean; - /** - * Don't generate records for lines containing empty column values (column matching /\s*\/), defaults to false. - */ - skip_lines_with_empty_values?: boolean; - skipLinesWithEmptyValues?: boolean; - /** - * Stop handling records after the requested number of records. - */ - to?: number; - /** - * Stop handling records after the requested line number. - */ - to_line?: number; - toLine?: number; - /** - * If true, ignore whitespace immediately around the delimiter, defaults to false. - * Does not remove whitespace in a quoted field. - */ - trim?: boolean; - } +export class CsvError extends Error { + readonly code: CsvErrorCode; + [key: string]: any; - interface Info { - /** - * Count the number of lines being fully commented. - */ - readonly comment_lines: number; - /** - * Count the number of processed empty lines. - */ - readonly empty_lines: number; - /** - * The number of lines encountered in the source dataset, start at 1 for the first line. - */ - readonly lines: number; - /** - * Count the number of processed records. - */ - readonly records: number; - /** - * Count of the number of processed bytes. - */ - readonly bytes: number; - /** - * Number of non uniform records when `relax_column_count` is true. - */ - readonly invalid_field_length: number; - } - - class CsvError extends Error { - readonly code: CsvErrorCode; - [key: string]: any; - - constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]); - } - - type CsvErrorCode = - 'CSV_INVALID_OPTION_BOM' - | 'CSV_INVALID_OPTION_CAST' - | 'CSV_INVALID_OPTION_CAST_DATE' - | 'CSV_INVALID_OPTION_COLUMNS' - | 'CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY' - | 'CSV_INVALID_OPTION_COMMENT' - | 'CSV_INVALID_OPTION_DELIMITER' - | 'CSV_INVALID_OPTION_ON_RECORD' - | 'CSV_INVALID_CLOSING_QUOTE' - | 'INVALID_OPENING_QUOTE' - | 'CSV_INVALID_COLUMN_MAPPING' - | 'CSV_INVALID_ARGUMENT' - | 'CSV_INVALID_COLUMN_DEFINITION' - | 'CSV_MAX_RECORD_SIZE' - | 'CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE' - | 'CSV_QUOTE_NOT_CLOSED' - | 'CSV_INCONSISTENT_RECORD_LENGTH' - | 'CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH' - | 'CSV_OPTION_COLUMNS_MISSING_NAME' + constructor(code: CsvErrorCode, message: string | string[], options?: Options, ...contexts: any[]); } + +declare function parse(input: Buffer | string, options?: Options, callback?: Callback): Parser; +declare function parse(input: Buffer | string, callback?: Callback): Parser; +declare function parse(options?: Options, callback?: Callback): Parser; +declare function parse(callback?: Callback): Parser; + +// export default parse; +export { parse } diff --git a/node_modules/csv-parse/lib/index.js b/node_modules/csv-parse/lib/index.js index 164c171..3ad632d 100644 --- a/node_modules/csv-parse/lib/index.js +++ b/node_modules/csv-parse/lib/index.js @@ -6,1263 +6,116 @@ Please look at the [project documentation](https://csv.js.org/parse/) for additional information. */ -const { Transform } = require('stream') -const ResizeableBuffer = require('./ResizeableBuffer') - -// white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff -const tab = 9 -const nl = 10 // \n, 0x0A in hexadecimal, 10 in decimal -const np = 12 -const cr = 13 // \r, 0x0D in hexadécimal, 13 in decimal -const space = 32 -const boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -} +import { Transform } from 'stream'; +import {is_object} from './utils/is_object.js'; +import {transform} from './api/index.js'; +import {CsvError} from './api/CsvError.js'; class Parser extends Transform { constructor(opts = {}){ - super({...{readableObjectMode: true}, ...opts, encoding: null}) - this.__originalOptions = opts - this.__normalizeOptions(opts) - } - __normalizeOptions(opts){ - const options = {} - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - if(options.encoding === undefined || options.encoding === true){ - options.encoding = 'utf8' - }else if(options.encoding === null || options.encoding === false){ - options.encoding = null - }else if(typeof options.encoding !== 'string' && options.encoding !== null){ - throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ - 'Invalid option encoding:', - 'encoding must be a string or null to return a buffer,', - `got ${JSON.stringify(options.encoding)}` - ], options) - } - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - throw new CsvError('CSV_INVALID_OPTION_BOM', [ - 'Invalid option bom:', 'bom must be true,', - `got ${JSON.stringify(options.bom)}` - ], options) - } - // Normalize option `cast` - let fnCastField = null - if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ - options.cast = undefined - }else if(typeof options.cast === 'function'){ - fnCastField = options.cast - options.cast = true - }else if(options.cast !== true){ - throw new CsvError('CSV_INVALID_OPTION_CAST', [ - 'Invalid option cast:', 'cast must be true or a function,', - `got ${JSON.stringify(options.cast)}` - ], options) - } - // Normalize option `cast_date` - if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ - options.cast_date = false - }else if(options.cast_date === true){ - options.cast_date = function(value){ - const date = Date.parse(value) - return !isNaN(date) ? new Date(date) : value - } - }else{ - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ - 'Invalid option cast_date:', 'cast_date must be true or a function,', - `got ${JSON.stringify(options.cast_date)}` - ], options) - } - // Normalize option `columns` - let fnFirstLineToHeaders = null - if(options.columns === true){ - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined - }else if(typeof options.columns === 'function'){ - fnFirstLineToHeaders = options.columns - options.columns = true - }else if(Array.isArray(options.columns)){ - options.columns = normalizeColumnsArray(options.columns) - }else if(options.columns === undefined || options.columns === null || options.columns === false){ - options.columns = false - }else{ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ - 'Invalid option columns:', - 'expect an array, a function or true,', - `got ${JSON.stringify(options.columns)}` - ], options) - } - // Normalize option `columns_duplicates_to_array` - if(options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false){ - options.columns_duplicates_to_array = false - }else if(options.columns_duplicates_to_array !== true){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'expect an boolean,', - `got ${JSON.stringify(options.columns_duplicates_to_array)}` - ], options) - }else if(options.columns === false){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'the `columns` mode must be activated.' - ], options) - } - // Normalize option `comment` - if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ - options.comment = null - }else{ - if(typeof options.comment === 'string'){ - options.comment = Buffer.from(options.comment, options.encoding) - } - if(!Buffer.isBuffer(options.comment)){ - throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ - 'Invalid option comment:', - 'comment must be a buffer or a string,', - `got ${JSON.stringify(options.comment)}` - ], options) - } - } - // Normalize option `delimiter` - const delimiter_json = JSON.stringify(options.delimiter) - if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter] - if(options.delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - options.delimiter = options.delimiter.map(function(delimiter){ - if(delimiter === undefined || delimiter === null || delimiter === false){ - return Buffer.from(',', options.encoding) - } - if(typeof delimiter === 'string'){ - delimiter = Buffer.from(delimiter, options.encoding) - } - if( !Buffer.isBuffer(delimiter) || delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - return delimiter - }) - // Normalize option `escape` - if(options.escape === undefined || options.escape === true){ - options.escape = Buffer.from('"', options.encoding) - }else if(typeof options.escape === 'string'){ - options.escape = Buffer.from(options.escape, options.encoding) - }else if (options.escape === null || options.escape === false){ - options.escape = null - } - if(options.escape !== null){ - if(!Buffer.isBuffer(options.escape)){ - throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`) - } - } - // Normalize option `from` - if(options.from === undefined || options.from === null){ - options.from = 1 - }else{ - if(typeof options.from === 'string' && /\d+/.test(options.from)){ - options.from = parseInt(options.from) - } - if(Number.isInteger(options.from)){ - if(options.from < 0){ - throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`) - } - }else{ - throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`) - } - } - // Normalize option `from_line` - if(options.from_line === undefined || options.from_line === null){ - options.from_line = 1 - }else{ - if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ - options.from_line = parseInt(options.from_line) - } - if(Number.isInteger(options.from_line)){ - if(options.from_line <= 0){ - throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`) - } - }else{ - throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`) - } - } - // Normalize options `ignore_last_delimiters` - if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ - options.ignore_last_delimiters = false - }else if(typeof options.ignore_last_delimiters === 'number'){ - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters) - if(options.ignore_last_delimiters === 0){ - options.ignore_last_delimiters = false - } - }else if(typeof options.ignore_last_delimiters !== 'boolean'){ - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ - 'Invalid option `ignore_last_delimiters`:', - 'the value must be a boolean value or an integer,', - `got ${JSON.stringify(options.ignore_last_delimiters)}` - ], options) - } - if(options.ignore_last_delimiters === true && options.columns === false){ - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ - 'The option `ignore_last_delimiters`', - 'requires the activation of the `columns` option' - ], options) - } - // Normalize option `info` - if(options.info === undefined || options.info === null || options.info === false){ - options.info = false - }else if(options.info !== true){ - throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`) - } - // Normalize option `max_record_size` - if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ - options.max_record_size = 0 - }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0){ - // Great, nothing to do - }else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ - options.max_record_size = parseInt(options.max_record_size) - }else{ - throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`) - } - // Normalize option `objname` - if(options.objname === undefined || options.objname === null || options.objname === false){ - options.objname = undefined - }else if(Buffer.isBuffer(options.objname)){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty buffer`) - } - if(options.encoding === null){ - // Don't call `toString`, leave objname as a buffer - }else{ - options.objname = options.objname.toString(options.encoding) - } - }else if(typeof options.objname === 'string'){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty string`) - } - // Great, nothing to do - }else{ - throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`) - } - // Normalize option `on_record` - if(options.on_record === undefined || options.on_record === null){ - options.on_record = undefined - }else if(typeof options.on_record !== 'function'){ - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ - 'Invalid option `on_record`:', - 'expect a function,', - `got ${JSON.stringify(options.on_record)}` - ], options) - } - // Normalize option `quote` - if(options.quote === null || options.quote === false || options.quote === ''){ - options.quote = null - }else{ - if(options.quote === undefined || options.quote === true){ - options.quote = Buffer.from('"', options.encoding) - }else if(typeof options.quote === 'string'){ - options.quote = Buffer.from(options.quote, options.encoding) - } - if(!Buffer.isBuffer(options.quote)){ - throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`) - } - } - // Normalize option `raw` - if(options.raw === undefined || options.raw === null || options.raw === false){ - options.raw = false - }else if(options.raw !== true){ - throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`) - } - // Normalize option `record_delimiter` - if(!options.record_delimiter){ - options.record_delimiter = [] - }else if(!Array.isArray(options.record_delimiter)){ - options.record_delimiter = [options.record_delimiter] - } - options.record_delimiter = options.record_delimiter.map( function(rd){ - if(typeof rd === 'string'){ - rd = Buffer.from(rd, options.encoding) - } - return rd - }) - // Normalize option `relax` - if(typeof options.relax === 'boolean'){ - // Great, nothing to do - }else if(options.relax === undefined || options.relax === null){ - options.relax = false - }else{ - throw new Error(`Invalid Option: relax must be a boolean, got ${JSON.stringify(options.relax)}`) - } - // Normalize option `relax_column_count` - if(typeof options.relax_column_count === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count === undefined || options.relax_column_count === null){ - options.relax_column_count = false - }else{ - throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`) - } - if(typeof options.relax_column_count_less === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ - options.relax_column_count_less = false - }else{ - throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`) - } - if(typeof options.relax_column_count_more === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ - options.relax_column_count_more = false - }else{ - throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`) - } - // Normalize option `skip_empty_lines` - if(typeof options.skip_empty_lines === 'boolean'){ - // Great, nothing to do - }else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ - options.skip_empty_lines = false - }else{ - throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`) - } - // Normalize option `skip_lines_with_empty_values` - if(typeof options.skip_lines_with_empty_values === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null){ - options.skip_lines_with_empty_values = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_lines_with_empty_values)}`) - } - // Normalize option `skip_lines_with_error` - if(typeof options.skip_lines_with_error === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_error === undefined || options.skip_lines_with_error === null){ - options.skip_lines_with_error = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_error must be a boolean, got ${JSON.stringify(options.skip_lines_with_error)}`) - } - // Normalize option `rtrim` - if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ - options.rtrim = false - }else if(options.rtrim !== true){ - throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`) - } - // Normalize option `ltrim` - if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ - options.ltrim = false - }else if(options.ltrim !== true){ - throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`) - } - // Normalize option `trim` - if(options.trim === undefined || options.trim === null || options.trim === false){ - options.trim = false - }else if(options.trim !== true){ - throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`) - } - // Normalize options `trim`, `ltrim` and `rtrim` - if(options.trim === true && opts.ltrim !== false){ - options.ltrim = true - }else if(options.ltrim !== true){ - options.ltrim = false - } - if(options.trim === true && opts.rtrim !== false){ - options.rtrim = true - }else if(options.rtrim !== true){ - options.rtrim = false - } - // Normalize option `to` - if(options.to === undefined || options.to === null){ - options.to = -1 - }else{ - if(typeof options.to === 'string' && /\d+/.test(options.to)){ - options.to = parseInt(options.to) - } - if(Number.isInteger(options.to)){ - if(options.to <= 0){ - throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`) - } - }else{ - throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`) - } - } - // Normalize option `to_line` - if(options.to_line === undefined || options.to_line === null){ - options.to_line = -1 - }else{ - if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ - options.to_line = parseInt(options.to_line) - } - if(Number.isInteger(options.to_line)){ - if(options.to_line <= 0){ - throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`) - } - }else{ - throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`) - } - } - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - } - this.options = options - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max( - // Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0, - // Skip if the remaining buffer can be delimiter - ...options.delimiter.map( (delimiter) => delimiter.length), - // Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0, - ), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max(...options.record_delimiter.map( (v) => v.length)), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - } + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; } // Implementation of `Transform._transform` - _transform(buf, encoding, callback){ + _transform(buf, _, callback){ if(this.state.stop === true){ - return - } - const err = this.__parse(buf, false) + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); if(err !== undefined){ - this.state.stop = true + this.state.stop = true; } - callback(err) + callback(err); } // Implementation of `Transform._flush` _flush(callback){ if(this.state.stop === true){ - return - } - const err = this.__parse(undefined, true) - callback(err) - } - // Central parser implementation - __parse(nextBuf, end){ - const {bom, comment, escape, from_line, ltrim, max_record_size, quote, raw, relax, rtrim, skip_empty_lines, to, to_line} = this.options - let {record_delimiter} = this.options - const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state - let buf - if(previousBuf === undefined){ - if(nextBuf === undefined){ - // Handle empty string - this.push(null) - return - }else{ - buf = nextBuf - } - }else if(previousBuf !== undefined && nextBuf === undefined){ - buf = previousBuf - }else{ - buf = Buffer.concat([previousBuf, nextBuf]) - } - // Handle UTF BOM - if(bomSkipped === false){ - if(bom === false){ - this.state.bomSkipped = true - }else if(buf.length < 3){ - // No enough data - if(end === false){ - // Wait for more data - this.state.previousBuf = buf - return - } - }else{ - for(let encoding in boms){ - if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ - // Skip BOM - let bomLength = boms[encoding].length - this.state.bufBytesStart += bomLength - buf = buf.slice(bomLength) - // Renormalize original options with the new encoding - this.__normalizeOptions({...this.__originalOptions, encoding: encoding}) - break - } - } - this.state.bomSkipped = true - } - } - const bufLen = buf.length - let pos - for(pos = 0; pos < bufLen; pos++){ - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if(this.__needMoreData(pos, bufLen, end)){ - break - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - if(to_line !== -1 && this.info.lines > to_line){ - this.state.stop = true - this.push(null) - return - } - // Auto discovery of record_delimiter, unix, mac and windows supported - if(this.state.quoting === false && record_delimiter.length === 0){ - const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos) - if(record_delimiterCount){ - record_delimiter = this.options.record_delimiter - } - } - const chr = buf[pos] - if(raw === true){ - rawBuffer.append(chr) - } - if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false ){ - this.state.wasRowDelimiter = true - } - // Previous char was a valid escape char - // treat the current char as a regular char - if(this.state.escaping === true){ - this.state.escaping = false - }else{ - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ - if(escapeIsQuote){ - if(this.__isQuote(buf, pos+escape.length)){ - this.state.escaping = true - pos += escape.length - 1 - continue - } - }else{ - this.state.escaping = true - pos += escape.length - 1 - continue - } - } - // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - if(this.state.commenting === false && this.__isQuote(buf, pos)){ - if(this.state.quoting === true){ - const nextChr = buf[pos+quote.length] - const isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr) - const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr) - const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr) - const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length) - // Escape a quote - // Treat next char as a regular character - if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ - pos += escape.length - 1 - }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ - this.state.quoting = false - this.state.wasQuoting = true - pos += quote.length - 1 - continue - }else if(relax === false){ - const err = this.__error( - new CsvError('CSV_INVALID_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - `got "${String.fromCharCode(nextChr)}"`, - `at line ${this.info.lines}`, - 'instead of delimiter, record delimiter, trimable character', - '(if activated) or comment', - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - this.state.quoting = false - this.state.wasQuoting = true - this.state.field.prepend(quote) - pos += quote.length - 1 - } - }else{ - if(this.state.field.length !== 0){ - // In relax mode, treat opening quote preceded by chrs as regular - if( relax === false ){ - const err = this.__error( - new CsvError('INVALID_OPENING_QUOTE', [ - 'Invalid Opening Quote:', - `a quote is found inside a field at line ${this.info.lines}`, - ], this.options, this.__infoField(), { - field: this.state.field, - }) - ) - if(err !== undefined) return err - } - }else{ - this.state.quoting = true - pos += quote.length - 1 - continue - } - } - } - if(this.state.quoting === false){ - let recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos) - if(recordDelimiterLength !== 0){ - // Do not emit comments which take a full line - const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) - if(skipCommentLine){ - this.info.comment_lines++ - // Skip full comment line - }else{ - // Activate records emition if above from_line - if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ - this.state.enabled = true - this.__resetField() - this.__resetRecord() - pos += recordDelimiterLength - 1 - continue - } - // Skip if line is empty and skip_empty_lines activated - if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ - this.info.empty_lines++ - pos += recordDelimiterLength - 1 - continue - } - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - if(to !== -1 && this.info.records >= to){ - this.state.stop = true - this.push(null) - return - } - } - this.state.commenting = false - pos += recordDelimiterLength - 1 - continue - } - if(this.state.commenting){ - continue - } - const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr) - if(commentCount !== 0){ - this.state.commenting = true - continue - } - let delimiterLength = this.__isDelimiter(buf, pos, chr) - if(delimiterLength !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - pos += delimiterLength - 1 - continue - } - } - } - if(this.state.commenting === false){ - if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ - const err = this.__error( - new CsvError('CSV_MAX_RECORD_SIZE', [ - 'Max Record Size:', - 'record exceed the maximum number of tolerated bytes', - `of ${max_record_size}`, - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr) - // rtrim in non quoting is handle in __onField - const rappend = rtrim === false || this.state.wasQuoting === false - if( lappend === true && rappend === true ){ - this.state.field.append(chr) - }else if(rtrim === true && !this.__isCharTrimable(chr)){ - const err = this.__error( - new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - 'found non trimable byte after quote', - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - if(end === true){ - // Ensure we are not ending in a quoting state - if(this.state.quoting === true){ - const err = this.__error( - new CsvError('CSV_QUOTE_NOT_CLOSED', [ - 'Quote Not Closed:', - `the parsing is finished with an opening quote at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - // Skip last line if it has no characters - if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - }else if(this.state.wasRowDelimiter === true){ - this.info.empty_lines++ - }else if(this.state.commenting === true){ - this.info.comment_lines++ - } - } - }else{ - this.state.bufBytesStart += pos - this.state.previousBuf = buf.slice(pos) - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - } - __onRecord(){ - const {columns, columns_duplicates_to_array, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_lines_with_empty_values} = this.options - const {enabled, record} = this.state - if(enabled === false){ - return this.__resetRecord() - } - // Convert the first line into column names - const recordLength = record.length - if(columns === true){ - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - return this.__firstLineToColumns(record) - } - if(columns === false && this.info.records === 0){ - this.state.expectedRecordLength = recordLength - } - if(recordLength !== this.state.expectedRecordLength){ - const err = columns === false ? - // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', [ - 'Invalid Record Length:', - `expect ${this.state.expectedRecordLength},`, - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - : - // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', [ - 'Invalid Record Length:', - `columns length is ${columns.length},`, // rename columns - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - if(relax_column_count === true || - (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || - (relax_column_count_more === true && recordLength > this.state.expectedRecordLength) ){ - this.info.invalid_field_length++ - this.state.error = err - // Error is undefined with skip_lines_with_error - }else{ - const finalErr = this.__error(err) - if(finalErr) return finalErr - } - } - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - if(this.state.recordHasError === true){ - this.__resetRecord() - this.state.recordHasError = false - return - } - this.info.records++ - if(from === 1 || this.info.records >= from){ - // With columns, records are object - if(columns !== false){ - const obj = {} - // Transform record array to an object - for(let i = 0, l = record.length; i < l; i++){ - if(columns[i] === undefined || columns[i].disabled) continue - // Turn duplicate columns into an array - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]) - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]] - } - } else { - obj[columns[i].name] = record[i] - } - } - const {objname} = this.options - // Without objname (default) - if(objname === undefined){ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: obj}, - (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), - (info === true ? {info: this.__infoRecord()}: {}) - )) - if(err){ - return err - } - }else{ - const err = this.__push(obj) - if(err){ - return err - } - } - // With objname (default) - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: [obj[objname], obj]}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push([obj[objname], obj]) - if(err){ - return err - } - } - } - // Without columns, records are array - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: record}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push(record) - if(err){ - return err - } - } - } - } - this.__resetRecord() - } - __firstLineToColumns(record){ - const {firstLineToHeaders} = this.state - try{ - const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record) - if(!Array.isArray(headers)){ - return this.__error( - new CsvError('CSV_INVALID_COLUMN_MAPPING', [ - 'Invalid Column Mapping:', - 'expect an array from column function,', - `got ${JSON.stringify(headers)}` - ], this.options, this.__infoField(), { - headers: headers, - }) - ) - } - const normalizedHeaders = normalizeColumnsArray(headers) - this.state.expectedRecordLength = normalizedHeaders.length - this.options.columns = normalizedHeaders - this.__resetRecord() - return - }catch(err){ - return err - } - } - __resetRecord(){ - if(this.options.raw === true){ - this.state.rawBuffer.reset() - } - this.state.error = undefined - this.state.record = [] - this.state.record_length = 0 - } - __onField(){ - const {cast, encoding, rtrim, max_record_size} = this.options - const {enabled, wasQuoting} = this.state - // Short circuit for the from_line options - if(enabled === false){ - return this.__resetField() - } - let field = this.state.field.toString(encoding) - if(rtrim === true && wasQuoting === false){ - field = field.trimRight() - } - if(cast === true){ - const [err, f] = this.__cast(field) - if(err !== undefined) return err - field = f - } - this.state.record.push(field) - // Increment record length if record size must not exceed a limit - if(max_record_size !== 0 && typeof field === 'string'){ - this.state.record_length += field.length - } - this.__resetField() - } - __resetField(){ - this.state.field.reset() - this.state.wasQuoting = false - } - __push(record){ - const {on_record} = this.options - if(on_record !== undefined){ - const info = this.__infoRecord() - try{ - record = on_record.call(null, record, info) - }catch(err){ - return err - } - if(record === undefined || record === null){ return } - } - this.push(record) - } - // Return a tuple with the error and the casted value - __cast(field){ - const {columns, relax_column_count} = this.options - const isColumns = Array.isArray(columns) - // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - if( isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length ){ - return [undefined, undefined] - } - if(this.state.castField !== null){ - try{ - const info = this.__infoField() - return [undefined, this.state.castField.call(null, field, info)] - }catch(err){ - return [err] - } - } - if(this.__isFloat(field)){ - return [undefined, parseFloat(field)] - }else if(this.options.cast_date !== false){ - const info = this.__infoField() - return [undefined, this.options.cast_date.call(null, field, info)] - } - return [undefined, field] - } - // Helper to test if a character is a space or a line delimiter - __isCharTrimable(chr){ - return chr === space || chr === tab || chr === cr || chr === nl || chr === np - } - // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - __isFloat(value){ - return (value - parseFloat( value ) + 1) >= 0 // Borrowed from jquery - } - __compareBytes(sourceBuf, targetBuf, targetPos, firstByte){ - if(sourceBuf[0] !== firstByte) return 0 - const sourceLength = sourceBuf.length - for(let i = 1; i < sourceLength; i++){ - if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0 - } - return sourceLength - } - __needMoreData(i, bufLen, end){ - if(end) return false - const {quote} = this.options - const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state - const numOfCharLeft = bufLen - i - 1 - const requiredLength = Math.max( - needMoreDataSize, - // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, - // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? (quote.length + recordDelimiterMaxLength) : 0, - ) - return numOfCharLeft < requiredLength - } - __isDelimiter(buf, pos, chr){ - const {delimiter, ignore_last_delimiters} = this.options - if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ - return 0 - }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ - return 0 - } - loop1: for(let i = 0; i < delimiter.length; i++){ - const del = delimiter[i] - if(del[0] === chr){ - for(let j = 1; j < del.length; j++){ - if(del[j] !== buf[pos+j]) continue loop1 - } - return del.length - } - } - return 0 - } - __isRecordDelimiter(chr, buf, pos){ - const {record_delimiter} = this.options - const recordDelimiterLength = record_delimiter.length - loop1: for(let i = 0; i < recordDelimiterLength; i++){ - const rd = record_delimiter[i] - const rdLength = rd.length - if(rd[0] !== chr){ - continue - } - for(let j = 1; j < rdLength; j++){ - if(rd[j] !== buf[pos+j]){ - continue loop1 - } - } - return rd.length - } - return 0 - } - __isEscape(buf, pos, chr){ - const {escape} = this.options - if(escape === null) return false - const l = escape.length - if(escape[0] === chr){ - for(let i = 0; i < l; i++){ - if(escape[i] !== buf[pos+i]){ - return false - } - } - return true - } - return false - } - __isQuote(buf, pos){ - const {quote} = this.options - if(quote === null) return false - const l = quote.length - for(let i = 0; i < l; i++){ - if(quote[i] !== buf[pos+i]){ - return false - } - } - return true - } - __autoDiscoverRecordDelimiter(buf, pos){ - const {encoding} = this.options - const chr = buf[pos] - if(chr === cr){ - if(buf[pos+1] === nl){ - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)) - this.state.recordDelimiterMaxLength = 2 - return 2 - }else{ - this.options.record_delimiter.push(Buffer.from('\r', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - }else if(chr === nl){ - this.options.record_delimiter.push(Buffer.from('\n', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - return 0 - } - __error(msg){ - const {skip_lines_with_error} = this.options - const err = typeof msg === 'string' ? new Error(msg) : msg - if(skip_lines_with_error){ - this.state.recordHasError = true - this.emit('skip', err) - return undefined - }else{ - return err - } - } - __infoDataSet(){ - return { - ...this.info, - columns: this.options.columns - } - } - __infoRecord(){ - const {columns} = this.options - return { - ...this.__infoDataSet(), - error: this.state.error, - header: columns === true, - index: this.state.record.length, - } - } - __infoField(){ - const {columns} = this.options - const isColumns = Array.isArray(columns) - return { - ...this.__infoRecord(), - column: isColumns === true ? - ( columns.length > this.state.record.length ? - columns[this.state.record.length].name : - null - ) : - this.state.record.length, - quoting: this.state.wasQuoting, + return; } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); } } const parse = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; if(data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; }else if(callback === undefined && type === 'function'){ - callback = argument + callback = argument; }else{ throw new CsvError('CSV_INVALID_ARGUMENT', [ 'Invalid argument:', `got ${JSON.stringify(argument)} at index ${i}` - ], options || {}) + ], options || {}); } } - const parser = new Parser(options) + const parser = new Parser(options); if(callback){ - const records = options === undefined || options.objname === undefined ? [] : {} + const records = options === undefined || options.objname === undefined ? [] : {}; parser.on('readable', function(){ - let record + let record; while((record = this.read()) !== null){ if(options === undefined || options.objname === undefined){ - records.push(record) + records.push(record); }else{ - records[record[0]] = record[1] + records[record[0]] = record[1]; } } - }) + }); parser.on('error', function(err){ - callback(err, undefined, parser.__infoDataSet()) - }) + callback(err, undefined, parser.api.__infoDataSet()); + }); parser.on('end', function(){ - callback(undefined, records, parser.__infoDataSet()) - }) + callback(undefined, records, parser.api.__infoDataSet()); + }); } if(data !== undefined){ - // Give a chance for events to be registered later + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate if(typeof setImmediate === 'function'){ - setImmediate(function(){ - parser.write(data) - parser.end() - }) + setImmediate(writer); }else{ - parser.write(data) - parser.end() + setTimeout(writer, 0); } } - return parser -} - -class CsvError extends Error { - constructor(code, message, options, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)) - } - } - } -} - -parse.Parser = Parser - -parse.CsvError = CsvError + return parser; +}; -module.exports = parse - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -const isObject = function(obj){ - return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) -} - -const isRecordEmpty = function(record){ - return record.every( (field) => field == null || field.toString && field.toString().trim() === '' ) -} - -const normalizeColumnsArray = function(columns){ - const normalizedColumns = []; - for(let i = 0, l = columns.length; i < l; i++){ - const column = columns[i] - if(column === undefined || column === null || column === false){ - normalizedColumns[i] = { disabled: true } - }else if(typeof column === 'string'){ - normalizedColumns[i] = { name: column } - }else if(isObject(column)){ - if(typeof column.name !== 'string'){ - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ - 'Option columns missing name:', - `property "name" is required at position ${i}`, - 'when column is an object literal' - ]) - } - normalizedColumns[i] = column - }else{ - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ - 'Invalid column definition:', - 'expect a string or a literal object,', - `got ${JSON.stringify(column)} at position ${i}` - ]) - } - } - return normalizedColumns; -} +// export default parse +export { parse, Parser, CsvError }; diff --git a/node_modules/csv-parse/lib/stream.js b/node_modules/csv-parse/lib/stream.js new file mode 100644 index 0000000..3aba296 --- /dev/null +++ b/node_modules/csv-parse/lib/stream.js @@ -0,0 +1,27 @@ + +import { + TransformStream, +} from 'node:stream/web'; +import {transform} from './api/index.js'; + +const parse = (opts) => { + const api = transform(opts); + return new TransformStream({ + async transform(chunk, controller) { + api.parse(chunk, false, (record) => { + controller.enqueue(record); + }, () => { + controller.close(); + }); + }, + async flush(controller){ + api.parse(undefined, true, (record) => { + controller.enqueue(record); + }, () => { + controller.close(); + }); + } + }); +}; + +export {parse}; diff --git a/node_modules/csv-parse/lib/sync.d.ts b/node_modules/csv-parse/lib/sync.d.ts index 7886698..b507e8b 100644 --- a/node_modules/csv-parse/lib/sync.d.ts +++ b/node_modules/csv-parse/lib/sync.d.ts @@ -1,6 +1,11 @@ -import * as csvParse from './index'; -export = parse; +import { Options } from './index.js'; -declare function parse(input: Buffer | string, options?: csvParse.Options): any; -declare namespace parse {} \ No newline at end of file +declare function parse(input: Buffer | string, options?: Options): any; +// export default parse; +export { parse }; + +export { + CastingContext, CastingFunction, CastingDateFunction, + ColumnOption, Options, Info, CsvErrorCode, CsvError +} from './index.js'; diff --git a/node_modules/csv-parse/lib/sync.js b/node_modules/csv-parse/lib/sync.js index 3f592de..4229ea3 100644 --- a/node_modules/csv-parse/lib/sync.js +++ b/node_modules/csv-parse/lib/sync.js @@ -1,25 +1,27 @@ -const parse = require('.') +import {CsvError, transform} from './api/index.js'; -module.exports = function(data, options={}){ +const parse = function(data, opts={}){ if(typeof data === 'string'){ - data = Buffer.from(data) + data = Buffer.from(data); } - const records = options && options.objname ? {} : [] - const parser = new parse.Parser(options) - parser.push = function(record){ - if(record === null){ - return - } - if(options.objname === undefined) - records.push(record) + const records = opts && opts.objname ? {} : []; + const parser = transform(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); else{ - records[record[0]] = record[1] + records[record[0]] = record[1]; } - } - const err1 = parser.__parse(data, false) - if(err1 !== undefined) throw err1 - const err2 = parser.__parse(undefined, true) - if(err2 !== undefined) throw err2 - return records -} + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; +}; + +// export default parse +export { parse }; +export { CsvError }; diff --git a/node_modules/csv-parse/lib/utils/ResizeableBuffer.js b/node_modules/csv-parse/lib/utils/ResizeableBuffer.js new file mode 100644 index 0000000..4979e91 --- /dev/null +++ b/node_modules/csv-parse/lib/utils/ResizeableBuffer.js @@ -0,0 +1,64 @@ + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(Buffer.isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else{ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else{ + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +export default ResizeableBuffer; diff --git a/node_modules/csv-parse/lib/utils/is_object.js b/node_modules/csv-parse/lib/utils/is_object.js new file mode 100644 index 0000000..4f95846 --- /dev/null +++ b/node_modules/csv-parse/lib/utils/is_object.js @@ -0,0 +1,6 @@ + +const is_object = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +export {is_object}; diff --git a/node_modules/csv-parse/lib/utils/underscore.js b/node_modules/csv-parse/lib/utils/underscore.js new file mode 100644 index 0000000..453816b --- /dev/null +++ b/node_modules/csv-parse/lib/utils/underscore.js @@ -0,0 +1,8 @@ + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +export {underscore}; diff --git a/node_modules/csv-parse/package.json b/node_modules/csv-parse/package.json index 4239bfb..dc92b34 100644 --- a/node_modules/csv-parse/package.json +++ b/node_modules/csv-parse/package.json @@ -1,5 +1,5 @@ { - "version": "4.16.3", + "version": "5.5.5", "name": "csv-parse", "description": "CSV parsing implementing the Node.js `stream.Transform` API", "keywords": [ @@ -8,21 +8,10 @@ "parser", "convert", "tsv", - "stream" + "stream", + "backend", + "frontend" ], - "coffeelintConfig": { - "indentation": { - "level": "error", - "value": 2 - }, - "line_endings": { - "level": "error", - "value": "unix" - }, - "max_line_length": { - "level": "ignore" - } - }, "author": "David Worms (https://www.adaltas.com)", "contributors": [ "David Worms (https://www.adaltas.com)", @@ -42,58 +31,112 @@ "Joe Eaves (https://github.com/Joeasaurus)", "Mark Stosberg (https://github.com/markstos)" ], - "license": "MIT", - "repository": { - "type": "git", - "url": "https://github.com/wdavidw/node-csv-parse" + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./sync": { + "import": { + "types": "./lib/sync.d.ts", + "default": "./lib/sync.js" + }, + "require": { + "types": "./dist/cjs/sync.d.cts", + "default": "./dist/cjs/sync.cjs" + } + }, + "./browser/esm": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "./browser/esm/sync": { + "types": "./dist/esm/sync.d.ts", + "default": "./dist/esm/sync.js" + } }, - "homepage": "https://csv.js.org/parse/", "devDependencies": { - "@babel/cli": "^7.14.8", - "@babel/core": "^7.15.0", - "@babel/preset-env": "^7.15.0", - "@types/mocha": "^9.0.0", - "@types/node": "^16.7.8", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "coffeescript": "^2.5.1", - "csv-generate": "^3.4.3", + "@rollup/plugin-eslint": "^9.0.4", + "@rollup/plugin-node-resolve": "^15.2.1", + "@types/mocha": "^10.0.1", + "@types/node": "^20.5.6", + "coffeelint": "^2.1.0", + "coffeescript": "^2.7.0", + "csv-generate": "^4.4.0", "csv-spectrum": "^1.0.0", - "each": "^1.2.2", - "eslint": "^7.32.0", - "express": "^4.17.1", - "mocha": "^9.1.1", + "each": "^2.4.0", + "eslint": "^8.47.0", + "mocha": "^10.2.0", "pad": "^3.2.0", + "rollup": "^3.28.1", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", "should": "^13.2.3", - "stream-transform": "^2.1.3", - "ts-node": "^10.2.1", - "typescript": "^4.4.2" + "stream-transform": "^3.3.1", + "ts-node": "^10.9.1", + "typescript": "^5.2.2" }, "files": [ - "/lib" + "dist", + "lib" ], - "main": "./lib", + "homepage": "https://csv.js.org/parse", + "license": "MIT", + "main": "./dist/cjs/index.cjs", "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "coffeescript/register", - "ts-node/register" - ], "inline-diffs": true, - "timeout": 40000, + "loader": "./test/loaders/all.js", + "recursive": true, "reporter": "spec", - "recursive": true + "require": [ + "should" + ], + "throw-deprecation": true, + "timeout": 40000 + }, + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-csv.git", + "directory": "packages/csv-parse" }, "scripts": { - "build:babel": "cd lib && babel *.js -d es5 && cd ..", - "build:browserify": "browserify lib/index.js --transform babelify --standalone parse > lib/browser/index.js && browserify lib/sync.js --transform babelify --standalone parse > lib/browser/sync.js", - "build": "npm run build:babel && npm run build:browserify", - "preversion": "cp lib/*.ts lib/es5 && git add lib/es5/*.ts", + "build": "npm run build:rollup && npm run build:ts", + "build:rollup": "npx rollup -c", + "build:ts": "cp lib/index.d.ts dist/cjs/index.d.cts && cp lib/sync.d.ts dist/cjs/sync.d.cts && cp lib/*.ts dist/esm", + "postbuild:ts": "find dist/cjs -name '*.d.cts' -exec sh -c \"sed -i \"s/\\.js'/\\.cjs'/g\" {} || sed -i '' \"s/\\.js'/\\.cjs'/g\" {}\" \\;", + "lint": "npm run lint:lib && npm run lint:samples && npm run lint:test", + "postlint": "tsc --noEmit true", + "lint:lib": "eslint --fix lib/*.js", + "lint:samples": "eslint --fix samples/*.js", + "lint:test": "coffeelint --fix test/*.coffee", + "preversion": "npm run build && git add dist", "pretest": "npm run build", - "lint": "eslint lib/*.js", - "test": "npm run lint && TS_NODE_COMPILER_OPTIONS='{\"strictNullChecks\":true}' mocha test/**/*.{coffee,ts}" + "test": "mocha 'test/**/*.{coffee,ts}'", + "test:legacy": "mocha --ignore test/api.web_stream.coffee --ignore test/api.stream.finished.coffee --ignore test/api.stream.iterator.coffee --loader=./test/loaders/legacy/all.js 'test/**/*.{coffee,ts}'" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "typesVersions": { + "*": { + ".": [ + "dist/esm/index.d.ts" + ], + "sync": [ + "dist/esm/sync.d.ts" + ], + "browser/esm": [ + "dist/esm/index.d.ts" + ], + "browser/esm/sync": [ + "dist/esm/sync.d.ts" + ] + } }, - "types": "./lib/index.d.ts", - "gitHead": "0fd5209b6862655c384cda052abf38019b959e70" + "gitHead": "410e7b172ce19e975825fcc95dbcfc0340f75af2" } diff --git a/node_modules/csv-stringify/README.md b/node_modules/csv-stringify/README.md index b49f374..f42e6f5 100644 --- a/node_modules/csv-stringify/README.md +++ b/node_modules/csv-stringify/README.md @@ -1,7 +1,11 @@ -[![Build Status](https://api.travis-ci.org/adaltas/node-csv-stringify.svg)](https://travis-ci.org/#!/adaltas/node-csv-stringify) [![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) [![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) +# CSV stringifier for Node.js and the web -This package is a stringifier converting records into a CSV text and +[![Build Status](https://img.shields.io/github/actions/workflow/status/adaltas/node-csv/nodejs.yml?branch=master)](https://github.com/adaltas/node-csv/actions) +[![NPM](https://img.shields.io/npm/dm/csv-stringify)](https://www.npmjs.com/package/csv-stringify) +[![NPM](https://img.shields.io/npm/v/csv-stringify)](https://www.npmjs.com/package/csv-stringify) + +The [`csv-stringify` package](https://csv.js.org/stringify/) is a stringifier converting records into a CSV text and implementing the Node.js [`stream.Transform` API](https://nodejs.org/api/stream.html). It also provides the easier synchronous and callback-based APIs for conveniency. It is both extremely easy @@ -10,10 +14,10 @@ data sets by a large community. ## Documentation -* [Project homepage](http://csv.js.org/stringify/) -* [API](http://csv.js.org/stringify/api/) -* [Options](http://csv.js.org/stringify/options/) -* [Examples](http://csv.js.org/stringify/examples/) +* [Project homepage](https://csv.js.org/stringify/) +* [API](https://csv.js.org/stringify/api/) +* [Options](https://csv.js.org/stringify/options/) +* [Examples](https://csv.js.org/stringify/examples/) ## Main features @@ -28,22 +32,24 @@ data sets by a large community. ## Usage -The module is built on the Node.js Stream API. For the sake of simplicity, a -simple callback API is also provided. To give you a quick look, here's an -example of the callback API: - -```javascript -const stringify = require('csv-stringify') -const assert = require('assert') -// import stringify from 'csv-stringify' -// import assert from 'assert/strict' - -const input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ] -stringify(input, function(err, output) { - const expected = '1,2,3,4\na,b,c,d\n' - assert.strictEqual(output, expected, `output.should.eql ${expected}`) - console.log("Passed.", output) -}) +Run `npm install csv` to install the full CSV module or run `npm install csv-stringify` if you are only interested by the CSV stringifier. + +The module is built on the Node.js Stream API. Use the callback and sync APIs for simplicity or the stream based API for scalability. + +## Example + +The [API](https://csv.js.org/stringify/api/) is available in multiple flavors. This example illustrates the sync API. + +```js +import { stringify } from 'csv-stringify/sync'; +import assert from 'assert'; + +const output = stringify([ + [ '1', '2', '3', '4' ], + [ 'a', 'b', 'c', 'd' ] +]); + +assert.equal(output, '1,2,3,4\na,b,c,d\n'); ``` ## Development @@ -63,9 +69,11 @@ view the tested Node.js version. ## Contributors +The project is sponsored by [Adaltas](https://www.adaltas.com), an Big Data consulting firm based in Paris, France. + * David Worms: [csv_home]: https://github.com/adaltas/node-csv [stream_transform]: http://nodejs.org/api/stream.html#stream_class_stream_transform -[examples]: http://csv.js.org/stringify/examples/ +[examples]: https://csv.js.org/stringify/examples/ [csv]: https://github.com/adaltas/node-csv diff --git a/node_modules/csv-stringify/dist/cjs/index.cjs b/node_modules/csv-stringify/dist/cjs/index.cjs new file mode 100644 index 0000000..4d8e91d --- /dev/null +++ b/node_modules/csv-stringify/dist/cjs/index.cjs @@ -0,0 +1,676 @@ +'use strict'; + +var stream = require('stream'); + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +class Stringifier extends stream.Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } +} + +const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; +}; + +exports.CsvError = CsvError; +exports.Stringifier = Stringifier; +exports.stringify = stringify; diff --git a/node_modules/csv-stringify/dist/cjs/index.d.cts b/node_modules/csv-stringify/dist/cjs/index.d.cts new file mode 100644 index 0000000..4c28ef9 --- /dev/null +++ b/node_modules/csv-stringify/dist/cjs/index.d.cts @@ -0,0 +1,125 @@ +/// + +import * as stream from "stream"; + +export type Callback = (err: Error | undefined, output: string) => void +export type RecordDelimiter = string | Buffer | 'unix' | 'mac' | 'windows' | 'ascii' | 'unicode' + +export type CastReturnObject = { value: string } & Pick< + Options, + | 'delimiter' + | 'escape' + | 'quote' + | 'quoted' + | 'quoted_empty' + | 'quoted_string' + | 'quoted_match' + | 'record_delimiter' +> + +export type Cast = ( + value: T, + context: CastingContext +) => string | CastReturnObject; + +export type PlainObject = Record +export type Input = any[] +export interface ColumnOption { + key: string + header?: string +} +export interface CastingContext { + readonly column?: number | string; + readonly header: boolean; + readonly index: number; + readonly records: number; +} +export interface Options extends stream.TransformOptions { + /** + * Prepend the byte order mark (BOM) to the output stream. + */ + bom?: boolean + /** + * Key-value object which defines custom cast for certain data types + */ + cast?: { + boolean?: Cast + date?: Cast + number?: Cast + bigint?: Cast + /** + * Custom formatter for generic object values + */ + object?: Cast> + string?: Cast + } + /** + * List of fields, applied when `transform` returns an object + * order matters + * read the transformer documentation for additionnal information + * columns are auto discovered in the first record when the user write objects + * can refer to nested properties of the input JSON + * see the "header" option on how to print columns names on the first line + */ + columns?: string[] | PlainObject | ColumnOption[] + /** + * Set the field delimiter, one character only, defaults to a comma. + */ + delimiter?: string | Buffer + /** + * Add the value of "options.RecordDelimiter" on the last line, default to true. + */ + eof?: boolean + /** + * Defaults to the escape read option. + */ + escape?: string | Buffer + /** + * Display the column names on the first line if the columns option is provided or discovered. + */ + header?: boolean + /** + * The quote characters, defaults to the ", an empty quote value will preserve the original field. + */ + quote?: string | Buffer | boolean + /** + * Boolean, default to false, quote all the non-empty fields even if not required. + */ + quoted?: boolean + + /** + * Boolean, no default, quote empty fields and overrides `quoted_string` on empty strings when defined. + */ + quoted_empty?: boolean + /** + * String or RegExp, no default, quote all fields matching a regular expression. + */ + quoted_match?: string | RegExp | (string | RegExp)[] + /** + * Boolean, default to false, quote all fields of type string even if not required. + */ + quoted_string?: boolean + /** + * String used to delimit record rows or a special value + * special values are 'unix', 'mac', 'windows', 'ascii', 'unicode' + * defaults to '\n'. + */ + record_delimiter?: RecordDelimiter + /** + * Boolean, default to false, if true, fields that begin with `=`, `+`, `-`, `@`, `\t`, or `\r` will be prepended with a `'` to protected agains csv injection attacks + */ + escape_formulas?: boolean +} + +export class Stringifier extends stream.Transform { + constructor(options: Options) + readonly options: Options +} + +declare function stringify(callback?: Callback): Stringifier +declare function stringify(options: Options, callback?: Callback): Stringifier +declare function stringify(input: Input, callback?: Callback): Stringifier +declare function stringify(input: Input, options?: Options, callback?: Callback): Stringifier + +// export default stringify +export { stringify } diff --git a/node_modules/csv-stringify/dist/cjs/sync.cjs b/node_modules/csv-stringify/dist/cjs/sync.cjs new file mode 100644 index 0000000..a92b057 --- /dev/null +++ b/node_modules/csv-stringify/dist/cjs/sync.cjs @@ -0,0 +1,598 @@ +'use strict'; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); +}; + +exports.stringify = stringify; diff --git a/node_modules/csv-stringify/dist/cjs/sync.d.cts b/node_modules/csv-stringify/dist/cjs/sync.d.cts new file mode 100644 index 0000000..98699bd --- /dev/null +++ b/node_modules/csv-stringify/dist/cjs/sync.d.cts @@ -0,0 +1,12 @@ + +import { Input, Options } from './index.cjs' + +declare function stringify(input: Input, options?: Options): string + +// export default stringify; +export { stringify }; + +export { + RecordDelimiter, Cast, PlainObject, Input, ColumnOption, CastingContext, + Options +} from './index.cjs'; diff --git a/node_modules/csv-stringify/dist/esm/index.d.ts b/node_modules/csv-stringify/dist/esm/index.d.ts new file mode 100644 index 0000000..4c28ef9 --- /dev/null +++ b/node_modules/csv-stringify/dist/esm/index.d.ts @@ -0,0 +1,125 @@ +/// + +import * as stream from "stream"; + +export type Callback = (err: Error | undefined, output: string) => void +export type RecordDelimiter = string | Buffer | 'unix' | 'mac' | 'windows' | 'ascii' | 'unicode' + +export type CastReturnObject = { value: string } & Pick< + Options, + | 'delimiter' + | 'escape' + | 'quote' + | 'quoted' + | 'quoted_empty' + | 'quoted_string' + | 'quoted_match' + | 'record_delimiter' +> + +export type Cast = ( + value: T, + context: CastingContext +) => string | CastReturnObject; + +export type PlainObject = Record +export type Input = any[] +export interface ColumnOption { + key: string + header?: string +} +export interface CastingContext { + readonly column?: number | string; + readonly header: boolean; + readonly index: number; + readonly records: number; +} +export interface Options extends stream.TransformOptions { + /** + * Prepend the byte order mark (BOM) to the output stream. + */ + bom?: boolean + /** + * Key-value object which defines custom cast for certain data types + */ + cast?: { + boolean?: Cast + date?: Cast + number?: Cast + bigint?: Cast + /** + * Custom formatter for generic object values + */ + object?: Cast> + string?: Cast + } + /** + * List of fields, applied when `transform` returns an object + * order matters + * read the transformer documentation for additionnal information + * columns are auto discovered in the first record when the user write objects + * can refer to nested properties of the input JSON + * see the "header" option on how to print columns names on the first line + */ + columns?: string[] | PlainObject | ColumnOption[] + /** + * Set the field delimiter, one character only, defaults to a comma. + */ + delimiter?: string | Buffer + /** + * Add the value of "options.RecordDelimiter" on the last line, default to true. + */ + eof?: boolean + /** + * Defaults to the escape read option. + */ + escape?: string | Buffer + /** + * Display the column names on the first line if the columns option is provided or discovered. + */ + header?: boolean + /** + * The quote characters, defaults to the ", an empty quote value will preserve the original field. + */ + quote?: string | Buffer | boolean + /** + * Boolean, default to false, quote all the non-empty fields even if not required. + */ + quoted?: boolean + + /** + * Boolean, no default, quote empty fields and overrides `quoted_string` on empty strings when defined. + */ + quoted_empty?: boolean + /** + * String or RegExp, no default, quote all fields matching a regular expression. + */ + quoted_match?: string | RegExp | (string | RegExp)[] + /** + * Boolean, default to false, quote all fields of type string even if not required. + */ + quoted_string?: boolean + /** + * String used to delimit record rows or a special value + * special values are 'unix', 'mac', 'windows', 'ascii', 'unicode' + * defaults to '\n'. + */ + record_delimiter?: RecordDelimiter + /** + * Boolean, default to false, if true, fields that begin with `=`, `+`, `-`, `@`, `\t`, or `\r` will be prepended with a `'` to protected agains csv injection attacks + */ + escape_formulas?: boolean +} + +export class Stringifier extends stream.Transform { + constructor(options: Options) + readonly options: Options +} + +declare function stringify(callback?: Callback): Stringifier +declare function stringify(options: Options, callback?: Callback): Stringifier +declare function stringify(input: Input, callback?: Callback): Stringifier +declare function stringify(input: Input, options?: Options, callback?: Callback): Stringifier + +// export default stringify +export { stringify } diff --git a/node_modules/csv-stringify/dist/esm/index.js b/node_modules/csv-stringify/dist/esm/index.js new file mode 100644 index 0000000..5e161de --- /dev/null +++ b/node_modules/csv-stringify/dist/esm/index.js @@ -0,0 +1,5796 @@ +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } +} + +const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; +}; + +export { CsvError, Stringifier, stringify }; diff --git a/node_modules/csv-stringify/dist/esm/sync.d.ts b/node_modules/csv-stringify/dist/esm/sync.d.ts new file mode 100644 index 0000000..3814c21 --- /dev/null +++ b/node_modules/csv-stringify/dist/esm/sync.d.ts @@ -0,0 +1,12 @@ + +import { Input, Options } from './index.js' + +declare function stringify(input: Input, options?: Options): string + +// export default stringify; +export { stringify }; + +export { + RecordDelimiter, Cast, PlainObject, Input, ColumnOption, CastingContext, + Options +} from './index.js'; diff --git a/node_modules/csv-stringify/dist/esm/sync.js b/node_modules/csv-stringify/dist/esm/sync.js new file mode 100644 index 0000000..26d6e4d --- /dev/null +++ b/node_modules/csv-stringify/dist/esm/sync.js @@ -0,0 +1,2568 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); +}; + +export { stringify }; diff --git a/node_modules/csv-stringify/dist/iife/index.js b/node_modules/csv-stringify/dist/iife/index.js new file mode 100644 index 0000000..deaab62 --- /dev/null +++ b/node_modules/csv-stringify/dist/iife/index.js @@ -0,0 +1,5805 @@ +var csv_stringify = (function (exports) { + 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } + } + + const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; + }; + + exports.CsvError = CsvError; + exports.Stringifier = Stringifier; + exports.stringify = stringify; + + return exports; + +})({}); diff --git a/node_modules/csv-stringify/dist/iife/sync.js b/node_modules/csv-stringify/dist/iife/sync.js new file mode 100644 index 0000000..b4055f1 --- /dev/null +++ b/node_modules/csv-stringify/dist/iife/sync.js @@ -0,0 +1,2575 @@ +var csv_stringify_sync = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); + }; + + exports.stringify = stringify; + + return exports; + +})({}); diff --git a/node_modules/csv-stringify/dist/umd/index.js b/node_modules/csv-stringify/dist/umd/index.js new file mode 100644 index 0000000..e57967d --- /dev/null +++ b/node_modules/csv-stringify/dist/umd/index.js @@ -0,0 +1,5806 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_stringify = {})); +})(this, (function (exports) { 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } + } + + const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; + }; + + exports.CsvError = CsvError; + exports.Stringifier = Stringifier; + exports.stringify = stringify; + +})); diff --git a/node_modules/csv-stringify/dist/umd/sync.js b/node_modules/csv-stringify/dist/umd/sync.js new file mode 100644 index 0000000..ad6a515 --- /dev/null +++ b/node_modules/csv-stringify/dist/umd/sync.js @@ -0,0 +1,2576 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_stringify_sync = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); + }; + + exports.stringify = stringify; + +})); diff --git a/node_modules/csv-stringify/lib/api/CsvError.js b/node_modules/csv-stringify/lib/api/CsvError.js new file mode 100644 index 0000000..5725c7d --- /dev/null +++ b/node_modules/csv-stringify/lib/api/CsvError.js @@ -0,0 +1,19 @@ + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +export { CsvError }; diff --git a/node_modules/csv-stringify/lib/api/index.js b/node_modules/csv-stringify/lib/api/index.js new file mode 100644 index 0000000..2bd65f6 --- /dev/null +++ b/node_modules/csv-stringify/lib/api/index.js @@ -0,0 +1,256 @@ + +import { get } from '../utils/get.js'; +import { is_object } from '../utils/is_object.js'; +import { normalize_columns } from './normalize_columns.js'; +import { normalize_options } from './normalize_options.js'; +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else{ + chunk_string = chunk_string + this.options.record_delimiter; + } + }else{ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else{ + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else{ + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else{ + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else{ + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else{ + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +export {stringifier}; diff --git a/node_modules/csv-stringify/lib/api/normalize_columns.js b/node_modules/csv-stringify/lib/api/normalize_columns.js new file mode 100644 index 0000000..f9a177e --- /dev/null +++ b/node_modules/csv-stringify/lib/api/normalize_columns.js @@ -0,0 +1,43 @@ + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else{ + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else{ + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +export {normalize_columns}; diff --git a/node_modules/csv-stringify/lib/api/normalize_options.js b/node_modules/csv-stringify/lib/api/normalize_options.js new file mode 100644 index 0000000..2b92375 --- /dev/null +++ b/node_modules/csv-stringify/lib/api/normalize_options.js @@ -0,0 +1,190 @@ + +import { CsvError } from './CsvError.js'; +import { normalize_columns } from './normalize_columns.js'; +import { underscore } from '../utils/underscore.js'; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + }else{ + // todo + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + }else{ + // todo + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + }else{ + // todo + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + }else{ + // todo + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + }else{ + // todo + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + }else{ + // todo + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + }else{ + // todo + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +export {normalize_options}; diff --git a/node_modules/csv-stringify/lib/browser/index.js b/node_modules/csv-stringify/lib/browser/index.js deleted file mode 100644 index 43f6622..0000000 --- a/node_modules/csv-stringify/lib/browser/index.js +++ /dev/null @@ -1,7423 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.stringify = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Stringify - -Please look at the [project documentation](https://csv.js.org/stringify/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var bom_utf8 = Buffer.from([239, 187, 191]); - -var Stringifier = /*#__PURE__*/function (_Transform) { - _inherits(Stringifier, _Transform); - - var _super = _createSuper(Stringifier); - - function Stringifier() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Stringifier); - - _this = _super.call(this, _objectSpread(_objectSpread({}, { - writableObjectMode: true - }), opts)); - var options = {}; - var err; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } - - if (err = _this.normalize(options)) throw err; - - switch (options.record_delimiter) { - case 'auto': - options.record_delimiter = null; - break; - - case 'unix': - options.record_delimiter = "\n"; - break; - - case 'mac': - options.record_delimiter = "\r"; - break; - - case 'windows': - options.record_delimiter = "\r\n"; - break; - - case 'ascii': - options.record_delimiter = "\x1E"; - break; - - case 'unicode': - options.record_delimiter = "\u2028"; - break; - } // Expose options - - - _this.options = options; // Internal state - - _this.state = { - stop: false - }; // Information - - _this.info = { - records: 0 - }; - return _this; - } - - _createClass(Stringifier, [{ - key: "normalize", - value: function normalize(options) { - // Normalize option `bom` - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', ['option `bom` is optional and must be a boolean value,', "got ".concat(JSON.stringify(options.bom))]); - } // Normalize option `delimiter` - - - if (options.delimiter === undefined || options.delimiter === null) { - options.delimiter = ','; - } else if (Buffer.isBuffer(options.delimiter)) { - options.delimiter = options.delimiter.toString(); - } else if (typeof options.delimiter !== 'string') { - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', ['option `delimiter` must be a buffer or a string,', "got ".concat(JSON.stringify(options.delimiter))]); - } // Normalize option `quote` - - - if (options.quote === undefined || options.quote === null) { - options.quote = '"'; - } else if (options.quote === true) { - options.quote = '"'; - } else if (options.quote === false) { - options.quote = ''; - } else if (Buffer.isBuffer(options.quote)) { - options.quote = options.quote.toString(); - } else if (typeof options.quote !== 'string') { - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', ['option `quote` must be a boolean, a buffer or a string,', "got ".concat(JSON.stringify(options.quote))]); - } // Normalize option `quoted` - - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `quoted_empty` - - - if (options.quoted_empty === undefined || options.quoted_empty === null) { - options.quoted_empty = undefined; - } else {// todo - } // Normalize option `quoted_match` - - - if (options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false) { - options.quoted_match = null; - } else if (!Array.isArray(options.quoted_match)) { - options.quoted_match = [options.quoted_match]; - } - - if (options.quoted_match) { - var _iterator = _createForOfIteratorHelper(options.quoted_match), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var quoted_match = _step.value; - var isString = typeof quoted_match === 'string'; - var isRegExp = quoted_match instanceof RegExp; - - if (!isString && !isRegExp) { - return Error("Invalid Option: quoted_match must be a string or a regex, got ".concat(JSON.stringify(quoted_match))); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } // Normalize option `quoted_string` - - - if (options.quoted_string === undefined || options.quoted_string === null) { - options.quoted_string = false; - } else {// todo - } // Normalize option `eof` - - - if (options.eof === undefined || options.eof === null) { - options.eof = true; - } else {// todo - } // Normalize option `escape` - - - if (options.escape === undefined || options.escape === null) { - options.escape = '"'; - } else if (Buffer.isBuffer(options.escape)) { - options.escape = options.escape.toString(); - } else if (typeof options.escape !== 'string') { - return Error("Invalid Option: escape must be a buffer or a string, got ".concat(JSON.stringify(options.escape))); - } - - if (options.escape.length > 1) { - return Error("Invalid Option: escape must be one character, got ".concat(options.escape.length, " characters")); - } // Normalize option `header` - - - if (options.header === undefined || options.header === null) { - options.header = false; - } else {// todo - } // Normalize option `columns` - - - options.columns = this.normalize_columns(options.columns); // Normalize option `quoted` - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `cast` - - - if (options.cast === undefined || options.cast === null) { - options.cast = {}; - } else {// todo - } // Normalize option cast.bigint - - - if (options.cast.bigint === undefined || options.cast.bigint === null) { - // Cast boolean to string by default - options.cast.bigint = function (value) { - return '' + value; - }; - } // Normalize option cast.boolean - - - if (options.cast["boolean"] === undefined || options.cast["boolean"] === null) { - // Cast boolean to string by default - options.cast["boolean"] = function (value) { - return value ? '1' : ''; - }; - } // Normalize option cast.date - - - if (options.cast.date === undefined || options.cast.date === null) { - // Cast date to timestamp string by default - options.cast.date = function (value) { - return '' + value.getTime(); - }; - } // Normalize option cast.number - - - if (options.cast.number === undefined || options.cast.number === null) { - // Cast number to string using native casting by default - options.cast.number = function (value) { - return '' + value; - }; - } // Normalize option cast.object - - - if (options.cast.object === undefined || options.cast.object === null) { - // Stringify object as JSON by default - options.cast.object = function (value) { - return JSON.stringify(value); - }; - } // Normalize option cast.string - - - if (options.cast.string === undefined || options.cast.string === null) { - // Leave string untouched - options.cast.string = function (value) { - return value; - }; - } // Normalize option `record_delimiter` - - - if (options.record_delimiter === undefined || options.record_delimiter === null) { - options.record_delimiter = '\n'; - } else if (Buffer.isBuffer(options.record_delimiter)) { - options.record_delimiter = options.record_delimiter.toString(); - } else if (typeof options.record_delimiter !== 'string') { - return Error("Invalid Option: record_delimiter must be a buffer or a string, got ".concat(JSON.stringify(options.record_delimiter))); - } - } - }, { - key: "_transform", - value: function _transform(chunk, encoding, callback) { - if (this.state.stop === true) { - return; - } // Chunk validation - - - if (!Array.isArray(chunk) && _typeof(chunk) !== 'object') { - this.state.stop = true; - return callback(Error("Invalid Record: expect an array or an object, got ".concat(JSON.stringify(chunk)))); - } // Detect columns from the first record - - - if (this.info.records === 0) { - if (Array.isArray(chunk)) { - if (this.options.header === true && !this.options.columns) { - this.state.stop = true; - return callback(Error('Undiscoverable Columns: header option requires column option or object records')); - } - } else if (this.options.columns === undefined || this.options.columns === null) { - this.options.columns = this.normalize_columns(Object.keys(chunk)); - } - } // Emit the header - - - if (this.info.records === 0) { - this.bom(); - this.headers(); - } // Emit and stringify the record if an object or an array - - - try { - this.emit('record', chunk, this.info.records); - } catch (err) { - this.state.stop = true; - return this.emit('error', err); - } // Convert the record into a string - - - var chunk_string; - - if (this.options.eof) { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - chunk_string = chunk_string + this.options.record_delimiter; - } - } else { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - if (this.options.header || this.info.records) { - chunk_string = this.options.record_delimiter + chunk_string; - } - } - } // Emit the csv - - - this.info.records++; - this.push(chunk_string); - callback(); - } - }, { - key: "_flush", - value: function _flush(callback) { - if (this.info.records === 0) { - this.bom(); - this.headers(); - } - - callback(); - } - }, { - key: "stringify", - value: function stringify(chunk) { - var _this2 = this; - - var chunkIsHeader = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - if (_typeof(chunk) !== 'object') { - return chunk; - } - - var _this$options = this.options, - columns = _this$options.columns, - header = _this$options.header; - var record = []; // Record is an array - - if (Array.isArray(chunk)) { - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if (columns) { - chunk.splice(columns.length); - } // Cast record elements - - - for (var _i = 0; _i < chunk.length; _i++) { - var field = chunk[_i]; - - var _this$__cast = this.__cast(field, { - index: _i, - column: _i, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - value = _this$__cast2[1]; - - if (err) { - this.emit('error', err); - return; - } - - record[_i] = [value, field]; - } // Record is a literal object - - } else { - if (columns) { - for (var _i2 = 0; _i2 < columns.length; _i2++) { - var _field = get(chunk, columns[_i2].key); - - var _this$__cast3 = this.__cast(_field, { - index: _i2, - column: columns[_i2].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast4 = _slicedToArray(_this$__cast3, 2), - _err = _this$__cast4[0], - _value = _this$__cast4[1]; - - if (_err) { - this.emit('error', _err); - return; - } - - record[_i2] = [_value, _field]; - } - } else { - var _iterator2 = _createForOfIteratorHelper(chunk), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - var _field2 = chunk[column]; - - var _this$__cast5 = this.__cast(_field2, { - index: i, - column: columns[i].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast6 = _slicedToArray(_this$__cast5, 2), - _err2 = _this$__cast6[0], - _value2 = _this$__cast6[1]; - - if (_err2) { - this.emit('error', _err2); - return; - } - - record.push([_value2, _field2]); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - } - - var csvrecord = ''; - - var _loop = function _loop(_i3) { - var options = void 0, - err = void 0; - - var _record$_i = _slicedToArray(record[_i3], 2), - value = _record$_i[0], - field = _record$_i[1]; - - if (typeof value === "string") { - options = _this2.options; - } else if (isObject(value)) { - // let { value, ...options } = value - options = value; - value = options.value; - delete options.value; - - if (typeof value !== "string" && value !== undefined && value !== null) { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - options = _objectSpread(_objectSpread({}, _this2.options), options); - - if (err = _this2.normalize(options)) { - _this2.emit("error", err); - - return { - v: void 0 - }; - } - } else if (value === undefined || value === null) { - options = _this2.options; - } else { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, an object, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - var _options = options, - delimiter = _options.delimiter, - escape = _options.escape, - quote = _options.quote, - quoted = _options.quoted, - quoted_empty = _options.quoted_empty, - quoted_string = _options.quoted_string, - quoted_match = _options.quoted_match, - record_delimiter = _options.record_delimiter; - - if (value) { - if (typeof value !== 'string') { - _this2.emit("error", Error("Formatter must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: null - }; - } - - var containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; - var containsQuote = quote !== '' && value.indexOf(quote) >= 0; - var containsEscape = value.indexOf(escape) >= 0 && escape !== quote; - var containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; - var quotedString = quoted_string && typeof field === 'string'; - var quotedMatch = quoted_match && quoted_match.filter(function (quoted_match) { - if (typeof quoted_match === 'string') { - return value.indexOf(quoted_match) !== -1; - } else { - return quoted_match.test(value); - } - }); - quotedMatch = quotedMatch && quotedMatch.length > 0; - var shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; - - if (shouldQuote === true && containsEscape === true) { - var regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g'); - value = value.replace(regexp, escape + escape); - } - - if (containsQuote === true) { - var _regexp = new RegExp(quote, 'g'); - - value = value.replace(_regexp, escape + quote); - } - - if (shouldQuote === true) { - value = quote + value + quote; - } - - csvrecord += value; - } else if (quoted_empty === true || field === '' && quoted_string === true && quoted_empty !== false) { - csvrecord += quote + quote; - } - - if (_i3 !== record.length - 1) { - csvrecord += delimiter; - } - }; - - for (var _i3 = 0; _i3 < record.length; _i3++) { - var _ret = _loop(_i3); - - if (_typeof(_ret) === "object") return _ret.v; - } - - return csvrecord; - } - }, { - key: "bom", - value: function bom() { - if (this.options.bom !== true) { - return; - } - - this.push(bom_utf8); - } - }, { - key: "headers", - value: function headers() { - if (this.options.header === false) { - return; - } - - if (this.options.columns === undefined) { - return; - } - - var headers = this.options.columns.map(function (column) { - return column.header; - }); - - if (this.options.eof) { - headers = this.stringify(headers, true) + this.options.record_delimiter; - } else { - headers = this.stringify(headers); - } - - this.push(headers); - } - }, { - key: "__cast", - value: function __cast(value, context) { - var type = _typeof(value); - - try { - if (type === 'string') { - // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)]; - } else if (type === 'bigint') { - return [undefined, this.options.cast.bigint(value, context)]; - } else if (type === 'number') { - return [undefined, this.options.cast.number(value, context)]; - } else if (type === 'boolean') { - return [undefined, this.options.cast["boolean"](value, context)]; - } else if (value instanceof Date) { - return [undefined, this.options.cast.date(value, context)]; - } else if (type === 'object' && value !== null) { - return [undefined, this.options.cast.object(value, context)]; - } else { - return [undefined, value, value]; - } - } catch (err) { - return [err]; - } - } - }, { - key: "normalize_columns", - value: function normalize_columns(columns) { - if (columns === undefined || columns === null) { - return undefined; - } - - if (_typeof(columns) !== 'object') { - throw Error('Invalid option "columns": expect an array or an object'); - } - - if (!Array.isArray(columns)) { - var newcolumns = []; - - for (var k in columns) { - newcolumns.push({ - key: k, - header: columns[k] - }); - } - - columns = newcolumns; - } else { - var _newcolumns = []; - - var _iterator3 = _createForOfIteratorHelper(columns), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var column = _step3.value; - - if (typeof column === 'string') { - _newcolumns.push({ - key: column, - header: column - }); - } else if (_typeof(column) === 'object' && column !== undefined && !Array.isArray(column)) { - if (!column.key) { - throw Error('Invalid column definition: property "key" is required'); - } - - if (column.header === undefined) { - column.header = column.key; - } - - _newcolumns.push(column); - } else { - throw Error('Invalid column definition: expect a string or an object'); - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - columns = _newcolumns; - } - - return columns; - } - }]); - - return Stringifier; -}(Transform); - -var stringify = function stringify() { - var data, options, callback; - - for (var _i4 in arguments) { - var argument = arguments[_i4]; - - var type = _typeof(argument); - - if (data === undefined && Array.isArray(argument)) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(_i4)]); - } - } - - var stringifier = new Stringifier(options); - - if (callback) { - var chunks = []; - stringifier.on('readable', function () { - var chunk; - - while ((chunk = this.read()) !== null) { - chunks.push(chunk); - } - }); - stringifier.on('error', function (err) { - callback(err); - }); - stringifier.on('end', function () { - callback(undefined, chunks.join('')); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - var _iterator4 = _createForOfIteratorHelper(data), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var record = _step4.value; - stringifier.write(record); - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - stringifier.end(); - }); - } else { - var _iterator5 = _createForOfIteratorHelper(data), - _step5; - - try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var record = _step5.value; - stringifier.write(record); - } - } catch (err) { - _iterator5.e(err); - } finally { - _iterator5.f(); - } - - stringifier.end(); - } - } - - return stringifier; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message) { - var _this3; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this3 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this3), CsvError); - } - - _this3.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - contexts[_key - 2] = arguments[_key]; - } - - for (var _i5 = 0, _contexts = contexts; _i5 < _contexts.length; _i5++) { - var context = _contexts[_i5]; - - for (var key in context) { - var value = context[key]; - _this3[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this3; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -stringify.Stringifier = Stringifier; -stringify.CsvError = CsvError; -module.exports = stringify; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; // Lodash implementation of `get` - - -var charCodeOfDot = '.'.charCodeAt(0); -var reEscapeChar = /\\(\\)?/g; -var rePropName = RegExp( // Match anything that isn't a dot or bracket. -'[^.[\\]]+' + '|' + // Or match property names within brackets. -'\\[(?:' + // Match a non-string expression. -'([^"\'][^[]*)' + '|' + // Or match strings (supports escaping characters). -'(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + // Or match "" as the space between consecutive dots or empty brackets. -'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g'); -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; -var reIsPlainProp = /^\w*$/; - -var getTag = function getTag(value) { - if (!value) value === undefined ? '[object Undefined]' : '[object Null]'; - return Object.prototype.toString.call(value); -}; - -var isKey = function isKey(value, object) { - if (Array.isArray(value)) { - return false; - } - - var type = _typeof(value); - - if (type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)) { - return true; - } - - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); -}; - -var isSymbol = function isSymbol(value) { - var type = _typeof(value); - - return type === 'symbol' || type === 'object' && value && getTag(value) === '[object Symbol]'; -}; - -var stringToPath = function stringToPath(string) { - var result = []; - - if (string.charCodeAt(0) === charCodeOfDot) { - result.push(''); - } - - string.replace(rePropName, function (match, expression, quote, subString) { - var key = match; - - if (quote) { - key = subString.replace(reEscapeChar, '$1'); - } else if (expression) { - key = expression.trim(); - } - - result.push(key); - }); - return result; -}; - -var castPath = function castPath(value, object) { - if (Array.isArray(value)) { - return value; - } else { - return isKey(value, object) ? [value] : stringToPath(value); - } -}; - -var toKey = function toKey(value) { - if (typeof value === 'string' || isSymbol(value)) return value; - var result = "".concat(value); - return result == '0' && 1 / value == -INFINITY ? '-0' : result; -}; - -var get = function get(object, path) { - path = castPath(path, object); - var index = 0; - var length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - - return index && index === length ? object : undefined; -}; - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"buffer":4,"stream":10,"timers":26}],2:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],3:[function(require,module,exports){ - -},{}],4:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":2,"buffer":4,"ieee754":6}],5:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],6:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],7:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],8:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],9:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":4}],10:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":5,"inherits":7,"readable-stream/lib/_stream_duplex.js":12,"readable-stream/lib/_stream_passthrough.js":13,"readable-stream/lib/_stream_readable.js":14,"readable-stream/lib/_stream_transform.js":15,"readable-stream/lib/_stream_writable.js":16,"readable-stream/lib/internal/streams/end-of-stream.js":20,"readable-stream/lib/internal/streams/pipeline.js":22}],11:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],12:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":14,"./_stream_writable":16,"_process":8,"inherits":7}],13:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":15,"inherits":7}],14:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":11,"./_stream_duplex":12,"./internal/streams/async_iterator":17,"./internal/streams/buffer_list":18,"./internal/streams/destroy":19,"./internal/streams/from":21,"./internal/streams/state":23,"./internal/streams/stream":24,"_process":8,"buffer":4,"events":5,"inherits":7,"string_decoder/":25,"util":3}],15:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":11,"./_stream_duplex":12,"inherits":7}],16:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":11,"./_stream_duplex":12,"./internal/streams/destroy":19,"./internal/streams/state":23,"./internal/streams/stream":24,"_process":8,"buffer":4,"inherits":7,"util-deprecate":27}],17:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":20,"_process":8}],18:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":4,"util":3}],19:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":8}],20:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":11}],21:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],22:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":11,"./end-of-stream":20}],23:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":11}],24:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":5}],25:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":9}],26:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":8,"timers":26}],27:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[1])(1) -}); diff --git a/node_modules/csv-stringify/lib/browser/sync.js b/node_modules/csv-stringify/lib/browser/sync.js deleted file mode 100644 index ae22b45..0000000 --- a/node_modules/csv-stringify/lib/browser/sync.js +++ /dev/null @@ -1,7499 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.stringify = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Stringify - -Please look at the [project documentation](https://csv.js.org/stringify/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var bom_utf8 = Buffer.from([239, 187, 191]); - -var Stringifier = /*#__PURE__*/function (_Transform) { - _inherits(Stringifier, _Transform); - - var _super = _createSuper(Stringifier); - - function Stringifier() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Stringifier); - - _this = _super.call(this, _objectSpread(_objectSpread({}, { - writableObjectMode: true - }), opts)); - var options = {}; - var err; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } - - if (err = _this.normalize(options)) throw err; - - switch (options.record_delimiter) { - case 'auto': - options.record_delimiter = null; - break; - - case 'unix': - options.record_delimiter = "\n"; - break; - - case 'mac': - options.record_delimiter = "\r"; - break; - - case 'windows': - options.record_delimiter = "\r\n"; - break; - - case 'ascii': - options.record_delimiter = "\x1E"; - break; - - case 'unicode': - options.record_delimiter = "\u2028"; - break; - } // Expose options - - - _this.options = options; // Internal state - - _this.state = { - stop: false - }; // Information - - _this.info = { - records: 0 - }; - return _this; - } - - _createClass(Stringifier, [{ - key: "normalize", - value: function normalize(options) { - // Normalize option `bom` - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', ['option `bom` is optional and must be a boolean value,', "got ".concat(JSON.stringify(options.bom))]); - } // Normalize option `delimiter` - - - if (options.delimiter === undefined || options.delimiter === null) { - options.delimiter = ','; - } else if (Buffer.isBuffer(options.delimiter)) { - options.delimiter = options.delimiter.toString(); - } else if (typeof options.delimiter !== 'string') { - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', ['option `delimiter` must be a buffer or a string,', "got ".concat(JSON.stringify(options.delimiter))]); - } // Normalize option `quote` - - - if (options.quote === undefined || options.quote === null) { - options.quote = '"'; - } else if (options.quote === true) { - options.quote = '"'; - } else if (options.quote === false) { - options.quote = ''; - } else if (Buffer.isBuffer(options.quote)) { - options.quote = options.quote.toString(); - } else if (typeof options.quote !== 'string') { - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', ['option `quote` must be a boolean, a buffer or a string,', "got ".concat(JSON.stringify(options.quote))]); - } // Normalize option `quoted` - - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `quoted_empty` - - - if (options.quoted_empty === undefined || options.quoted_empty === null) { - options.quoted_empty = undefined; - } else {// todo - } // Normalize option `quoted_match` - - - if (options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false) { - options.quoted_match = null; - } else if (!Array.isArray(options.quoted_match)) { - options.quoted_match = [options.quoted_match]; - } - - if (options.quoted_match) { - var _iterator = _createForOfIteratorHelper(options.quoted_match), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var quoted_match = _step.value; - var isString = typeof quoted_match === 'string'; - var isRegExp = quoted_match instanceof RegExp; - - if (!isString && !isRegExp) { - return Error("Invalid Option: quoted_match must be a string or a regex, got ".concat(JSON.stringify(quoted_match))); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } // Normalize option `quoted_string` - - - if (options.quoted_string === undefined || options.quoted_string === null) { - options.quoted_string = false; - } else {// todo - } // Normalize option `eof` - - - if (options.eof === undefined || options.eof === null) { - options.eof = true; - } else {// todo - } // Normalize option `escape` - - - if (options.escape === undefined || options.escape === null) { - options.escape = '"'; - } else if (Buffer.isBuffer(options.escape)) { - options.escape = options.escape.toString(); - } else if (typeof options.escape !== 'string') { - return Error("Invalid Option: escape must be a buffer or a string, got ".concat(JSON.stringify(options.escape))); - } - - if (options.escape.length > 1) { - return Error("Invalid Option: escape must be one character, got ".concat(options.escape.length, " characters")); - } // Normalize option `header` - - - if (options.header === undefined || options.header === null) { - options.header = false; - } else {// todo - } // Normalize option `columns` - - - options.columns = this.normalize_columns(options.columns); // Normalize option `quoted` - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `cast` - - - if (options.cast === undefined || options.cast === null) { - options.cast = {}; - } else {// todo - } // Normalize option cast.bigint - - - if (options.cast.bigint === undefined || options.cast.bigint === null) { - // Cast boolean to string by default - options.cast.bigint = function (value) { - return '' + value; - }; - } // Normalize option cast.boolean - - - if (options.cast["boolean"] === undefined || options.cast["boolean"] === null) { - // Cast boolean to string by default - options.cast["boolean"] = function (value) { - return value ? '1' : ''; - }; - } // Normalize option cast.date - - - if (options.cast.date === undefined || options.cast.date === null) { - // Cast date to timestamp string by default - options.cast.date = function (value) { - return '' + value.getTime(); - }; - } // Normalize option cast.number - - - if (options.cast.number === undefined || options.cast.number === null) { - // Cast number to string using native casting by default - options.cast.number = function (value) { - return '' + value; - }; - } // Normalize option cast.object - - - if (options.cast.object === undefined || options.cast.object === null) { - // Stringify object as JSON by default - options.cast.object = function (value) { - return JSON.stringify(value); - }; - } // Normalize option cast.string - - - if (options.cast.string === undefined || options.cast.string === null) { - // Leave string untouched - options.cast.string = function (value) { - return value; - }; - } // Normalize option `record_delimiter` - - - if (options.record_delimiter === undefined || options.record_delimiter === null) { - options.record_delimiter = '\n'; - } else if (Buffer.isBuffer(options.record_delimiter)) { - options.record_delimiter = options.record_delimiter.toString(); - } else if (typeof options.record_delimiter !== 'string') { - return Error("Invalid Option: record_delimiter must be a buffer or a string, got ".concat(JSON.stringify(options.record_delimiter))); - } - } - }, { - key: "_transform", - value: function _transform(chunk, encoding, callback) { - if (this.state.stop === true) { - return; - } // Chunk validation - - - if (!Array.isArray(chunk) && _typeof(chunk) !== 'object') { - this.state.stop = true; - return callback(Error("Invalid Record: expect an array or an object, got ".concat(JSON.stringify(chunk)))); - } // Detect columns from the first record - - - if (this.info.records === 0) { - if (Array.isArray(chunk)) { - if (this.options.header === true && !this.options.columns) { - this.state.stop = true; - return callback(Error('Undiscoverable Columns: header option requires column option or object records')); - } - } else if (this.options.columns === undefined || this.options.columns === null) { - this.options.columns = this.normalize_columns(Object.keys(chunk)); - } - } // Emit the header - - - if (this.info.records === 0) { - this.bom(); - this.headers(); - } // Emit and stringify the record if an object or an array - - - try { - this.emit('record', chunk, this.info.records); - } catch (err) { - this.state.stop = true; - return this.emit('error', err); - } // Convert the record into a string - - - var chunk_string; - - if (this.options.eof) { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - chunk_string = chunk_string + this.options.record_delimiter; - } - } else { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - if (this.options.header || this.info.records) { - chunk_string = this.options.record_delimiter + chunk_string; - } - } - } // Emit the csv - - - this.info.records++; - this.push(chunk_string); - callback(); - } - }, { - key: "_flush", - value: function _flush(callback) { - if (this.info.records === 0) { - this.bom(); - this.headers(); - } - - callback(); - } - }, { - key: "stringify", - value: function stringify(chunk) { - var _this2 = this; - - var chunkIsHeader = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - if (_typeof(chunk) !== 'object') { - return chunk; - } - - var _this$options = this.options, - columns = _this$options.columns, - header = _this$options.header; - var record = []; // Record is an array - - if (Array.isArray(chunk)) { - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if (columns) { - chunk.splice(columns.length); - } // Cast record elements - - - for (var _i = 0; _i < chunk.length; _i++) { - var field = chunk[_i]; - - var _this$__cast = this.__cast(field, { - index: _i, - column: _i, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - value = _this$__cast2[1]; - - if (err) { - this.emit('error', err); - return; - } - - record[_i] = [value, field]; - } // Record is a literal object - - } else { - if (columns) { - for (var _i2 = 0; _i2 < columns.length; _i2++) { - var _field = get(chunk, columns[_i2].key); - - var _this$__cast3 = this.__cast(_field, { - index: _i2, - column: columns[_i2].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast4 = _slicedToArray(_this$__cast3, 2), - _err = _this$__cast4[0], - _value = _this$__cast4[1]; - - if (_err) { - this.emit('error', _err); - return; - } - - record[_i2] = [_value, _field]; - } - } else { - var _iterator2 = _createForOfIteratorHelper(chunk), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - var _field2 = chunk[column]; - - var _this$__cast5 = this.__cast(_field2, { - index: i, - column: columns[i].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast6 = _slicedToArray(_this$__cast5, 2), - _err2 = _this$__cast6[0], - _value2 = _this$__cast6[1]; - - if (_err2) { - this.emit('error', _err2); - return; - } - - record.push([_value2, _field2]); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - } - - var csvrecord = ''; - - var _loop = function _loop(_i3) { - var options = void 0, - err = void 0; - - var _record$_i = _slicedToArray(record[_i3], 2), - value = _record$_i[0], - field = _record$_i[1]; - - if (typeof value === "string") { - options = _this2.options; - } else if (isObject(value)) { - // let { value, ...options } = value - options = value; - value = options.value; - delete options.value; - - if (typeof value !== "string" && value !== undefined && value !== null) { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - options = _objectSpread(_objectSpread({}, _this2.options), options); - - if (err = _this2.normalize(options)) { - _this2.emit("error", err); - - return { - v: void 0 - }; - } - } else if (value === undefined || value === null) { - options = _this2.options; - } else { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, an object, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - var _options = options, - delimiter = _options.delimiter, - escape = _options.escape, - quote = _options.quote, - quoted = _options.quoted, - quoted_empty = _options.quoted_empty, - quoted_string = _options.quoted_string, - quoted_match = _options.quoted_match, - record_delimiter = _options.record_delimiter; - - if (value) { - if (typeof value !== 'string') { - _this2.emit("error", Error("Formatter must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: null - }; - } - - var containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; - var containsQuote = quote !== '' && value.indexOf(quote) >= 0; - var containsEscape = value.indexOf(escape) >= 0 && escape !== quote; - var containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; - var quotedString = quoted_string && typeof field === 'string'; - var quotedMatch = quoted_match && quoted_match.filter(function (quoted_match) { - if (typeof quoted_match === 'string') { - return value.indexOf(quoted_match) !== -1; - } else { - return quoted_match.test(value); - } - }); - quotedMatch = quotedMatch && quotedMatch.length > 0; - var shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; - - if (shouldQuote === true && containsEscape === true) { - var regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g'); - value = value.replace(regexp, escape + escape); - } - - if (containsQuote === true) { - var _regexp = new RegExp(quote, 'g'); - - value = value.replace(_regexp, escape + quote); - } - - if (shouldQuote === true) { - value = quote + value + quote; - } - - csvrecord += value; - } else if (quoted_empty === true || field === '' && quoted_string === true && quoted_empty !== false) { - csvrecord += quote + quote; - } - - if (_i3 !== record.length - 1) { - csvrecord += delimiter; - } - }; - - for (var _i3 = 0; _i3 < record.length; _i3++) { - var _ret = _loop(_i3); - - if (_typeof(_ret) === "object") return _ret.v; - } - - return csvrecord; - } - }, { - key: "bom", - value: function bom() { - if (this.options.bom !== true) { - return; - } - - this.push(bom_utf8); - } - }, { - key: "headers", - value: function headers() { - if (this.options.header === false) { - return; - } - - if (this.options.columns === undefined) { - return; - } - - var headers = this.options.columns.map(function (column) { - return column.header; - }); - - if (this.options.eof) { - headers = this.stringify(headers, true) + this.options.record_delimiter; - } else { - headers = this.stringify(headers); - } - - this.push(headers); - } - }, { - key: "__cast", - value: function __cast(value, context) { - var type = _typeof(value); - - try { - if (type === 'string') { - // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)]; - } else if (type === 'bigint') { - return [undefined, this.options.cast.bigint(value, context)]; - } else if (type === 'number') { - return [undefined, this.options.cast.number(value, context)]; - } else if (type === 'boolean') { - return [undefined, this.options.cast["boolean"](value, context)]; - } else if (value instanceof Date) { - return [undefined, this.options.cast.date(value, context)]; - } else if (type === 'object' && value !== null) { - return [undefined, this.options.cast.object(value, context)]; - } else { - return [undefined, value, value]; - } - } catch (err) { - return [err]; - } - } - }, { - key: "normalize_columns", - value: function normalize_columns(columns) { - if (columns === undefined || columns === null) { - return undefined; - } - - if (_typeof(columns) !== 'object') { - throw Error('Invalid option "columns": expect an array or an object'); - } - - if (!Array.isArray(columns)) { - var newcolumns = []; - - for (var k in columns) { - newcolumns.push({ - key: k, - header: columns[k] - }); - } - - columns = newcolumns; - } else { - var _newcolumns = []; - - var _iterator3 = _createForOfIteratorHelper(columns), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var column = _step3.value; - - if (typeof column === 'string') { - _newcolumns.push({ - key: column, - header: column - }); - } else if (_typeof(column) === 'object' && column !== undefined && !Array.isArray(column)) { - if (!column.key) { - throw Error('Invalid column definition: property "key" is required'); - } - - if (column.header === undefined) { - column.header = column.key; - } - - _newcolumns.push(column); - } else { - throw Error('Invalid column definition: expect a string or an object'); - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - columns = _newcolumns; - } - - return columns; - } - }]); - - return Stringifier; -}(Transform); - -var stringify = function stringify() { - var data, options, callback; - - for (var _i4 in arguments) { - var argument = arguments[_i4]; - - var type = _typeof(argument); - - if (data === undefined && Array.isArray(argument)) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(_i4)]); - } - } - - var stringifier = new Stringifier(options); - - if (callback) { - var chunks = []; - stringifier.on('readable', function () { - var chunk; - - while ((chunk = this.read()) !== null) { - chunks.push(chunk); - } - }); - stringifier.on('error', function (err) { - callback(err); - }); - stringifier.on('end', function () { - callback(undefined, chunks.join('')); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - var _iterator4 = _createForOfIteratorHelper(data), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var record = _step4.value; - stringifier.write(record); - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - stringifier.end(); - }); - } else { - var _iterator5 = _createForOfIteratorHelper(data), - _step5; - - try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var record = _step5.value; - stringifier.write(record); - } - } catch (err) { - _iterator5.e(err); - } finally { - _iterator5.f(); - } - - stringifier.end(); - } - } - - return stringifier; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message) { - var _this3; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this3 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this3), CsvError); - } - - _this3.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - contexts[_key - 2] = arguments[_key]; - } - - for (var _i5 = 0, _contexts = contexts; _i5 < _contexts.length; _i5++) { - var context = _contexts[_i5]; - - for (var key in context) { - var value = context[key]; - _this3[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this3; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -stringify.Stringifier = Stringifier; -stringify.CsvError = CsvError; -module.exports = stringify; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; // Lodash implementation of `get` - - -var charCodeOfDot = '.'.charCodeAt(0); -var reEscapeChar = /\\(\\)?/g; -var rePropName = RegExp( // Match anything that isn't a dot or bracket. -'[^.[\\]]+' + '|' + // Or match property names within brackets. -'\\[(?:' + // Match a non-string expression. -'([^"\'][^[]*)' + '|' + // Or match strings (supports escaping characters). -'(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + // Or match "" as the space between consecutive dots or empty brackets. -'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g'); -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; -var reIsPlainProp = /^\w*$/; - -var getTag = function getTag(value) { - if (!value) value === undefined ? '[object Undefined]' : '[object Null]'; - return Object.prototype.toString.call(value); -}; - -var isKey = function isKey(value, object) { - if (Array.isArray(value)) { - return false; - } - - var type = _typeof(value); - - if (type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)) { - return true; - } - - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); -}; - -var isSymbol = function isSymbol(value) { - var type = _typeof(value); - - return type === 'symbol' || type === 'object' && value && getTag(value) === '[object Symbol]'; -}; - -var stringToPath = function stringToPath(string) { - var result = []; - - if (string.charCodeAt(0) === charCodeOfDot) { - result.push(''); - } - - string.replace(rePropName, function (match, expression, quote, subString) { - var key = match; - - if (quote) { - key = subString.replace(reEscapeChar, '$1'); - } else if (expression) { - key = expression.trim(); - } - - result.push(key); - }); - return result; -}; - -var castPath = function castPath(value, object) { - if (Array.isArray(value)) { - return value; - } else { - return isKey(value, object) ? [value] : stringToPath(value); - } -}; - -var toKey = function toKey(value) { - if (typeof value === 'string' || isSymbol(value)) return value; - var result = "".concat(value); - return result == '0' && 1 / value == -INFINITY ? '-0' : result; -}; - -var get = function get(object, path) { - path = castPath(path, object); - var index = 0; - var length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - - return index && index === length ? object : undefined; -}; - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"buffer":5,"stream":12,"timers":28}],2:[function(require,module,exports){ -(function (Buffer){(function (){ -"use strict"; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -var stringify = require('.'); - -var _require = require('string_decoder'), - StringDecoder = _require.StringDecoder; - -module.exports = function (records) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var data = []; - - if (Buffer.isBuffer(records)) { - var decoder = new StringDecoder(); - records = decoder.write(records); - } - - function onData(record) { - if (record) { - data.push(record.toString()); - } - } - - var stringifier = new stringify.Stringifier(options); - stringifier.on('data', onData); - - var _iterator = _createForOfIteratorHelper(records), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var record = _step.value; - stringifier.write(record); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - stringifier.end(); - stringifier.off('data', onData); - return data.join(''); -}; - -}).call(this)}).call(this,{"isBuffer":require("../node_modules/is-buffer/index.js")}) -},{".":1,"../node_modules/is-buffer/index.js":9,"string_decoder":27}],3:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],4:[function(require,module,exports){ - -},{}],5:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":3,"buffer":5,"ieee754":7}],6:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],7:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],8:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],9:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],10:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],11:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":5}],12:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":6,"inherits":8,"readable-stream/lib/_stream_duplex.js":14,"readable-stream/lib/_stream_passthrough.js":15,"readable-stream/lib/_stream_readable.js":16,"readable-stream/lib/_stream_transform.js":17,"readable-stream/lib/_stream_writable.js":18,"readable-stream/lib/internal/streams/end-of-stream.js":22,"readable-stream/lib/internal/streams/pipeline.js":24}],13:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],14:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":16,"./_stream_writable":18,"_process":10,"inherits":8}],15:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":17,"inherits":8}],16:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":13,"./_stream_duplex":14,"./internal/streams/async_iterator":19,"./internal/streams/buffer_list":20,"./internal/streams/destroy":21,"./internal/streams/from":23,"./internal/streams/state":25,"./internal/streams/stream":26,"_process":10,"buffer":5,"events":6,"inherits":8,"string_decoder/":27,"util":4}],17:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":13,"./_stream_duplex":14,"inherits":8}],18:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":13,"./_stream_duplex":14,"./internal/streams/destroy":21,"./internal/streams/state":25,"./internal/streams/stream":26,"_process":10,"buffer":5,"inherits":8,"util-deprecate":29}],19:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":22,"_process":10}],20:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":5,"util":4}],21:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":10}],22:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":13}],23:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],24:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":13,"./end-of-stream":22}],25:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":13}],26:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":6}],27:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":11}],28:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":10,"timers":28}],29:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[2])(2) -}); diff --git a/node_modules/csv-stringify/lib/es5/index.d.ts b/node_modules/csv-stringify/lib/es5/index.d.ts deleted file mode 100644 index 91d0c4d..0000000 --- a/node_modules/csv-stringify/lib/es5/index.d.ts +++ /dev/null @@ -1,101 +0,0 @@ -/// - -import * as stream from "stream"; -export = stringify - -declare function stringify(callback?: stringify.Callback): stringify.Stringifier -declare function stringify(options: stringify.Options, callback?: stringify.Callback): stringify.Stringifier -declare function stringify(input: stringify.Input, callback?: stringify.Callback): stringify.Stringifier -declare function stringify(input: stringify.Input, options?: stringify.Options, callback?: stringify.Callback): stringify.Stringifier -declare namespace stringify { - type Callback = (err: Error | undefined, output: string) => void - type RecordDelimiter = string | Buffer | 'auto' | 'unix' | 'mac' | 'windows' | 'ascii' | 'unicode' - type Cast = (value: T, context: CastingContext) => string - type PlainObject = Record - type Input = any[] - interface ColumnOption { - key: string - header?: string - } - interface CastingContext { - readonly column?: number | string; - readonly header: boolean; - readonly index: number; - readonly records: number; - } - interface Options { - /** - * Prepend the byte order mark (BOM) to the output stream. - */ - bom?: boolean - /** - * Key-value object which defines custom cast for certain data types - */ - cast?: { - boolean?: Cast - date?: Cast - number?: Cast - /** - * Custom formatter for generic object values - */ - object?: Cast> - string?: Cast - } - /** - * List of fields, applied when `transform` returns an object - * order matters - * read the transformer documentation for additionnal information - * columns are auto discovered in the first record when the user write objects - * can refer to nested properties of the input JSON - * see the "header" option on how to print columns names on the first line - */ - columns?: string[] | PlainObject | ColumnOption[] - /** - * Set the field delimiter, one character only, defaults to a comma. - */ - delimiter?: string | Buffer - /** - * Add the value of "options.RecordDelimiter" on the last line, default to true. - */ - eof?: boolean - /** - * Defaults to the escape read option. - */ - escape?: string | Buffer - /** - * Display the column names on the first line if the columns option is provided or discovered. - */ - header?: boolean - /** - * The quote characters, defaults to the ", an empty quote value will preserve the original field. - */ - quote?: string | Buffer | boolean - /** - * Boolean, default to false, quote all the non-empty fields even if not required. - */ - quoted?: boolean - - /** - * Boolean, no default, quote empty fields and overrides `quoted_string` on empty strings when defined. - */ - quoted_empty?: boolean - /** - * String or RegExp, no default, quote all fields matching a regular expression. - */ - quoted_match?: string | RegExp - /** - * Boolean, default to false, quote all fields of type string even if not required. - */ - quoted_string?: boolean - /** - * String used to delimit record rows or a special value - * special values are 'auto', 'unix', 'mac', 'windows', 'ascii', 'unicode' - * defaults to 'auto' (discovered in source or 'unix' if no source is specified). - */ - record_delimiter?: RecordDelimiter - } - class Stringifier extends stream.Transform { - constructor(options: Options) - readonly options: Options - } -} diff --git a/node_modules/csv-stringify/lib/es5/index.js b/node_modules/csv-stringify/lib/es5/index.js deleted file mode 100644 index 77d4dc8..0000000 --- a/node_modules/csv-stringify/lib/es5/index.js +++ /dev/null @@ -1,928 +0,0 @@ -"use strict"; - -function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } - -function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } - -function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } - -function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_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 _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e2) { throw _e2; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e3) { didErr = true; err = _e3; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } - -function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } - -function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } - -function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); } - -function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } - -function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } - -function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } - -/* -CSV Stringify - -Please look at the [project documentation](https://csv.js.org/stringify/) for -additional information. -*/ -var _require = require('stream'), - Transform = _require.Transform; - -var bom_utf8 = Buffer.from([239, 187, 191]); - -var Stringifier = /*#__PURE__*/function (_Transform) { - _inherits(Stringifier, _Transform); - - var _super = _createSuper(Stringifier); - - function Stringifier() { - var _this; - - var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - - _classCallCheck(this, Stringifier); - - _this = _super.call(this, _objectSpread(_objectSpread({}, { - writableObjectMode: true - }), opts)); - var options = {}; - var err; // Merge with user options - - for (var opt in opts) { - options[underscore(opt)] = opts[opt]; - } - - if (err = _this.normalize(options)) throw err; - - switch (options.record_delimiter) { - case 'auto': - options.record_delimiter = null; - break; - - case 'unix': - options.record_delimiter = "\n"; - break; - - case 'mac': - options.record_delimiter = "\r"; - break; - - case 'windows': - options.record_delimiter = "\r\n"; - break; - - case 'ascii': - options.record_delimiter = "\x1E"; - break; - - case 'unicode': - options.record_delimiter = "\u2028"; - break; - } // Expose options - - - _this.options = options; // Internal state - - _this.state = { - stop: false - }; // Information - - _this.info = { - records: 0 - }; - return _this; - } - - _createClass(Stringifier, [{ - key: "normalize", - value: function normalize(options) { - // Normalize option `bom` - if (options.bom === undefined || options.bom === null || options.bom === false) { - options.bom = false; - } else if (options.bom !== true) { - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', ['option `bom` is optional and must be a boolean value,', "got ".concat(JSON.stringify(options.bom))]); - } // Normalize option `delimiter` - - - if (options.delimiter === undefined || options.delimiter === null) { - options.delimiter = ','; - } else if (Buffer.isBuffer(options.delimiter)) { - options.delimiter = options.delimiter.toString(); - } else if (typeof options.delimiter !== 'string') { - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', ['option `delimiter` must be a buffer or a string,', "got ".concat(JSON.stringify(options.delimiter))]); - } // Normalize option `quote` - - - if (options.quote === undefined || options.quote === null) { - options.quote = '"'; - } else if (options.quote === true) { - options.quote = '"'; - } else if (options.quote === false) { - options.quote = ''; - } else if (Buffer.isBuffer(options.quote)) { - options.quote = options.quote.toString(); - } else if (typeof options.quote !== 'string') { - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', ['option `quote` must be a boolean, a buffer or a string,', "got ".concat(JSON.stringify(options.quote))]); - } // Normalize option `quoted` - - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `quoted_empty` - - - if (options.quoted_empty === undefined || options.quoted_empty === null) { - options.quoted_empty = undefined; - } else {// todo - } // Normalize option `quoted_match` - - - if (options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false) { - options.quoted_match = null; - } else if (!Array.isArray(options.quoted_match)) { - options.quoted_match = [options.quoted_match]; - } - - if (options.quoted_match) { - var _iterator = _createForOfIteratorHelper(options.quoted_match), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var quoted_match = _step.value; - var isString = typeof quoted_match === 'string'; - var isRegExp = quoted_match instanceof RegExp; - - if (!isString && !isRegExp) { - return Error("Invalid Option: quoted_match must be a string or a regex, got ".concat(JSON.stringify(quoted_match))); - } - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - } // Normalize option `quoted_string` - - - if (options.quoted_string === undefined || options.quoted_string === null) { - options.quoted_string = false; - } else {// todo - } // Normalize option `eof` - - - if (options.eof === undefined || options.eof === null) { - options.eof = true; - } else {// todo - } // Normalize option `escape` - - - if (options.escape === undefined || options.escape === null) { - options.escape = '"'; - } else if (Buffer.isBuffer(options.escape)) { - options.escape = options.escape.toString(); - } else if (typeof options.escape !== 'string') { - return Error("Invalid Option: escape must be a buffer or a string, got ".concat(JSON.stringify(options.escape))); - } - - if (options.escape.length > 1) { - return Error("Invalid Option: escape must be one character, got ".concat(options.escape.length, " characters")); - } // Normalize option `header` - - - if (options.header === undefined || options.header === null) { - options.header = false; - } else {// todo - } // Normalize option `columns` - - - options.columns = this.normalize_columns(options.columns); // Normalize option `quoted` - - if (options.quoted === undefined || options.quoted === null) { - options.quoted = false; - } else {// todo - } // Normalize option `cast` - - - if (options.cast === undefined || options.cast === null) { - options.cast = {}; - } else {// todo - } // Normalize option cast.bigint - - - if (options.cast.bigint === undefined || options.cast.bigint === null) { - // Cast boolean to string by default - options.cast.bigint = function (value) { - return '' + value; - }; - } // Normalize option cast.boolean - - - if (options.cast["boolean"] === undefined || options.cast["boolean"] === null) { - // Cast boolean to string by default - options.cast["boolean"] = function (value) { - return value ? '1' : ''; - }; - } // Normalize option cast.date - - - if (options.cast.date === undefined || options.cast.date === null) { - // Cast date to timestamp string by default - options.cast.date = function (value) { - return '' + value.getTime(); - }; - } // Normalize option cast.number - - - if (options.cast.number === undefined || options.cast.number === null) { - // Cast number to string using native casting by default - options.cast.number = function (value) { - return '' + value; - }; - } // Normalize option cast.object - - - if (options.cast.object === undefined || options.cast.object === null) { - // Stringify object as JSON by default - options.cast.object = function (value) { - return JSON.stringify(value); - }; - } // Normalize option cast.string - - - if (options.cast.string === undefined || options.cast.string === null) { - // Leave string untouched - options.cast.string = function (value) { - return value; - }; - } // Normalize option `record_delimiter` - - - if (options.record_delimiter === undefined || options.record_delimiter === null) { - options.record_delimiter = '\n'; - } else if (Buffer.isBuffer(options.record_delimiter)) { - options.record_delimiter = options.record_delimiter.toString(); - } else if (typeof options.record_delimiter !== 'string') { - return Error("Invalid Option: record_delimiter must be a buffer or a string, got ".concat(JSON.stringify(options.record_delimiter))); - } - } - }, { - key: "_transform", - value: function _transform(chunk, encoding, callback) { - if (this.state.stop === true) { - return; - } // Chunk validation - - - if (!Array.isArray(chunk) && _typeof(chunk) !== 'object') { - this.state.stop = true; - return callback(Error("Invalid Record: expect an array or an object, got ".concat(JSON.stringify(chunk)))); - } // Detect columns from the first record - - - if (this.info.records === 0) { - if (Array.isArray(chunk)) { - if (this.options.header === true && !this.options.columns) { - this.state.stop = true; - return callback(Error('Undiscoverable Columns: header option requires column option or object records')); - } - } else if (this.options.columns === undefined || this.options.columns === null) { - this.options.columns = this.normalize_columns(Object.keys(chunk)); - } - } // Emit the header - - - if (this.info.records === 0) { - this.bom(); - this.headers(); - } // Emit and stringify the record if an object or an array - - - try { - this.emit('record', chunk, this.info.records); - } catch (err) { - this.state.stop = true; - return this.emit('error', err); - } // Convert the record into a string - - - var chunk_string; - - if (this.options.eof) { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - chunk_string = chunk_string + this.options.record_delimiter; - } - } else { - chunk_string = this.stringify(chunk); - - if (chunk_string === undefined) { - return; - } else { - if (this.options.header || this.info.records) { - chunk_string = this.options.record_delimiter + chunk_string; - } - } - } // Emit the csv - - - this.info.records++; - this.push(chunk_string); - callback(); - } - }, { - key: "_flush", - value: function _flush(callback) { - if (this.info.records === 0) { - this.bom(); - this.headers(); - } - - callback(); - } - }, { - key: "stringify", - value: function stringify(chunk) { - var _this2 = this; - - var chunkIsHeader = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - - if (_typeof(chunk) !== 'object') { - return chunk; - } - - var _this$options = this.options, - columns = _this$options.columns, - header = _this$options.header; - var record = []; // Record is an array - - if (Array.isArray(chunk)) { - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if (columns) { - chunk.splice(columns.length); - } // Cast record elements - - - for (var _i = 0; _i < chunk.length; _i++) { - var field = chunk[_i]; - - var _this$__cast = this.__cast(field, { - index: _i, - column: _i, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast2 = _slicedToArray(_this$__cast, 2), - err = _this$__cast2[0], - value = _this$__cast2[1]; - - if (err) { - this.emit('error', err); - return; - } - - record[_i] = [value, field]; - } // Record is a literal object - - } else { - if (columns) { - for (var _i2 = 0; _i2 < columns.length; _i2++) { - var _field = get(chunk, columns[_i2].key); - - var _this$__cast3 = this.__cast(_field, { - index: _i2, - column: columns[_i2].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast4 = _slicedToArray(_this$__cast3, 2), - _err = _this$__cast4[0], - _value = _this$__cast4[1]; - - if (_err) { - this.emit('error', _err); - return; - } - - record[_i2] = [_value, _field]; - } - } else { - var _iterator2 = _createForOfIteratorHelper(chunk), - _step2; - - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var column = _step2.value; - var _field2 = chunk[column]; - - var _this$__cast5 = this.__cast(_field2, { - index: i, - column: columns[i].key, - records: this.info.records, - header: chunkIsHeader - }), - _this$__cast6 = _slicedToArray(_this$__cast5, 2), - _err2 = _this$__cast6[0], - _value2 = _this$__cast6[1]; - - if (_err2) { - this.emit('error', _err2); - return; - } - - record.push([_value2, _field2]); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); - } - } - } - - var csvrecord = ''; - - var _loop = function _loop(_i3) { - var options = void 0, - err = void 0; - - var _record$_i = _slicedToArray(record[_i3], 2), - value = _record$_i[0], - field = _record$_i[1]; - - if (typeof value === "string") { - options = _this2.options; - } else if (isObject(value)) { - // let { value, ...options } = value - options = value; - value = options.value; - delete options.value; - - if (typeof value !== "string" && value !== undefined && value !== null) { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - options = _objectSpread(_objectSpread({}, _this2.options), options); - - if (err = _this2.normalize(options)) { - _this2.emit("error", err); - - return { - v: void 0 - }; - } - } else if (value === undefined || value === null) { - options = _this2.options; - } else { - _this2.emit("error", Error("Invalid Casting Value: returned value must return a string, an object, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: void 0 - }; - } - - var _options = options, - delimiter = _options.delimiter, - escape = _options.escape, - quote = _options.quote, - quoted = _options.quoted, - quoted_empty = _options.quoted_empty, - quoted_string = _options.quoted_string, - quoted_match = _options.quoted_match, - record_delimiter = _options.record_delimiter; - - if (value) { - if (typeof value !== 'string') { - _this2.emit("error", Error("Formatter must return a string, null or undefined, got ".concat(JSON.stringify(value)))); - - return { - v: null - }; - } - - var containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; - var containsQuote = quote !== '' && value.indexOf(quote) >= 0; - var containsEscape = value.indexOf(escape) >= 0 && escape !== quote; - var containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; - var quotedString = quoted_string && typeof field === 'string'; - var quotedMatch = quoted_match && quoted_match.filter(function (quoted_match) { - if (typeof quoted_match === 'string') { - return value.indexOf(quoted_match) !== -1; - } else { - return quoted_match.test(value); - } - }); - quotedMatch = quotedMatch && quotedMatch.length > 0; - var shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; - - if (shouldQuote === true && containsEscape === true) { - var regexp = escape === '\\' ? new RegExp(escape + escape, 'g') : new RegExp(escape, 'g'); - value = value.replace(regexp, escape + escape); - } - - if (containsQuote === true) { - var _regexp = new RegExp(quote, 'g'); - - value = value.replace(_regexp, escape + quote); - } - - if (shouldQuote === true) { - value = quote + value + quote; - } - - csvrecord += value; - } else if (quoted_empty === true || field === '' && quoted_string === true && quoted_empty !== false) { - csvrecord += quote + quote; - } - - if (_i3 !== record.length - 1) { - csvrecord += delimiter; - } - }; - - for (var _i3 = 0; _i3 < record.length; _i3++) { - var _ret = _loop(_i3); - - if (_typeof(_ret) === "object") return _ret.v; - } - - return csvrecord; - } - }, { - key: "bom", - value: function bom() { - if (this.options.bom !== true) { - return; - } - - this.push(bom_utf8); - } - }, { - key: "headers", - value: function headers() { - if (this.options.header === false) { - return; - } - - if (this.options.columns === undefined) { - return; - } - - var headers = this.options.columns.map(function (column) { - return column.header; - }); - - if (this.options.eof) { - headers = this.stringify(headers, true) + this.options.record_delimiter; - } else { - headers = this.stringify(headers); - } - - this.push(headers); - } - }, { - key: "__cast", - value: function __cast(value, context) { - var type = _typeof(value); - - try { - if (type === 'string') { - // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)]; - } else if (type === 'bigint') { - return [undefined, this.options.cast.bigint(value, context)]; - } else if (type === 'number') { - return [undefined, this.options.cast.number(value, context)]; - } else if (type === 'boolean') { - return [undefined, this.options.cast["boolean"](value, context)]; - } else if (value instanceof Date) { - return [undefined, this.options.cast.date(value, context)]; - } else if (type === 'object' && value !== null) { - return [undefined, this.options.cast.object(value, context)]; - } else { - return [undefined, value, value]; - } - } catch (err) { - return [err]; - } - } - }, { - key: "normalize_columns", - value: function normalize_columns(columns) { - if (columns === undefined || columns === null) { - return undefined; - } - - if (_typeof(columns) !== 'object') { - throw Error('Invalid option "columns": expect an array or an object'); - } - - if (!Array.isArray(columns)) { - var newcolumns = []; - - for (var k in columns) { - newcolumns.push({ - key: k, - header: columns[k] - }); - } - - columns = newcolumns; - } else { - var _newcolumns = []; - - var _iterator3 = _createForOfIteratorHelper(columns), - _step3; - - try { - for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) { - var column = _step3.value; - - if (typeof column === 'string') { - _newcolumns.push({ - key: column, - header: column - }); - } else if (_typeof(column) === 'object' && column !== undefined && !Array.isArray(column)) { - if (!column.key) { - throw Error('Invalid column definition: property "key" is required'); - } - - if (column.header === undefined) { - column.header = column.key; - } - - _newcolumns.push(column); - } else { - throw Error('Invalid column definition: expect a string or an object'); - } - } - } catch (err) { - _iterator3.e(err); - } finally { - _iterator3.f(); - } - - columns = _newcolumns; - } - - return columns; - } - }]); - - return Stringifier; -}(Transform); - -var stringify = function stringify() { - var data, options, callback; - - for (var _i4 in arguments) { - var argument = arguments[_i4]; - - var type = _typeof(argument); - - if (data === undefined && Array.isArray(argument)) { - data = argument; - } else if (options === undefined && isObject(argument)) { - options = argument; - } else if (callback === undefined && type === 'function') { - callback = argument; - } else { - throw new CsvError('CSV_INVALID_ARGUMENT', ['Invalid argument:', "got ".concat(JSON.stringify(argument), " at index ").concat(_i4)]); - } - } - - var stringifier = new Stringifier(options); - - if (callback) { - var chunks = []; - stringifier.on('readable', function () { - var chunk; - - while ((chunk = this.read()) !== null) { - chunks.push(chunk); - } - }); - stringifier.on('error', function (err) { - callback(err); - }); - stringifier.on('end', function () { - callback(undefined, chunks.join('')); - }); - } - - if (data !== undefined) { - // Give a chance for events to be registered later - if (typeof setImmediate === 'function') { - setImmediate(function () { - var _iterator4 = _createForOfIteratorHelper(data), - _step4; - - try { - for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { - var record = _step4.value; - stringifier.write(record); - } - } catch (err) { - _iterator4.e(err); - } finally { - _iterator4.f(); - } - - stringifier.end(); - }); - } else { - var _iterator5 = _createForOfIteratorHelper(data), - _step5; - - try { - for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) { - var record = _step5.value; - stringifier.write(record); - } - } catch (err) { - _iterator5.e(err); - } finally { - _iterator5.f(); - } - - stringifier.end(); - } - } - - return stringifier; -}; - -var CsvError = /*#__PURE__*/function (_Error) { - _inherits(CsvError, _Error); - - var _super2 = _createSuper(CsvError); - - function CsvError(code, message) { - var _this3; - - _classCallCheck(this, CsvError); - - if (Array.isArray(message)) message = message.join(' '); - _this3 = _super2.call(this, message); - - if (Error.captureStackTrace !== undefined) { - Error.captureStackTrace(_assertThisInitialized(_this3), CsvError); - } - - _this3.code = code; - - for (var _len = arguments.length, contexts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { - contexts[_key - 2] = arguments[_key]; - } - - for (var _i5 = 0, _contexts = contexts; _i5 < _contexts.length; _i5++) { - var context = _contexts[_i5]; - - for (var key in context) { - var value = context[key]; - _this3[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); - } - } - - return _this3; - } - - return CsvError; -}( /*#__PURE__*/_wrapNativeSuper(Error)); - -stringify.Stringifier = Stringifier; -stringify.CsvError = CsvError; -module.exports = stringify; - -var isObject = function isObject(obj) { - return _typeof(obj) === 'object' && obj !== null && !Array.isArray(obj); -}; - -var underscore = function underscore(str) { - return str.replace(/([A-Z])/g, function (_, match) { - return '_' + match.toLowerCase(); - }); -}; // Lodash implementation of `get` - - -var charCodeOfDot = '.'.charCodeAt(0); -var reEscapeChar = /\\(\\)?/g; -var rePropName = RegExp( // Match anything that isn't a dot or bracket. -'[^.[\\]]+' + '|' + // Or match property names within brackets. -'\\[(?:' + // Match a non-string expression. -'([^"\'][^[]*)' + '|' + // Or match strings (supports escaping characters). -'(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + ')\\]' + '|' + // Or match "" as the space between consecutive dots or empty brackets. -'(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))', 'g'); -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; -var reIsPlainProp = /^\w*$/; - -var getTag = function getTag(value) { - if (!value) value === undefined ? '[object Undefined]' : '[object Null]'; - return Object.prototype.toString.call(value); -}; - -var isKey = function isKey(value, object) { - if (Array.isArray(value)) { - return false; - } - - var type = _typeof(value); - - if (type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)) { - return true; - } - - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object); -}; - -var isSymbol = function isSymbol(value) { - var type = _typeof(value); - - return type === 'symbol' || type === 'object' && value && getTag(value) === '[object Symbol]'; -}; - -var stringToPath = function stringToPath(string) { - var result = []; - - if (string.charCodeAt(0) === charCodeOfDot) { - result.push(''); - } - - string.replace(rePropName, function (match, expression, quote, subString) { - var key = match; - - if (quote) { - key = subString.replace(reEscapeChar, '$1'); - } else if (expression) { - key = expression.trim(); - } - - result.push(key); - }); - return result; -}; - -var castPath = function castPath(value, object) { - if (Array.isArray(value)) { - return value; - } else { - return isKey(value, object) ? [value] : stringToPath(value); - } -}; - -var toKey = function toKey(value) { - if (typeof value === 'string' || isSymbol(value)) return value; - var result = "".concat(value); - return result == '0' && 1 / value == -INFINITY ? '-0' : result; -}; - -var get = function get(object, path) { - path = castPath(path, object); - var index = 0; - var length = path.length; - - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - - return index && index === length ? object : undefined; -}; \ No newline at end of file diff --git a/node_modules/csv-stringify/lib/es5/sync.d.ts b/node_modules/csv-stringify/lib/es5/sync.d.ts deleted file mode 100644 index 7c4aa9a..0000000 --- a/node_modules/csv-stringify/lib/es5/sync.d.ts +++ /dev/null @@ -1,6 +0,0 @@ -import * as csvStringify from './index' - -export = stringify - -declare function stringify(input: csvStringify.Input, options?: csvStringify.Options): string -declare namespace stringify {} diff --git a/node_modules/csv-stringify/lib/es5/sync.js b/node_modules/csv-stringify/lib/es5/sync.js deleted file mode 100644 index f8ad02d..0000000 --- a/node_modules/csv-stringify/lib/es5/sync.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -var stringify = require('.'); - -var _require = require('string_decoder'), - StringDecoder = _require.StringDecoder; - -module.exports = function (records) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var data = []; - - if (Buffer.isBuffer(records)) { - var decoder = new StringDecoder(); - records = decoder.write(records); - } - - function onData(record) { - if (record) { - data.push(record.toString()); - } - } - - var stringifier = new stringify.Stringifier(options); - stringifier.on('data', onData); - - var _iterator = _createForOfIteratorHelper(records), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var record = _step.value; - stringifier.write(record); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - stringifier.end(); - stringifier.off('data', onData); - return data.join(''); -}; \ No newline at end of file diff --git a/node_modules/csv-stringify/lib/index.d.ts b/node_modules/csv-stringify/lib/index.d.ts index 91d0c4d..4c28ef9 100644 --- a/node_modules/csv-stringify/lib/index.d.ts +++ b/node_modules/csv-stringify/lib/index.d.ts @@ -1,101 +1,125 @@ /// import * as stream from "stream"; -export = stringify -declare function stringify(callback?: stringify.Callback): stringify.Stringifier -declare function stringify(options: stringify.Options, callback?: stringify.Callback): stringify.Stringifier -declare function stringify(input: stringify.Input, callback?: stringify.Callback): stringify.Stringifier -declare function stringify(input: stringify.Input, options?: stringify.Options, callback?: stringify.Callback): stringify.Stringifier -declare namespace stringify { - type Callback = (err: Error | undefined, output: string) => void - type RecordDelimiter = string | Buffer | 'auto' | 'unix' | 'mac' | 'windows' | 'ascii' | 'unicode' - type Cast = (value: T, context: CastingContext) => string - type PlainObject = Record - type Input = any[] - interface ColumnOption { - key: string - header?: string - } - interface CastingContext { - readonly column?: number | string; - readonly header: boolean; - readonly index: number; - readonly records: number; - } - interface Options { - /** - * Prepend the byte order mark (BOM) to the output stream. - */ - bom?: boolean - /** - * Key-value object which defines custom cast for certain data types - */ - cast?: { - boolean?: Cast - date?: Cast - number?: Cast - /** - * Custom formatter for generic object values - */ - object?: Cast> - string?: Cast - } - /** - * List of fields, applied when `transform` returns an object - * order matters - * read the transformer documentation for additionnal information - * columns are auto discovered in the first record when the user write objects - * can refer to nested properties of the input JSON - * see the "header" option on how to print columns names on the first line - */ - columns?: string[] | PlainObject | ColumnOption[] - /** - * Set the field delimiter, one character only, defaults to a comma. - */ - delimiter?: string | Buffer - /** - * Add the value of "options.RecordDelimiter" on the last line, default to true. - */ - eof?: boolean - /** - * Defaults to the escape read option. - */ - escape?: string | Buffer - /** - * Display the column names on the first line if the columns option is provided or discovered. - */ - header?: boolean - /** - * The quote characters, defaults to the ", an empty quote value will preserve the original field. - */ - quote?: string | Buffer | boolean - /** - * Boolean, default to false, quote all the non-empty fields even if not required. - */ - quoted?: boolean +export type Callback = (err: Error | undefined, output: string) => void +export type RecordDelimiter = string | Buffer | 'unix' | 'mac' | 'windows' | 'ascii' | 'unicode' +export type CastReturnObject = { value: string } & Pick< + Options, + | 'delimiter' + | 'escape' + | 'quote' + | 'quoted' + | 'quoted_empty' + | 'quoted_string' + | 'quoted_match' + | 'record_delimiter' +> + +export type Cast = ( + value: T, + context: CastingContext +) => string | CastReturnObject; + +export type PlainObject = Record +export type Input = any[] +export interface ColumnOption { + key: string + header?: string +} +export interface CastingContext { + readonly column?: number | string; + readonly header: boolean; + readonly index: number; + readonly records: number; +} +export interface Options extends stream.TransformOptions { + /** + * Prepend the byte order mark (BOM) to the output stream. + */ + bom?: boolean + /** + * Key-value object which defines custom cast for certain data types + */ + cast?: { + boolean?: Cast + date?: Cast + number?: Cast + bigint?: Cast /** - * Boolean, no default, quote empty fields and overrides `quoted_string` on empty strings when defined. - */ - quoted_empty?: boolean - /** - * String or RegExp, no default, quote all fields matching a regular expression. - */ - quoted_match?: string | RegExp - /** - * Boolean, default to false, quote all fields of type string even if not required. - */ - quoted_string?: boolean - /** - * String used to delimit record rows or a special value - * special values are 'auto', 'unix', 'mac', 'windows', 'ascii', 'unicode' - * defaults to 'auto' (discovered in source or 'unix' if no source is specified). + * Custom formatter for generic object values */ - record_delimiter?: RecordDelimiter - } - class Stringifier extends stream.Transform { - constructor(options: Options) - readonly options: Options + object?: Cast> + string?: Cast } + /** + * List of fields, applied when `transform` returns an object + * order matters + * read the transformer documentation for additionnal information + * columns are auto discovered in the first record when the user write objects + * can refer to nested properties of the input JSON + * see the "header" option on how to print columns names on the first line + */ + columns?: string[] | PlainObject | ColumnOption[] + /** + * Set the field delimiter, one character only, defaults to a comma. + */ + delimiter?: string | Buffer + /** + * Add the value of "options.RecordDelimiter" on the last line, default to true. + */ + eof?: boolean + /** + * Defaults to the escape read option. + */ + escape?: string | Buffer + /** + * Display the column names on the first line if the columns option is provided or discovered. + */ + header?: boolean + /** + * The quote characters, defaults to the ", an empty quote value will preserve the original field. + */ + quote?: string | Buffer | boolean + /** + * Boolean, default to false, quote all the non-empty fields even if not required. + */ + quoted?: boolean + + /** + * Boolean, no default, quote empty fields and overrides `quoted_string` on empty strings when defined. + */ + quoted_empty?: boolean + /** + * String or RegExp, no default, quote all fields matching a regular expression. + */ + quoted_match?: string | RegExp | (string | RegExp)[] + /** + * Boolean, default to false, quote all fields of type string even if not required. + */ + quoted_string?: boolean + /** + * String used to delimit record rows or a special value + * special values are 'unix', 'mac', 'windows', 'ascii', 'unicode' + * defaults to '\n'. + */ + record_delimiter?: RecordDelimiter + /** + * Boolean, default to false, if true, fields that begin with `=`, `+`, `-`, `@`, `\t`, or `\r` will be prepended with a `'` to protected agains csv injection attacks + */ + escape_formulas?: boolean } + +export class Stringifier extends stream.Transform { + constructor(options: Options) + readonly options: Options +} + +declare function stringify(callback?: Callback): Stringifier +declare function stringify(options: Options, callback?: Callback): Stringifier +declare function stringify(input: Input, callback?: Callback): Stringifier +declare function stringify(input: Input, options?: Options, callback?: Callback): Stringifier + +// export default stringify +export { stringify } diff --git a/node_modules/csv-stringify/lib/index.js b/node_modules/csv-stringify/lib/index.js index c309ff9..81a9cc7 100644 --- a/node_modules/csv-stringify/lib/index.js +++ b/node_modules/csv-stringify/lib/index.js @@ -6,625 +6,115 @@ Please look at the [project documentation](https://csv.js.org/stringify/) for additional information. */ -const { Transform } = require('stream') -const bom_utf8 = Buffer.from([239, 187, 191]) +import { Transform } from 'stream'; +import { CsvError } from './api/CsvError.js'; +import { is_object } from './utils/is_object.js'; +import { stringifier } from './api/index.js'; +import { normalize_options } from './api/normalize_options.js'; class Stringifier extends Transform { constructor(opts = {}){ - super({...{writableObjectMode: true}, ...opts}) - const options = {} - let err - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - if(err = this.normalize(options)) throw err - switch(options.record_delimiter){ - case 'auto': - options.record_delimiter = null - break - case 'unix': - options.record_delimiter = "\n" - break - case 'mac': - options.record_delimiter = "\r" - break - case 'windows': - options.record_delimiter = "\r\n" - break - case 'ascii': - options.record_delimiter = "\u001e" - break - case 'unicode': - options.record_delimiter = "\u2028" - break - } + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; // Expose options - this.options = options + this.options = options; // Internal state this.state = { stop: false - } + }; // Information this.info = { records: 0 - } - } - normalize(options){ - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ - 'option `bom` is optional and must be a boolean value,', - `got ${JSON.stringify(options.bom)}` - ]) - } - // Normalize option `delimiter` - if(options.delimiter === undefined || options.delimiter === null){ - options.delimiter = ',' - }else if(Buffer.isBuffer(options.delimiter)){ - options.delimiter = options.delimiter.toString() - }else if(typeof options.delimiter !== 'string'){ - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ - 'option `delimiter` must be a buffer or a string,', - `got ${JSON.stringify(options.delimiter)}` - ]) - } - // Normalize option `quote` - if(options.quote === undefined || options.quote === null){ - options.quote = '"' - }else if(options.quote === true){ - options.quote = '"' - }else if(options.quote === false){ - options.quote = '' - }else if (Buffer.isBuffer(options.quote)){ - options.quote = options.quote.toString() - }else if(typeof options.quote !== 'string'){ - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ - 'option `quote` must be a boolean, a buffer or a string,', - `got ${JSON.stringify(options.quote)}` - ]) - } - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `quoted_empty` - if(options.quoted_empty === undefined || options.quoted_empty === null){ - options.quoted_empty = undefined - }else{ - // todo - } - // Normalize option `quoted_match` - if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ - options.quoted_match = null - }else if(!Array.isArray(options.quoted_match)){ - options.quoted_match = [options.quoted_match] - } - if(options.quoted_match){ - for(let quoted_match of options.quoted_match){ - const isString = typeof quoted_match === 'string' - const isRegExp = quoted_match instanceof RegExp - if(!isString && !isRegExp){ - return Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`) - } - } - } - // Normalize option `quoted_string` - if(options.quoted_string === undefined || options.quoted_string === null){ - options.quoted_string = false - }else{ - // todo - } - // Normalize option `eof` - if(options.eof === undefined || options.eof === null){ - options.eof = true - }else{ - // todo - } - // Normalize option `escape` - if(options.escape === undefined || options.escape === null){ - options.escape = '"' - }else if(Buffer.isBuffer(options.escape)){ - options.escape = options.escape.toString() - }else if(typeof options.escape !== 'string'){ - return Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`) - } - if (options.escape.length > 1){ - return Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`) - } - // Normalize option `header` - if(options.header === undefined || options.header === null){ - options.header = false - }else{ - // todo - } - // Normalize option `columns` - options.columns = this.normalize_columns(options.columns) - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `cast` - if(options.cast === undefined || options.cast === null){ - options.cast = {} - }else{ - // todo - } - // Normalize option cast.bigint - if(options.cast.bigint === undefined || options.cast.bigint === null){ - // Cast boolean to string by default - options.cast.bigint = value => '' + value - } - // Normalize option cast.boolean - if(options.cast.boolean === undefined || options.cast.boolean === null){ - // Cast boolean to string by default - options.cast.boolean = value => value ? '1' : '' - } - // Normalize option cast.date - if(options.cast.date === undefined || options.cast.date === null){ - // Cast date to timestamp string by default - options.cast.date = value => '' + value.getTime() - } - // Normalize option cast.number - if(options.cast.number === undefined || options.cast.number === null){ - // Cast number to string using native casting by default - options.cast.number = value => '' + value - } - // Normalize option cast.object - if(options.cast.object === undefined || options.cast.object === null){ - // Stringify object as JSON by default - options.cast.object = value => JSON.stringify(value) - } - // Normalize option cast.string - if(options.cast.string === undefined || options.cast.string === null){ - // Leave string untouched - options.cast.string = function(value){return value} - } - // Normalize option `record_delimiter` - if(options.record_delimiter === undefined || options.record_delimiter === null){ - options.record_delimiter = '\n' - }else if(Buffer.isBuffer(options.record_delimiter)){ - options.record_delimiter = options.record_delimiter.toString() - }else if(typeof options.record_delimiter !== 'string'){ - return Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`) - } + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; } _transform(chunk, encoding, callback){ if(this.state.stop === true){ - return - } - // Chunk validation - if(!Array.isArray(chunk) && typeof chunk !== 'object'){ - this.state.stop = true - return callback(Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`)) - } - // Detect columns from the first record - if(this.info.records === 0){ - if(Array.isArray(chunk)){ - if(this.options.header === true && !this.options.columns){ - this.state.stop = true - return callback(Error('Undiscoverable Columns: header option requires column option or object records')) - } - }else if(this.options.columns === undefined || this.options.columns === null){ - this.options.columns = this.normalize_columns(Object.keys(chunk)) - } - } - // Emit the header - if(this.info.records === 0){ - this.bom() - this.headers() + return; } - // Emit and stringify the record if an object or an array - try{ - this.emit('record', chunk, this.info.records) - }catch(err){ - this.state.stop = true - return this.emit('error', err) + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; } - // Convert the record into a string - let chunk_string - if(this.options.eof){ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - chunk_string = chunk_string + this.options.record_delimiter - } - }else{ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - if(this.options.header || this.info.records){ - chunk_string = this.options.record_delimiter + chunk_string - } - } - } - // Emit the csv - this.info.records++ - this.push(chunk_string) - callback() + callback(err); } _flush(callback){ - if(this.info.records === 0){ - this.bom() - this.headers() - } - callback() - } - stringify(chunk, chunkIsHeader=false){ - if(typeof chunk !== 'object'){ - return chunk - } - const {columns, header} = this.options - const record = [] - // Record is an array - if(Array.isArray(chunk)){ - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if(columns){ - chunk.splice(columns.length) - } - // Cast record elements - for(let i=0; i= 0 - const containsQuote = (quote !== '') && value.indexOf(quote) >= 0 - const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote) - const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0 - const quotedString = quoted_string && typeof field === 'string' - let quotedMatch = quoted_match && quoted_match.filter( quoted_match => { - if(typeof quoted_match === 'string'){ - return value.indexOf(quoted_match) !== -1 - }else{ - return quoted_match.test(value) - } - }) - quotedMatch = quotedMatch && quotedMatch.length > 0 - const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch - if(shouldQuote === true && containsEscape === true){ - const regexp = escape === '\\' - ? new RegExp(escape + escape, 'g') - : new RegExp(escape, 'g') - value = value.replace(regexp, escape + escape) - } - if(containsQuote === true){ - const regexp = new RegExp(quote,'g') - value = value.replace(regexp, escape + quote) - } - if(shouldQuote === true){ - value = quote + value + quote - } - csvrecord += value - }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ - csvrecord += quote + quote - } - if(i !== record.length - 1){ - csvrecord += delimiter - } - } - return csvrecord - } - bom(){ - if(this.options.bom !== true){ - return - } - this.push(bom_utf8) - } - headers(){ - if(this.options.header === false){ - return - } - if(this.options.columns === undefined){ - return - } - let headers = this.options.columns.map(column => column.header) - if(this.options.eof){ - headers = this.stringify(headers, true) + this.options.record_delimiter - }else{ - headers = this.stringify(headers) - } - this.push(headers) - } - __cast(value, context){ - const type = typeof value - try{ - if(type === 'string'){ // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)] - }else if(type === 'bigint'){ - return [undefined, this.options.cast.bigint(value, context)] - }else if(type === 'number'){ - return [undefined, this.options.cast.number(value, context)] - }else if(type === 'boolean'){ - return [undefined, this.options.cast.boolean(value, context)] - }else if(value instanceof Date){ - return [undefined, this.options.cast.date(value, context)] - }else if(type === 'object' && value !== null){ - return [undefined, this.options.cast.object(value, context)] - }else{ - return [undefined, value, value] - } - }catch(err){ - return [err] - } - } - normalize_columns(columns){ - if(columns === undefined || columns === null){ - return undefined - } - if(typeof columns !== 'object'){ - throw Error('Invalid option "columns": expect an array or an object') + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; } - if(!Array.isArray(columns)){ - const newcolumns = [] - for(let k in columns){ - newcolumns.push({ - key: k, - header: columns[k] - }) - } - columns = newcolumns - }else{ - const newcolumns = [] - for(let column of columns){ - if(typeof column === 'string'){ - newcolumns.push({ - key: column, - header: column - }) - }else if(typeof column === 'object' && column !== undefined && !Array.isArray(column)){ - if(!column.key){ - throw Error('Invalid column definition: property "key" is required') - } - if(column.header === undefined){ - column.header = column.key - } - newcolumns.push(column) - }else{ - throw Error('Invalid column definition: expect a string or an object') - } - } - columns = newcolumns + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); } - return columns + callback(); } } const stringify = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; if(data === undefined && (Array.isArray(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; }else if(callback === undefined && type === 'function'){ - callback = argument + callback = argument; }else{ throw new CsvError('CSV_INVALID_ARGUMENT', [ 'Invalid argument:', `got ${JSON.stringify(argument)} at index ${i}` - ]) + ]); } } - const stringifier = new Stringifier(options) + const stringifier = new Stringifier(options); if(callback){ - const chunks = [] + const chunks = []; stringifier.on('readable', function(){ - let chunk + let chunk; while((chunk = this.read()) !== null){ - chunks.push(chunk) + chunks.push(chunk); } - }) + }); stringifier.on('error', function(err){ - callback(err) - }) + callback(err); + }); stringifier.on('end', function(){ - callback(undefined, chunks.join('')) - }) + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); } if(data !== undefined){ - // Give a chance for events to be registered later + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate if(typeof setImmediate === 'function'){ - setImmediate(function(){ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - }) + setImmediate(writer); }else{ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - } - } - return stringifier -} - -class CsvError extends Error { - constructor(code, message, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)) - } + setTimeout(writer, 0); } } -} - -stringify.Stringifier = Stringifier - -stringify.CsvError = CsvError - -module.exports = stringify - -const isObject = function(obj){ - return typeof obj === 'object' && obj !== null && ! Array.isArray(obj) -} - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -// Lodash implementation of `get` + return stringifier; +}; -const charCodeOfDot = '.'.charCodeAt(0) -const reEscapeChar = /\\(\\)?/g -const rePropName = RegExp( - // Match anything that isn't a dot or bracket. - '[^.[\\]]+' + '|' + - // Or match property names within brackets. - '\\[(?:' + - // Match a non-string expression. - '([^"\'][^[]*)' + '|' + - // Or match strings (supports escaping characters). - '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + - ')\\]'+ '|' + - // Or match "" as the space between consecutive dots or empty brackets. - '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' -, 'g') -const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/ -const reIsPlainProp = /^\w*$/ -const getTag = function(value){ - if(!value) - value === undefined ? '[object Undefined]' : '[object Null]' - return Object.prototype.toString.call(value) -} -const isKey = function(value, object){ - if(Array.isArray(value)){ - return false - } - const type = typeof value - if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ - return true - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)) -} -const isSymbol = function(value){ - const type = typeof value - return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]') -} -const stringToPath = function(string){ - const result = [] - if(string.charCodeAt(0) === charCodeOfDot){ - result.push('') - } - string.replace(rePropName, function(match, expression, quote, subString){ - let key = match - if(quote){ - key = subString.replace(reEscapeChar, '$1') - }else if(expression){ - key = expression.trim() - } - result.push(key) - }) - return result -} -const castPath = function(value, object){ - if(Array.isArray(value)){ - return value - } else { - return isKey(value, object) ? [value] : stringToPath(value) - } -} -const toKey = function(value){ - if(typeof value === 'string' || isSymbol(value)) - return value - const result = `${value}` - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result -} -const get = function(object, path){ - path = castPath(path, object) - let index = 0 - const length = path.length - while(object != null && index < length){ - object = object[toKey(path[index++])] - } - return (index && index === length) ? object : undefined -} +// export default stringify +export { stringify, CsvError, Stringifier }; diff --git a/node_modules/csv-stringify/lib/sync.d.ts b/node_modules/csv-stringify/lib/sync.d.ts index 7c4aa9a..3814c21 100644 --- a/node_modules/csv-stringify/lib/sync.d.ts +++ b/node_modules/csv-stringify/lib/sync.d.ts @@ -1,6 +1,12 @@ -import * as csvStringify from './index' -export = stringify +import { Input, Options } from './index.js' -declare function stringify(input: csvStringify.Input, options?: csvStringify.Options): string -declare namespace stringify {} +declare function stringify(input: Input, options?: Options): string + +// export default stringify; +export { stringify }; + +export { + RecordDelimiter, Cast, PlainObject, Input, ColumnOption, CastingContext, + Options +} from './index.js'; diff --git a/node_modules/csv-stringify/lib/sync.js b/node_modules/csv-stringify/lib/sync.js index b44060f..8c8cb9d 100644 --- a/node_modules/csv-stringify/lib/sync.js +++ b/node_modules/csv-stringify/lib/sync.js @@ -1,24 +1,35 @@ -const stringify = require('.') -const {StringDecoder} = require('string_decoder') +import { stringifier } from './api/index.js'; +import { normalize_options } from './api/normalize_options.js'; -module.exports = function(records, options={}){ - const data = [] - if(Buffer.isBuffer(records)){ - const decoder = new StringDecoder() - records = decoder.write(records) +const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; } - function onData(record){ - if(record){ - data.push(record.toString()) - } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; } - let stringifier = new stringify.Stringifier(options) - stringifier.on('data', onData); - for(let record of records){ - stringifier.write(record) - } - stringifier.end() - stringifier.off('data', onData); - return data.join('') -} + return data.join(''); +}; + +export { stringify }; diff --git a/node_modules/csv-stringify/lib/utils/get.js b/node_modules/csv-stringify/lib/utils/get.js new file mode 100644 index 0000000..5dd9eff --- /dev/null +++ b/node_modules/csv-stringify/lib/utils/get.js @@ -0,0 +1,82 @@ + + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + if(!value) + value === undefined ? '[object Undefined]' : '[object Null]'; + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +export {get}; diff --git a/node_modules/csv-stringify/lib/utils/is_object.js b/node_modules/csv-stringify/lib/utils/is_object.js new file mode 100644 index 0000000..13c243b --- /dev/null +++ b/node_modules/csv-stringify/lib/utils/is_object.js @@ -0,0 +1,7 @@ + + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +export {is_object}; diff --git a/node_modules/csv-stringify/lib/utils/underscore.js b/node_modules/csv-stringify/lib/utils/underscore.js new file mode 100644 index 0000000..78397a3 --- /dev/null +++ b/node_modules/csv-stringify/lib/utils/underscore.js @@ -0,0 +1,9 @@ + + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +export { underscore }; diff --git a/node_modules/csv-stringify/package.json b/node_modules/csv-stringify/package.json index d2335a5..edd5c77 100644 --- a/node_modules/csv-stringify/package.json +++ b/node_modules/csv-stringify/package.json @@ -1,74 +1,119 @@ { - "version": "5.6.5", + "version": "6.4.6", "name": "csv-stringify", "description": "CSV stringifier implementing the Node.js `stream.Transform` API", "keywords": [ "csv", "stringify", - "stringifier" + "stringifier", + "backend", + "frontend" ], - "license": "MIT", - "repository": { - "type": "git", - "url": "http://www.github.com/adaltas/node-csv-stringify" - }, - "homepage": "https://csv.js.org/stringify/", "author": "David Worms (https://www.adaltas.com)", - "coffeelintConfig": { - "indentation": { - "level": "error", - "value": 2 - }, - "line_endings": { - "level": "error", - "value": "unix" - }, - "max_line_length": { - "level": "ignore" - } - }, "devDependencies": { - "@babel/cli": "^7.14.8", - "@babel/core": "^7.15.0", - "@babel/preset-env": "^7.15.0", - "@types/mocha": "^9.0.0", - "@types/node": "^16.7.8", + "@rollup/plugin-eslint": "^9.0.4", + "@rollup/plugin-node-resolve": "^15.2.1", + "@types/mocha": "^10.0.1", + "@types/node": "^20.5.6", "@types/should": "^13.0.0", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "coffeescript": "~2.5.1", - "csv-generate": "^3.4.3", - "each": "^1.2.2", - "express": "^4.17.1", - "mocha": "~9.1.1", + "coffeescript": "~2.7.0", + "csv-generate": "^4.4.0", + "each": "^2.4.0", + "eslint": "^8.47.0", + "express": "^4.18.2", + "mocha": "~10.2.0", + "rollup": "^3.28.1", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", "should": "~13.2.3", - "ts-node": "^10.2.1", - "typescript": "^4.4.2" + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./sync": { + "import": { + "types": "./lib/sync.d.ts", + "default": "./lib/sync.js" + }, + "require": { + "types": "./dist/cjs/sync.d.cts", + "default": "./dist/cjs/sync.cjs" + } + }, + "./browser/esm": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "./browser/esm/sync": { + "types": "./dist/esm/sync.d.ts", + "default": "./dist/esm/sync.js" + } }, "files": [ - "/lib" + "dist", + "lib" ], - "main": "./lib", + "homepage": "https://csv.js.org/stringify", + "license": "MIT", + "main": "./dist/cjs/index.cjs", "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "coffeescript/register", - "ts-node/register" - ], "inline-diffs": true, - "timeout": 40000, + "loader": "./test/loaders/all.js", + "recursive": true, "reporter": "spec", - "recursive": true + "require": [ + "should" + ], + "throw-deprecation": true, + "timeout": 40000 + }, + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-csv.git", + "directory": "packages/csv-stringify" }, "scripts": { - "build:babel": "cd lib && babel *.js -d es5 && cd ..", - "build:browserify": "browserify lib/index.js --transform babelify --standalone stringify > lib/browser/index.js && browserify lib/sync.js --transform babelify --standalone stringify > lib/browser/sync.js", - "build": "npm run build:babel && npm run build:browserify", - "preversion": "cp lib/*.ts lib/es5 && git add lib/es5/*.ts", + "build": "npm run build:rollup && npm run build:ts", + "build:rollup": "npx rollup -c", + "build:ts": "cp lib/index.d.ts dist/cjs/index.d.cts && cp lib/sync.d.ts dist/cjs/sync.d.cts && cp lib/*.ts dist/esm", + "postbuild:ts": "find dist/cjs -name '*.d.cts' -exec sh -c \"sed -i \"s/\\.js'/\\.cjs'/g\" {} || sed -i '' \"s/\\.js'/\\.cjs'/g\" {}\" \\;", + "lint": "npm run lint:lib && npm run lint:samples && npm run lint:test", + "postlint": "tsc --noEmit true", + "lint:lib": "eslint --fix lib/*.js", + "lint:samples": "eslint --fix samples/*.js", + "lint:test": "coffeelint --fix test/*.coffee", + "preversion": "npm run build && git add dist", "pretest": "npm run build", - "test": "mocha test/**/*.{coffee,ts}" + "test": "mocha 'test/**/*.{coffee,ts}'", + "test:legacy": "mocha --ignore test/api.callback.coffee --ignore test/api.web_stream.coffee --loader=./test/loaders/legacy/all.js 'test/**/*.{coffee,ts}'" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "typesVersions": { + "*": { + ".": [ + "dist/esm/index.d.ts" + ], + "sync": [ + "dist/esm/sync.d.ts" + ], + "browser/esm": [ + "dist/esm/index.d.ts" + ], + "browser/esm/sync": [ + "dist/esm/sync.d.ts" + ] + } }, - "types": "./lib/index.d.ts", - "gitHead": "0fd5209b6862655c384cda052abf38019b959e70" + "gitHead": "6575fc60ef848fb7fd3acbf5ff32130345fe1524" } diff --git a/node_modules/csv/README.md b/node_modules/csv/README.md index 1906750..4aa9417 100644 --- a/node_modules/csv/README.md +++ b/node_modules/csv/README.md @@ -1,37 +1,30 @@ -
-     _   _           _        _____  _______      __
-    | \ | |         | |      / ____|/ ____\ \    / /
-    |  \| | ___   __| | ___ | |    | (___  \ \  / /
-    | . ` |/ _ \ / _` |/ _ \| |     \___ \  \ \/ /
-    | |\  | (_) | (_| |  __/| |____ ____) |  \  /
-    |_| \_|\___/ \__,_|\___| \_____|_____/    \/     MIT License
+# CSV for Node.js and the web
 
-
+[![Build Status](https://img.shields.io/github/actions/workflow/status/adaltas/node-csv/nodejs.yml?branch=master)](https://github.com/adaltas/node-csv/actions) +[![NPM](https://img.shields.io/npm/dm/csv)](https://www.npmjs.com/package/csv) [![NPM](https://img.shields.io/npm/v/csv)](https://www.npmjs.com/package/csv) -This project provides CSV generation, parsing, transformation and serialization +The `csv` project provides CSV generation, parsing, transformation and serialization for Node.js. It has been tested and used by a large community over the years and should be considered reliable. It provides every option you would expect from an advanced CSV parser and stringifier. -[![NPM](https://img.shields.io/npm/dm/csv)](https://www.npmjs.com/package/csv) [![NPM](https://img.shields.io/npm/v/csv)](https://www.npmjs.com/package/csv) - -The `csv` package is itself split into 4 packages: - -* [`csv-generate`](https://csv.js.org/generate/), - a flexible generator of CSV string and Javascript objects. - [![Build Status](https://secure.travis-ci.org/adaltas/node-csv-generate.svg?branch=master)][travis-csv-generate] -* [`csv-parse`](https://csv.js.org/parse/), - a parser converting CSV text into arrays or objects. - [![Build Status](https://secure.travis-ci.org/adaltas/node-csv-parse.svg?branch=master)][travis-csv-parse] -* [`stream-transform`](https://csv.js.org/transform/), - a transformation framework. - [![Build Status](https://secure.travis-ci.org/adaltas/node-stream-transform.svg?branch=master)][travis-stream-transform] -* [`csv-stringify`](https://csv.js.org/stringify/), - a stringifier converting records into a CSV text. - [![Build Status](https://secure.travis-ci.org/adaltas/node-csv-stringify.svg?branch=master)][travis-csv-stringify] +This package exposes 4 packages: + +* [`csv-generate`](https://csv.js.org/generate/) + ([GitHub](https://github.com/adaltas/node-csv/tree/master/packages/csv-generate)), + a flexible generator of CSV string and Javascript objects. +* [`csv-parse`](https://csv.js.org/parse/) + ([GitHub](https://github.com/adaltas/node-csv/tree/master/packages/csv-parse)), + a parser converting CSV text into arrays or objects. +* [`csv-stringify`](https://csv.js.org/stringify/) + ([GitHub](https://github.com/adaltas/node-csv/tree/master/packages/csv-stringify)), + a stringifier converting records into a CSV text. +* [`stream-transform`](https://csv.js.org/transform/) + ([GitHub](https://github.com/adaltas/node-csv/tree/master/packages/stream-transform)), + a transformation framework. ## Documentation @@ -41,9 +34,42 @@ The full documentation for the current version is available [here](https://csv.j Installation command is `npm install csv`. -Each package is fully compatible with the stream 2 and 3 specifications. +Each package is fully compatible with the Node.js stream 2 and 3 specifications. Also, a simple callback-based API is always provided for convenience. +## Sample + +This example uses the Stream API to create a processing pipeline. + +```js +// Import the package +import * as csv from '../lib/index.js'; + +// Run the pipeline +csv +// Generate 20 records + .generate({ + delimiter: '|', + length: 20 + }) +// Transform CSV data into records + .pipe(csv.parse({ + delimiter: '|' + })) +// Transform each value into uppercase + .pipe(csv.transform((record) => { + return record.map((value) => { + return value.toUpperCase(); + }); + })) +// Convert objects into a stream + .pipe(csv.stringify({ + quoted: true + })) +// Print the CSV stream to stdout + .pipe(process.stdout); +``` + ## Development This parent project doesn't have tests itself but instead delegates the @@ -51,6 +77,12 @@ tests to its child projects. Read the documentation of the child projects for additional information. +## Contributors + +The project is sponsored by [Adaltas](https://www.adaltas.com), an Big Data consulting firm based in Paris, France. + +* David Worms: + ## Related projects * Pavel Kolesnikov "ya-csv": diff --git a/node_modules/csv/dist/cjs/index.cjs b/node_modules/csv/dist/cjs/index.cjs new file mode 100644 index 0000000..6afa193 --- /dev/null +++ b/node_modules/csv/dist/cjs/index.cjs @@ -0,0 +1,2525 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; +}; +util.inherits(Generator, stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; +}; + +const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(Buffer.isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!Buffer.isBuffer(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!Buffer.isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(Buffer.isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!Buffer.isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +class Parser extends stream.Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform$1(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } +} + +const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))){ + data = argument; + }else if(options === undefined && is_object$1(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError$1('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; +const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +class Stringifier extends stream.Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } +} + +const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; +}; + +exports.generate = generate; +exports.parse = parse; +exports.stringify = stringify; +exports.transform = transform; diff --git a/node_modules/csv/dist/cjs/index.d.cts b/node_modules/csv/dist/cjs/index.d.cts new file mode 100644 index 0000000..c9770f8 --- /dev/null +++ b/node_modules/csv/dist/cjs/index.d.cts @@ -0,0 +1,14 @@ + +// Alias to the modules exposing the stream and callback APIs + +import { generate } from 'csv-generate'; +import { parse } from 'csv-parse'; +import { transform } from 'stream-transform'; +import { stringify } from 'csv-stringify'; + +export { generate, parse, transform, stringify }; + +export * as generator from 'csv-generate'; +export * as parser from 'csv-parse'; +export * as transformer from 'stream-transform'; +export * as stringifier from 'csv-stringify'; diff --git a/node_modules/csv/dist/cjs/sync.cjs b/node_modules/csv/dist/cjs/sync.cjs new file mode 100644 index 0000000..41936de --- /dev/null +++ b/node_modules/csv/dist/cjs/sync.cjs @@ -0,0 +1,2338 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; +}; +util.inherits(Generator, stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } +}; + +let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +}; + +const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(Buffer.isBuffer(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!Buffer.isBuffer(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!Buffer.isBuffer(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!Buffer.isBuffer(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(Buffer.isBuffer(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!Buffer.isBuffer(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || Buffer.isBuffer(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! Buffer.isBuffer(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform$1(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(Buffer.isBuffer(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (Buffer.isBuffer(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(Buffer.isBuffer(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(Buffer.isBuffer(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; + +const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; +}; + +exports.generate = generate; +exports.parse = parse; +exports.stringify = stringify; +exports.transform = transform; diff --git a/node_modules/csv/dist/cjs/sync.d.cts b/node_modules/csv/dist/cjs/sync.d.cts new file mode 100644 index 0000000..b181259 --- /dev/null +++ b/node_modules/csv/dist/cjs/sync.d.cts @@ -0,0 +1,14 @@ + +// Alias to the modules exposing the sync APIs + +import { generate } from 'csv-generate/sync' +import { parse } from 'csv-parse/sync'; +import { transform } from 'stream-transform/sync'; +import { stringify } from 'csv-stringify/sync'; + +export { generate, parse, transform, stringify } + +export * as generator from 'csv-generate/sync'; +export * as parser from 'csv-parse/sync'; +export * as transformer from 'stream-transform/sync'; +export * as stringifier from 'csv-stringify/sync'; diff --git a/node_modules/csv/dist/esm/index.d.ts b/node_modules/csv/dist/esm/index.d.ts new file mode 100644 index 0000000..c9770f8 --- /dev/null +++ b/node_modules/csv/dist/esm/index.d.ts @@ -0,0 +1,14 @@ + +// Alias to the modules exposing the stream and callback APIs + +import { generate } from 'csv-generate'; +import { parse } from 'csv-parse'; +import { transform } from 'stream-transform'; +import { stringify } from 'csv-stringify'; + +export { generate, parse, transform, stringify }; + +export * as generator from 'csv-generate'; +export * as parser from 'csv-parse'; +export * as transformer from 'stream-transform'; +export * as stringifier from 'csv-stringify'; diff --git a/node_modules/csv/dist/esm/index.js b/node_modules/csv/dist/esm/index.js new file mode 100644 index 0000000..b989537 --- /dev/null +++ b/node_modules/csv/dist/esm/index.js @@ -0,0 +1,7713 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol$1(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; +}; +util.inherits(Generator, Stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; +}; + +const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform$1(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } +} + +const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer$1(argument))){ + data = argument; + }else if(options === undefined && is_object$1(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError$1('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, Stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; +const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } +} + +const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; +}; + +export { generate, parse, stringify, transform }; diff --git a/node_modules/csv/dist/esm/sync.d.ts b/node_modules/csv/dist/esm/sync.d.ts new file mode 100644 index 0000000..b181259 --- /dev/null +++ b/node_modules/csv/dist/esm/sync.d.ts @@ -0,0 +1,14 @@ + +// Alias to the modules exposing the sync APIs + +import { generate } from 'csv-generate/sync' +import { parse } from 'csv-parse/sync'; +import { transform } from 'stream-transform/sync'; +import { stringify } from 'csv-stringify/sync'; + +export { generate, parse, transform, stringify } + +export * as generator from 'csv-generate/sync'; +export * as parser from 'csv-parse/sync'; +export * as transformer from 'stream-transform/sync'; +export * as stringifier from 'csv-stringify/sync'; diff --git a/node_modules/csv/dist/esm/sync.js b/node_modules/csv/dist/esm/sync.js new file mode 100644 index 0000000..981bdfe --- /dev/null +++ b/node_modules/csv/dist/esm/sync.js @@ -0,0 +1,7526 @@ +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol$1(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; +}; + +// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. +const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } +}; + +const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; +}; + +const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } +}; + +const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; +}; +util.inherits(Generator, Stream.Readable); + +// Stop the generation. +Generator.prototype.end = function(){ + this.push(null); +}; +// Put new data into the read queue. +Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); +}; +Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); +}; +// Put new data into the read queue. +Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); +}; + +const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } +}; + +let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +}; + +const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); +}; + +const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; +}; + +class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } +} + +// white space characters +// https://en.wikipedia.org/wiki/Whitespace_character +// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types +// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff +const np = 12; +const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal +const space = 32; +const tab = 9; + +const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; +}; + +const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; +}; + +const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); +}; + +const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal +const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + +const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) +}; + +const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; +}; + +const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform$1(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; +}; + +// Lodash implementation of `get` + +const charCodeOfDot = '.'.charCodeAt(0); +const reEscapeChar = /\\(\\)?/g; +const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); +const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; +const reIsPlainProp = /^\w*$/; +const getTag = function(value){ + return Object.prototype.toString.call(value); +}; +const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); +}; +const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +}; +const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; +}; +const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } +}; +const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +}; +const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; +}; + +const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); +}; + +const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; +}; + +class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } +} + +const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); +}; + +const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; +}; + +const bom_utf8 = Buffer.from([239, 187, 191]); + +const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; +}; + +const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, Stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; + +const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; +}; + +export { generate, parse, stringify, transform }; diff --git a/node_modules/csv/dist/iife/index.js b/node_modules/csv/dist/iife/index.js new file mode 100644 index 0000000..5e749a3 --- /dev/null +++ b/node_modules/csv/dist/iife/index.js @@ -0,0 +1,7723 @@ +var csv = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol$1(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; + }; + + const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform$1(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } + } + + const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer$1(argument))){ + data = argument; + }else if(options === undefined && is_object$1(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError$1('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } + } + + const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; + }; + + exports.generate = generate; + exports.parse = parse; + exports.stringify = stringify; + exports.transform = transform; + + return exports; + +})({}); diff --git a/node_modules/csv/dist/iife/sync.js b/node_modules/csv/dist/iife/sync.js new file mode 100644 index 0000000..b27fdae --- /dev/null +++ b/node_modules/csv/dist/iife/sync.js @@ -0,0 +1,7536 @@ +var csv_sync = (function (exports) { + 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol$1(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } + }; + + let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + }; + + const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform$1(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + + const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; + }; + + exports.generate = generate; + exports.parse = parse; + exports.stringify = stringify; + exports.transform = transform; + + return exports; + +})({}); diff --git a/node_modules/csv/dist/umd/index.js b/node_modules/csv/dist/umd/index.js new file mode 100644 index 0000000..ca5627e --- /dev/null +++ b/node_modules/csv/dist/umd/index.js @@ -0,0 +1,7724 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol$1(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(){ + let options; + let callback; + if(arguments.length === 2){ + options = arguments[0]; + callback = arguments[1]; + }else if(arguments.length === 1){ + if(typeof arguments[0] === 'function'){ + options = {}; + callback = arguments[0]; + }else { + options = arguments[0]; + } + }else if(arguments.length === 0){ + options = {}; + } + const generator = new Generator(options); + if(callback){ + const data = []; + generator.on('readable', function(){ + let d; while((d = generator.read()) !== null){ + data.push(d); + } + }); + generator.on('error', callback); + generator.on('end', function(){ + if(generator.options.objectMode){ + callback(null, data); + }else { + if(generator.options.encoding){ + callback(null, data.join('')); + }else { + callback(null, Buffer.concat(data)); + } + } + }); + } + return generator; + }; + + const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + class Parser extends Transform { + constructor(opts = {}){ + super({...{readableObjectMode: true}, ...opts, encoding: null}); + this.api = transform$1(opts); + this.api.options.on_skip = (err, chunk) => { + this.emit('skip', err, chunk); + }; + // Backward compatibility + this.state = this.api.state; + this.options = this.api.options; + this.info = this.api.info; + } + // Implementation of `Transform._transform` + _transform(buf, _, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(buf, false, (record) => { + this.push(record); + }, () => { + this.push(null); + this.end(); + // Fix #333 and break #410 + // ko: api.stream.iterator.coffee + // ko with v21.4.0, ok with node v20.5.1: api.stream.finished # aborted (with generate()) + // ko: api.stream.finished # aborted (with Readable) + // this.destroy() + // Fix #410 and partially break #333 + // ok: api.stream.iterator.coffee + // ok: api.stream.finished # aborted (with generate()) + // broken: api.stream.finished # aborted (with Readable) + this.on('end', this.destroy); + }); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + // Implementation of `Transform._flush` + _flush(callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.parse(undefined, true, (record) => { + this.push(record); + }, () => { + this.push(null); + this.on('end', this.destroy); + }); + callback(err); + } + } + + const parse = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (typeof argument === 'string' || isBuffer$1(argument))){ + data = argument; + }else if(options === undefined && is_object$1(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError$1('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ], options || {}); + } + } + const parser = new Parser(options); + if(callback){ + const records = options === undefined || options.objname === undefined ? [] : {}; + parser.on('readable', function(){ + let record; + while((record = this.read()) !== null){ + if(options === undefined || options.objname === undefined){ + records.push(record); + }else { + records[record[0]] = record[1]; + } + } + }); + parser.on('error', function(err){ + callback(err, undefined, parser.api.__infoDataSet()); + }); + parser.on('end', function(){ + callback(undefined, records, parser.api.__infoDataSet()); + }); + } + if(data !== undefined){ + const writer = function(){ + parser.write(data); + parser.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return parser; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + class Stringifier extends Transform { + constructor(opts = {}){ + super({...{writableObjectMode: true}, ...opts}); + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + // Expose options + this.options = options; + // Internal state + this.state = { + stop: false + }; + // Information + this.info = { + records: 0 + }; + this.api = stringifier(this.options, this.state, this.info); + this.api.options.on_record = (...args) => { + this.emit('record', ...args); + }; + } + _transform(chunk, encoding, callback){ + if(this.state.stop === true){ + return; + } + const err = this.api.__transform(chunk, this.push.bind(this)); + if(err !== undefined){ + this.state.stop = true; + } + callback(err); + } + _flush(callback){ + if(this.state.stop === true){ + // Note, Node.js 12 call flush even after an error, we must prevent + // `callback` from being called in flush without any error. + return; + } + if(this.info.records === 0){ + this.api.bom(this.push.bind(this)); + const err = this.api.headers(this.push.bind(this)); + if(err) callback(err); + } + callback(); + } + } + + const stringify = function(){ + let data, options, callback; + for(const i in arguments){ + const argument = arguments[i]; + const type = typeof argument; + if(data === undefined && (Array.isArray(argument))){ + data = argument; + }else if(options === undefined && is_object(argument)){ + options = argument; + }else if(callback === undefined && type === 'function'){ + callback = argument; + }else { + throw new CsvError('CSV_INVALID_ARGUMENT', [ + 'Invalid argument:', + `got ${JSON.stringify(argument)} at index ${i}` + ]); + } + } + const stringifier = new Stringifier(options); + if(callback){ + const chunks = []; + stringifier.on('readable', function(){ + let chunk; + while((chunk = this.read()) !== null){ + chunks.push(chunk); + } + }); + stringifier.on('error', function(err){ + callback(err); + }); + stringifier.on('end', function(){ + try { + callback(undefined, chunks.join('')); + } catch (err) { + // This can happen if the `chunks` is extremely long; it may throw + // "Cannot create a string longer than 0x1fffffe8 characters" + // See [#386](https://github.com/adaltas/node-csv/pull/386) + callback(err); + return; + } + }); + } + if(data !== undefined){ + const writer = function(){ + for(const record of data){ + stringifier.write(record); + } + stringifier.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + return stringifier; + }; + + exports.generate = generate; + exports.parse = parse; + exports.stringify = stringify; + exports.transform = transform; + +})); diff --git a/node_modules/csv/dist/umd/sync.js b/node_modules/csv/dist/umd/sync.js new file mode 100644 index 0000000..403e3b7 --- /dev/null +++ b/node_modules/csv/dist/umd/sync.js @@ -0,0 +1,7537 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv_sync = {})); +})(this, (function (exports) { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol$1(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol$1, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const init_state$1 = (options) => { + // State + return { + start_time: options.duration ? Date.now() : null, + fixed_size_buffer: '', + count_written: 0, + count_created: 0, + }; + }; + + // Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. + const random = function(options={}){ + if(options.seed){ + return options.seed = options.seed * Math.PI * 100 % 100 / 100; + }else { + return Math.random(); + } + }; + + const types = { + // Generate an ASCII value. + ascii: function({options}){ + const column = []; + const nb_chars = Math.ceil(random(options) * options.maxWordLength); + for(let i=0; i { + // Convert Stream Readable options if underscored + if(opts.object_mode){ + opts.objectMode = opts.object_mode; + } + if(opts.high_water_mark){ + opts.highWaterMark = opts.high_water_mark; + } + // See https://nodejs.org/api/stream.html#stream_new_stream_readable_options + // Node.js 20 introduced `stream.getDefaultHighWaterMark(opts.objectMode)` + // opts.highWaterMark = opts.highWaterMark ?? (opts.objectMode ? 16 : 16384); + // opts.highWaterMark = opts.highWaterMark ?? stream.getDefaultHighWaterMark(opts.objectMode); + // Clone and camelize options + const options = {}; + for(const k in opts){ + options[camelize(k)] = opts[k]; + } + // Normalize options + const dft = { + columns: 8, + delimiter: ',', + duration: null, + encoding: null, + end: null, + eof: false, + fixedSize: false, + length: -1, + maxWordLength: 16, + rowDelimiter: '\n', + seed: false, + sleep: 0, + }; + for(const k in dft){ + if(options[k] === undefined){ + options[k] = dft[k]; + } + } + // Default values + if(options.eof === true){ + options.eof = options.rowDelimiter; + } + if(typeof options.columns === 'number'){ + options.columns = new Array(options.columns); + } + const accepted_header_types = Object.keys(types).filter((t) => (!['super_', 'camelize'].includes(t))); + for(let i = 0; i < options.columns.length; i++){ + const v = options.columns[i] || 'ascii'; + if(typeof v === 'string'){ + if(!accepted_header_types.includes(v)){ + throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`); + } + options.columns[i] = types[v]; + } + } + return options; + }; + + const read = (options, state, size, push, close) => { + // Already started + const data = []; + let recordsLength = 0; + // Get remaining buffer when fixedSize is enable + if (options.fixedSize) { + recordsLength = state.fixed_size_buffer.length; + if(recordsLength !== 0){ + data.push(state.fixed_size_buffer); + } + } + // eslint-disable-next-line + while(true){ + // Exit + if ( + state.count_created === options.length || + (options.end && Date.now() > options.end) || + (options.duration && Date.now() > state.start_time + options.duration) + ) { + // Flush + if (data.length) { + if (options.objectMode) { + for (const record of data) { + push(record); + } + } else { + push(data.join("") + (options.eof ? options.eof : "")); + } + state.end = true; + } else { + close(); + } + return; + } + // Create the record + let record = []; + let recordLength; + for(const fn of options.columns){ + const result = fn({options: options, state: state}); + const type = typeof result; + if(result !== null && type !== 'string' && type !== 'number'){ + close(Error([ + 'INVALID_VALUE:', + 'values returned by column function must be', + 'a string, a number or null,', + `got ${JSON.stringify(result)}` + ].join(' '))); + return; + } + record.push(result); + } + // Obtain record length + if(options.objectMode){ + recordLength = 0; + // recordLength is currently equal to the number of columns + // This is wrong and shall equal to 1 record only + for(const column of record){ + recordLength += column.length; + } + }else { + // Stringify the record + record = (state.count_created === 0 ? '' : options.rowDelimiter)+record.join(options.delimiter); + recordLength = record.length; + } + state.count_created++; + if(recordsLength + recordLength > size){ + if(options.objectMode){ + data.push(record); + for(const record of data){ + push(record); + } + }else { + if(options.fixedSize){ + state.fixed_size_buffer = record.substr(size - recordsLength); + data.push(record.substr(0, size - recordsLength)); + }else { + data.push(record); + } + push(data.join('')); + } + return; + } + recordsLength += recordLength; + data.push(record); + } + }; + + const Generator = function(options = {}){ + this.options = normalize_options$2(options); + // Call parent constructor + Stream.Readable.call(this, this.options); + this.state = init_state$1(this.options); + return this; + }; + util.inherits(Generator, Stream.Readable); + + // Stop the generation. + Generator.prototype.end = function(){ + this.push(null); + }; + // Put new data into the read queue. + Generator.prototype._read = function(size){ + setImmediate(() => { + this.__read(size); + }); + }; + Generator.prototype.__read = function(size){ + read(this.options, this.state, size, (chunk) => { + this.__push(chunk); + }, (err) => { + if(err){ + this.destroy(err); + }else { + this.push(null); + } + }); + }; + // Put new data into the read queue. + Generator.prototype.__push = function(record){ + const push = () => { + this.state.count_written++; + this.push(record); + if(this.state.end === true){ + return this.push(null); + } + }; + this.options.sleep > 0 ? setTimeout(push, this.options.sleep) : push(); + }; + + const generate = function(options){ + if(typeof options === 'string' && /\d+/.test(options)){ + options = parseInt(options); + } + if(Number.isInteger(options)){ + options = {length: options}; + }else if(typeof options !== 'object' || options === null){ + throw Error('Invalid Argument: options must be an object or an integer'); + } + if(!Number.isInteger(options.length)){ + throw Error('Invalid Argument: length is not defined'); + } + const chunks = []; + let work = true; + const generator = new Generator(options); + generator.push = function(chunk){ + if(chunk === null){ + return work = false; + } + chunks.push(chunk); + }; + while(work){ + generator.__read(options.highWaterMark); + } + if(!options.objectMode){ + return chunks.join(''); + }else { + return chunks; + } + }; + + let CsvError$1 = class CsvError extends Error { + constructor(code, message, options, ...contexts) { + if(Array.isArray(message)) message = message.join(' ').trim(); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + }; + + const is_object$1 = function(obj){ + return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)); + }; + + const normalize_columns_array = function(columns){ + const normalizedColumns = []; + for(let i = 0, l = columns.length; i < l; i++){ + const column = columns[i]; + if(column === undefined || column === null || column === false){ + normalizedColumns[i] = { disabled: true }; + }else if(typeof column === 'string'){ + normalizedColumns[i] = { name: column }; + }else if(is_object$1(column)){ + if(typeof column.name !== 'string'){ + throw new CsvError$1('CSV_OPTION_COLUMNS_MISSING_NAME', [ + 'Option columns missing name:', + `property "name" is required at position ${i}`, + 'when column is an object literal' + ]); + } + normalizedColumns[i] = column; + }else { + throw new CsvError$1('CSV_INVALID_COLUMN_DEFINITION', [ + 'Invalid column definition:', + 'expect a string or a literal object,', + `got ${JSON.stringify(column)} at position ${i}` + ]); + } + } + return normalizedColumns; + }; + + class ResizeableBuffer{ + constructor(size=100){ + this.size = size; + this.length = 0; + this.buf = Buffer.allocUnsafe(size); + } + prepend(val){ + if(isBuffer$1(val)){ + const length = this.length + val.length; + if(length >= this.size){ + this.resize(); + if(length >= this.size){ + throw Error('INVALID_BUFFER_STATE'); + } + } + const buf = this.buf; + this.buf = Buffer.allocUnsafe(this.size); + val.copy(this.buf, 0); + buf.copy(this.buf, val.length); + this.length += val.length; + }else { + const length = this.length++; + if(length === this.size){ + this.resize(); + } + const buf = this.clone(); + this.buf[0] = val; + buf.copy(this.buf,1, 0, length); + } + } + append(val){ + const length = this.length++; + if(length === this.size){ + this.resize(); + } + this.buf[length] = val; + } + clone(){ + return Buffer.from(this.buf.slice(0, this.length)); + } + resize(){ + const length = this.length; + this.size = this.size * 2; + const buf = Buffer.allocUnsafe(this.size); + this.buf.copy(buf,0, 0, length); + this.buf = buf; + } + toString(encoding){ + if(encoding){ + return this.buf.slice(0, this.length).toString(encoding); + }else { + return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)); + } + } + toJSON(){ + return this.toString('utf8'); + } + reset(){ + this.length = 0; + } + } + + // white space characters + // https://en.wikipedia.org/wiki/Whitespace_character + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types + // \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff + const np = 12; + const cr$1 = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl$1 = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + const space = 32; + const tab = 9; + + const init_state = function(options){ + return { + bomSkipped: false, + bufBytesStart: 0, + castField: options.cast_function, + commenting: false, + // Current error encountered by a record + error: undefined, + enabled: options.from_line === 1, + escaping: false, + escapeIsQuote: isBuffer$1(options.escape) && isBuffer$1(options.quote) && Buffer.compare(options.escape, options.quote) === 0, + // columns can be `false`, `true`, `Array` + expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, + field: new ResizeableBuffer(20), + firstLineToHeaders: options.cast_first_line_to_header, + needMoreDataSize: Math.max( + // Skip if the remaining buffer smaller than comment + options.comment !== null ? options.comment.length : 0, + // Skip if the remaining buffer can be delimiter + ...options.delimiter.map((delimiter) => delimiter.length), + // Skip if the remaining buffer can be escape sequence + options.quote !== null ? options.quote.length : 0, + ), + previousBuf: undefined, + quoting: false, + stop: false, + rawBuffer: new ResizeableBuffer(100), + record: [], + recordHasError: false, + record_length: 0, + recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 0 : Math.max(...options.record_delimiter.map((v) => v.length)), + trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], + wasQuoting: false, + wasRowDelimiter: false, + timchars: [ + Buffer.from(Buffer.from([cr$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([nl$1], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([np], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([space], 'utf8').toString(), options.encoding), + Buffer.from(Buffer.from([tab], 'utf8').toString(), options.encoding), + ] + }; + }; + + const underscore$1 = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options$1 = function(opts){ + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore$1(opt)] = opts[opt]; + } + // Normalize option `encoding` + // Note: defined first because other options depends on it + // to convert chars/strings into buffers. + if(options.encoding === undefined || options.encoding === true){ + options.encoding = 'utf8'; + }else if(options.encoding === null || options.encoding === false){ + options.encoding = null; + }else if(typeof options.encoding !== 'string' && options.encoding !== null){ + throw new CsvError$1('CSV_INVALID_OPTION_ENCODING', [ + 'Invalid option encoding:', + 'encoding must be a string or null to return a buffer,', + `got ${JSON.stringify(options.encoding)}` + ], options); + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_BOM', [ + 'Invalid option bom:', 'bom must be true,', + `got ${JSON.stringify(options.bom)}` + ], options); + } + // Normalize option `cast` + options.cast_function = null; + if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ + options.cast = undefined; + }else if(typeof options.cast === 'function'){ + options.cast_function = options.cast; + options.cast = true; + }else if(options.cast !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST', [ + 'Invalid option cast:', 'cast must be true or a function,', + `got ${JSON.stringify(options.cast)}` + ], options); + } + // Normalize option `cast_date` + if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ + options.cast_date = false; + }else if(options.cast_date === true){ + options.cast_date = function(value){ + const date = Date.parse(value); + return !isNaN(date) ? new Date(date) : value; + }; + }else if (typeof options.cast_date !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_CAST_DATE', [ + 'Invalid option cast_date:', 'cast_date must be true or a function,', + `got ${JSON.stringify(options.cast_date)}` + ], options); + } + // Normalize option `columns` + options.cast_first_line_to_header = null; + if(options.columns === true){ + // Fields in the first line are converted as-is to columns + options.cast_first_line_to_header = undefined; + }else if(typeof options.columns === 'function'){ + options.cast_first_line_to_header = options.columns; + options.columns = true; + }else if(Array.isArray(options.columns)){ + options.columns = normalize_columns_array(options.columns); + }else if(options.columns === undefined || options.columns === null || options.columns === false){ + options.columns = false; + }else { + throw new CsvError$1('CSV_INVALID_OPTION_COLUMNS', [ + 'Invalid option columns:', + 'expect an array, a function or true,', + `got ${JSON.stringify(options.columns)}` + ], options); + } + // Normalize option `group_columns_by_name` + if(options.group_columns_by_name === undefined || options.group_columns_by_name === null || options.group_columns_by_name === false){ + options.group_columns_by_name = false; + }else if(options.group_columns_by_name !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'expect an boolean,', + `got ${JSON.stringify(options.group_columns_by_name)}` + ], options); + }else if(options.columns === false){ + throw new CsvError$1('CSV_INVALID_OPTION_GROUP_COLUMNS_BY_NAME', [ + 'Invalid option group_columns_by_name:', + 'the `columns` mode must be activated.' + ], options); + } + // Normalize option `comment` + if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ + options.comment = null; + }else { + if(typeof options.comment === 'string'){ + options.comment = Buffer.from(options.comment, options.encoding); + } + if(!isBuffer$1(options.comment)){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment:', + 'comment must be a buffer or a string,', + `got ${JSON.stringify(options.comment)}` + ], options); + } + } + // Normalize option `comment_no_infix` + if(options.comment_no_infix === undefined || options.comment_no_infix === null || options.comment_no_infix === false){ + options.comment_no_infix = false; + }else if(options.comment_no_infix !== true){ + throw new CsvError$1('CSV_INVALID_OPTION_COMMENT', [ + 'Invalid option comment_no_infix:', + 'value must be a boolean,', + `got ${JSON.stringify(options.comment_no_infix)}` + ], options); + } + // Normalize option `delimiter` + const delimiter_json = JSON.stringify(options.delimiter); + if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter]; + if(options.delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + options.delimiter = options.delimiter.map(function(delimiter){ + if(delimiter === undefined || delimiter === null || delimiter === false){ + return Buffer.from(',', options.encoding); + } + if(typeof delimiter === 'string'){ + delimiter = Buffer.from(delimiter, options.encoding); + } + if(!isBuffer$1(delimiter) || delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_DELIMITER', [ + 'Invalid option delimiter:', + 'delimiter must be a non empty string or buffer or array of string|buffer,', + `got ${delimiter_json}` + ], options); + } + return delimiter; + }); + // Normalize option `escape` + if(options.escape === undefined || options.escape === true){ + options.escape = Buffer.from('"', options.encoding); + }else if(typeof options.escape === 'string'){ + options.escape = Buffer.from(options.escape, options.encoding); + }else if (options.escape === null || options.escape === false){ + options.escape = null; + } + if(options.escape !== null){ + if(!isBuffer$1(options.escape)){ + throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`); + } + } + // Normalize option `from` + if(options.from === undefined || options.from === null){ + options.from = 1; + }else { + if(typeof options.from === 'string' && /\d+/.test(options.from)){ + options.from = parseInt(options.from); + } + if(Number.isInteger(options.from)){ + if(options.from < 0){ + throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`); + } + }else { + throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`); + } + } + // Normalize option `from_line` + if(options.from_line === undefined || options.from_line === null){ + options.from_line = 1; + }else { + if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ + options.from_line = parseInt(options.from_line); + } + if(Number.isInteger(options.from_line)){ + if(options.from_line <= 0){ + throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`); + } + }else { + throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`); + } + } + // Normalize options `ignore_last_delimiters` + if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ + options.ignore_last_delimiters = false; + }else if(typeof options.ignore_last_delimiters === 'number'){ + options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters); + if(options.ignore_last_delimiters === 0){ + options.ignore_last_delimiters = false; + } + }else if(typeof options.ignore_last_delimiters !== 'boolean'){ + throw new CsvError$1('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ + 'Invalid option `ignore_last_delimiters`:', + 'the value must be a boolean value or an integer,', + `got ${JSON.stringify(options.ignore_last_delimiters)}` + ], options); + } + if(options.ignore_last_delimiters === true && options.columns === false){ + throw new CsvError$1('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ + 'The option `ignore_last_delimiters`', + 'requires the activation of the `columns` option' + ], options); + } + // Normalize option `info` + if(options.info === undefined || options.info === null || options.info === false){ + options.info = false; + }else if(options.info !== true){ + throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`); + } + // Normalize option `max_record_size` + if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ + options.max_record_size = 0; + }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0);else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ + options.max_record_size = parseInt(options.max_record_size); + }else { + throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`); + } + // Normalize option `objname` + if(options.objname === undefined || options.objname === null || options.objname === false){ + options.objname = undefined; + }else if(isBuffer$1(options.objname)){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty buffer`); + } + if(options.encoding === null);else { + options.objname = options.objname.toString(options.encoding); + } + }else if(typeof options.objname === 'string'){ + if(options.objname.length === 0){ + throw new Error(`Invalid Option: objname must be a non empty string`); + } + // Great, nothing to do + }else if(typeof options.objname === 'number');else { + throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`); + } + if(options.objname !== undefined){ + if(typeof options.objname === 'number'){ + if(options.columns !== false){ + throw Error('Invalid Option: objname index cannot be combined with columns or be defined as a field'); + } + }else { // A string or a buffer + if(options.columns === false){ + throw Error('Invalid Option: objname field must be combined with columns or be defined as an index'); + } + } + } + // Normalize option `on_record` + if(options.on_record === undefined || options.on_record === null){ + options.on_record = undefined; + }else if(typeof options.on_record !== 'function'){ + throw new CsvError$1('CSV_INVALID_OPTION_ON_RECORD', [ + 'Invalid option `on_record`:', + 'expect a function,', + `got ${JSON.stringify(options.on_record)}` + ], options); + } + // Normalize option `quote` + if(options.quote === null || options.quote === false || options.quote === ''){ + options.quote = null; + }else { + if(options.quote === undefined || options.quote === true){ + options.quote = Buffer.from('"', options.encoding); + }else if(typeof options.quote === 'string'){ + options.quote = Buffer.from(options.quote, options.encoding); + } + if(!isBuffer$1(options.quote)){ + throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`); + } + } + // Normalize option `raw` + if(options.raw === undefined || options.raw === null || options.raw === false){ + options.raw = false; + }else if(options.raw !== true){ + throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`); + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined){ + options.record_delimiter = []; + }else if(typeof options.record_delimiter === 'string' || isBuffer$1(options.record_delimiter)){ + if(options.record_delimiter.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = [options.record_delimiter]; + }else if(!Array.isArray(options.record_delimiter)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer,', + `got ${JSON.stringify(options.record_delimiter)}` + ], options); + } + options.record_delimiter = options.record_delimiter.map(function(rd, i){ + if(typeof rd !== 'string' && ! isBuffer$1(rd)){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a string, a buffer or array of string|buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + }else if(rd.length === 0){ + throw new CsvError$1('CSV_INVALID_OPTION_RECORD_DELIMITER', [ + 'Invalid option `record_delimiter`:', + 'value must be a non empty string or buffer', + `at index ${i},`, + `got ${JSON.stringify(rd)}` + ], options); + } + if(typeof rd === 'string'){ + rd = Buffer.from(rd, options.encoding); + } + return rd; + }); + // Normalize option `relax_column_count` + if(typeof options.relax_column_count === 'boolean');else if(options.relax_column_count === undefined || options.relax_column_count === null){ + options.relax_column_count = false; + }else { + throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`); + } + if(typeof options.relax_column_count_less === 'boolean');else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ + options.relax_column_count_less = false; + }else { + throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`); + } + if(typeof options.relax_column_count_more === 'boolean');else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ + options.relax_column_count_more = false; + }else { + throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`); + } + // Normalize option `relax_quotes` + if(typeof options.relax_quotes === 'boolean');else if(options.relax_quotes === undefined || options.relax_quotes === null){ + options.relax_quotes = false; + }else { + throw new Error(`Invalid Option: relax_quotes must be a boolean, got ${JSON.stringify(options.relax_quotes)}`); + } + // Normalize option `skip_empty_lines` + if(typeof options.skip_empty_lines === 'boolean');else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ + options.skip_empty_lines = false; + }else { + throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`); + } + // Normalize option `skip_records_with_empty_values` + if(typeof options.skip_records_with_empty_values === 'boolean');else if(options.skip_records_with_empty_values === undefined || options.skip_records_with_empty_values === null){ + options.skip_records_with_empty_values = false; + }else { + throw new Error(`Invalid Option: skip_records_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_records_with_empty_values)}`); + } + // Normalize option `skip_records_with_error` + if(typeof options.skip_records_with_error === 'boolean');else if(options.skip_records_with_error === undefined || options.skip_records_with_error === null){ + options.skip_records_with_error = false; + }else { + throw new Error(`Invalid Option: skip_records_with_error must be a boolean, got ${JSON.stringify(options.skip_records_with_error)}`); + } + // Normalize option `rtrim` + if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ + options.rtrim = false; + }else if(options.rtrim !== true){ + throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`); + } + // Normalize option `ltrim` + if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ + options.ltrim = false; + }else if(options.ltrim !== true){ + throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`); + } + // Normalize option `trim` + if(options.trim === undefined || options.trim === null || options.trim === false){ + options.trim = false; + }else if(options.trim !== true){ + throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`); + } + // Normalize options `trim`, `ltrim` and `rtrim` + if(options.trim === true && opts.ltrim !== false){ + options.ltrim = true; + }else if(options.ltrim !== true){ + options.ltrim = false; + } + if(options.trim === true && opts.rtrim !== false){ + options.rtrim = true; + }else if(options.rtrim !== true){ + options.rtrim = false; + } + // Normalize option `to` + if(options.to === undefined || options.to === null){ + options.to = -1; + }else { + if(typeof options.to === 'string' && /\d+/.test(options.to)){ + options.to = parseInt(options.to); + } + if(Number.isInteger(options.to)){ + if(options.to <= 0){ + throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`); + } + }else { + throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`); + } + } + // Normalize option `to_line` + if(options.to_line === undefined || options.to_line === null){ + options.to_line = -1; + }else { + if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ + options.to_line = parseInt(options.to_line); + } + if(Number.isInteger(options.to_line)){ + if(options.to_line <= 0){ + throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`); + } + }else { + throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`); + } + } + return options; + }; + + const isRecordEmpty = function(record){ + return record.every((field) => field == null || field.toString && field.toString().trim() === ''); + }; + + const cr = 13; // `\r`, carriage return, 0x0D in hexadécimal, 13 in decimal + const nl = 10; // `\n`, newline, 0x0A in hexadecimal, 10 in decimal + + const boms = { + // Note, the following are equals: + // Buffer.from("\ufeff") + // Buffer.from([239, 187, 191]) + // Buffer.from('EFBBBF', 'hex') + 'utf8': Buffer.from([239, 187, 191]), + // Note, the following are equals: + // Buffer.from "\ufeff", 'utf16le + // Buffer.from([255, 254]) + 'utf16le': Buffer.from([255, 254]) + }; + + const transform$1 = function(original_options = {}) { + const info = { + bytes: 0, + comment_lines: 0, + empty_lines: 0, + invalid_field_length: 0, + lines: 1, + records: 0 + }; + const options = normalize_options$1(original_options); + return { + info: info, + original_options: original_options, + options: options, + state: init_state(options), + __needMoreData: function(i, bufLen, end){ + if(end) return false; + const {encoding, escape, quote} = this.options; + const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state; + const numOfCharLeft = bufLen - i - 1; + const requiredLength = Math.max( + needMoreDataSize, + // Skip if the remaining buffer smaller than record delimiter + // If "record_delimiter" is yet to be discovered: + // 1. It is equals to `[]` and "recordDelimiterMaxLength" equals `0` + // 2. We set the length to windows line ending in the current encoding + // Note, that encoding is known from user or bom discovery at that point + // recordDelimiterMaxLength, + recordDelimiterMaxLength === 0 ? Buffer.from('\r\n', encoding).length : recordDelimiterMaxLength, + // Skip if remaining buffer can be an escaped quote + quoting ? ((escape === null ? 0 : escape.length) + quote.length) : 0, + // Skip if remaining buffer can be record delimiter following the closing quote + quoting ? (quote.length + recordDelimiterMaxLength) : 0, + ); + return numOfCharLeft < requiredLength; + }, + // Central parser implementation + parse: function(nextBuf, end, push, close){ + const {bom, comment_no_infix, encoding, from_line, ltrim, max_record_size,raw, relax_quotes, rtrim, skip_empty_lines, to, to_line} = this.options; + let {comment, escape, quote, record_delimiter} = this.options; + const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state; + let buf; + if(previousBuf === undefined){ + if(nextBuf === undefined){ + // Handle empty string + close(); + return; + }else { + buf = nextBuf; + } + }else if(previousBuf !== undefined && nextBuf === undefined){ + buf = previousBuf; + }else { + buf = Buffer.concat([previousBuf, nextBuf]); + } + // Handle UTF BOM + if(bomSkipped === false){ + if(bom === false){ + this.state.bomSkipped = true; + }else if(buf.length < 3){ + // No enough data + if(end === false){ + // Wait for more data + this.state.previousBuf = buf; + return; + } + }else { + for(const encoding in boms){ + if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ + // Skip BOM + const bomLength = boms[encoding].length; + this.state.bufBytesStart += bomLength; + buf = buf.slice(bomLength); + // Renormalize original options with the new encoding + this.options = normalize_options$1({...this.original_options, encoding: encoding}); + // Options will re-evaluate the Buffer with the new encoding + ({comment, escape, quote } = this.options); + break; + } + } + this.state.bomSkipped = true; + } + } + const bufLen = buf.length; + let pos; + for(pos = 0; pos < bufLen; pos++){ + // Ensure we get enough space to look ahead + // There should be a way to move this out of the loop + if(this.__needMoreData(pos, bufLen, end)){ + break; + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + if(to_line !== -1 && this.info.lines > to_line){ + this.state.stop = true; + close(); + return; + } + // Auto discovery of record_delimiter, unix, mac and windows supported + if(this.state.quoting === false && record_delimiter.length === 0){ + const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos); + if(record_delimiterCount){ + record_delimiter = this.options.record_delimiter; + } + } + const chr = buf[pos]; + if(raw === true){ + rawBuffer.append(chr); + } + if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false){ + this.state.wasRowDelimiter = true; + } + // Previous char was a valid escape char + // treat the current char as a regular char + if(this.state.escaping === true){ + this.state.escaping = false; + }else { + // Escape is only active inside quoted fields + // We are quoting, the char is an escape chr and there is a chr to escape + // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ + if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ + if(escapeIsQuote){ + if(this.__isQuote(buf, pos+escape.length)){ + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + }else { + this.state.escaping = true; + pos += escape.length - 1; + continue; + } + } + // Not currently escaping and chr is a quote + // TODO: need to compare bytes instead of single char + if(this.state.commenting === false && this.__isQuote(buf, pos)){ + if(this.state.quoting === true){ + const nextChr = buf[pos+quote.length]; + const isNextChrTrimable = rtrim && this.__isCharTrimable(buf, pos+quote.length); + const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr); + const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr); + const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length); + // Escape a quote + // Treat next char as a regular character + if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ + pos += escape.length - 1; + }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ + this.state.quoting = false; + this.state.wasQuoting = true; + pos += quote.length - 1; + continue; + }else if(relax_quotes === false){ + const err = this.__error( + new CsvError$1('CSV_INVALID_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + `got "${String.fromCharCode(nextChr)}"`, + `at line ${this.info.lines}`, + 'instead of delimiter, record delimiter, trimable character', + '(if activated) or comment', + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + this.state.quoting = false; + this.state.wasQuoting = true; + this.state.field.prepend(quote); + pos += quote.length - 1; + } + }else { + if(this.state.field.length !== 0){ + // In relax_quotes mode, treat opening quote preceded by chrs as regular + if(relax_quotes === false){ + const info = this.__infoField(); + const bom = Object.keys(boms).map(b => boms[b].equals(this.state.field.toString()) ? b : false).filter(Boolean)[0]; + const err = this.__error( + new CsvError$1('INVALID_OPENING_QUOTE', [ + 'Invalid Opening Quote:', + `a quote is found on field ${JSON.stringify(info.column)} at line ${info.lines}, value is ${JSON.stringify(this.state.field.toString(encoding))}`, + bom ? `(${bom} bom)` : undefined + ], this.options, info, { + field: this.state.field, + }) + ); + if(err !== undefined) return err; + } + }else { + this.state.quoting = true; + pos += quote.length - 1; + continue; + } + } + } + if(this.state.quoting === false){ + const recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos); + if(recordDelimiterLength !== 0){ + // Do not emit comments which take a full line + const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0); + if(skipCommentLine){ + this.info.comment_lines++; + // Skip full comment line + }else { + // Activate records emition if above from_line + if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ + this.state.enabled = true; + this.__resetField(); + this.__resetRecord(); + pos += recordDelimiterLength - 1; + continue; + } + // Skip if line is empty and skip_empty_lines activated + if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ + this.info.empty_lines++; + pos += recordDelimiterLength - 1; + continue; + } + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + if(to !== -1 && this.info.records >= to){ + this.state.stop = true; + close(); + return; + } + } + this.state.commenting = false; + pos += recordDelimiterLength - 1; + continue; + } + if(this.state.commenting){ + continue; + } + if(comment !== null && (comment_no_infix === false || (this.state.record.length === 0 && this.state.field.length === 0))) { + const commentCount = this.__compareBytes(comment, buf, pos, chr); + if(commentCount !== 0){ + this.state.commenting = true; + continue; + } + } + const delimiterLength = this.__isDelimiter(buf, pos, chr); + if(delimiterLength !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + pos += delimiterLength - 1; + continue; + } + } + } + if(this.state.commenting === false){ + if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ + return this.__error( + new CsvError$1('CSV_MAX_RECORD_SIZE', [ + 'Max Record Size:', + 'record exceed the maximum number of tolerated bytes', + `of ${max_record_size}`, + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + } + } + const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(buf, pos); + // rtrim in non quoting is handle in __onField + const rappend = rtrim === false || this.state.wasQuoting === false; + if(lappend === true && rappend === true){ + this.state.field.append(chr); + }else if(rtrim === true && !this.__isCharTrimable(buf, pos)){ + return this.__error( + new CsvError$1('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ + 'Invalid Closing Quote:', + 'found non trimable byte after quote', + `at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + }else { + if(lappend === false){ + pos += this.__isCharTrimable(buf, pos) - 1; + } + continue; + } + } + if(end === true){ + // Ensure we are not ending in a quoting state + if(this.state.quoting === true){ + const err = this.__error( + new CsvError$1('CSV_QUOTE_NOT_CLOSED', [ + 'Quote Not Closed:', + `the parsing is finished with an opening quote at line ${this.info.lines}`, + ], this.options, this.__infoField()) + ); + if(err !== undefined) return err; + }else { + // Skip last line if it has no characters + if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ + this.info.bytes = this.state.bufBytesStart + pos; + const errField = this.__onField(); + if(errField !== undefined) return errField; + const errRecord = this.__onRecord(push); + if(errRecord !== undefined) return errRecord; + }else if(this.state.wasRowDelimiter === true){ + this.info.empty_lines++; + }else if(this.state.commenting === true){ + this.info.comment_lines++; + } + } + }else { + this.state.bufBytesStart += pos; + this.state.previousBuf = buf.slice(pos); + } + if(this.state.wasRowDelimiter === true){ + this.info.lines++; + this.state.wasRowDelimiter = false; + } + }, + __onRecord: function(push){ + const {columns, group_columns_by_name, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_records_with_empty_values} = this.options; + const {enabled, record} = this.state; + if(enabled === false){ + return this.__resetRecord(); + } + // Convert the first line into column names + const recordLength = record.length; + if(columns === true){ + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + return this.__firstLineToColumns(record); + } + if(columns === false && this.info.records === 0){ + this.state.expectedRecordLength = recordLength; + } + if(recordLength !== this.state.expectedRecordLength){ + const err = columns === false ? + new CsvError$1('CSV_RECORD_INCONSISTENT_FIELDS_LENGTH', [ + 'Invalid Record Length:', + `expect ${this.state.expectedRecordLength},`, + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }) + : + new CsvError$1('CSV_RECORD_INCONSISTENT_COLUMNS', [ + 'Invalid Record Length:', + `columns length is ${columns.length},`, // rename columns + `got ${recordLength} on line ${this.info.lines}`, + ], this.options, this.__infoField(), { + record: record, + }); + if(relax_column_count === true || + (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || + (relax_column_count_more === true && recordLength > this.state.expectedRecordLength)){ + this.info.invalid_field_length++; + this.state.error = err; + // Error is undefined with skip_records_with_error + }else { + const finalErr = this.__error(err); + if(finalErr) return finalErr; + } + } + if(skip_records_with_empty_values === true && isRecordEmpty(record)){ + this.__resetRecord(); + return; + } + if(this.state.recordHasError === true){ + this.__resetRecord(); + this.state.recordHasError = false; + return; + } + this.info.records++; + if(from === 1 || this.info.records >= from){ + const {objname} = this.options; + // With columns, records are object + if(columns !== false){ + const obj = {}; + // Transform record array to an object + for(let i = 0, l = record.length; i < l; i++){ + if(columns[i] === undefined || columns[i].disabled) continue; + // Turn duplicate columns into an array + if (group_columns_by_name === true && obj[columns[i].name] !== undefined) { + if (Array.isArray(obj[columns[i].name])) { + obj[columns[i].name] = obj[columns[i].name].concat(record[i]); + } else { + obj[columns[i].name] = [obj[columns[i].name], record[i]]; + } + } else { + obj[columns[i].name] = record[i]; + } + } + // Without objname (default) + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: obj}, + (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), + (info === true ? {info: this.__infoRecord()}: {}) + ); + const err = this.__push( + objname === undefined ? extRecord : [obj[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? obj : [obj[objname], obj] + , push); + if(err){ + return err; + } + } + // Without columns, records are array + }else { + if(raw === true || info === true){ + const extRecord = Object.assign( + {record: record}, + raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, + info === true ? {info: this.__infoRecord()}: {} + ); + const err = this.__push( + objname === undefined ? extRecord : [record[objname], extRecord] + , push); + if(err){ + return err; + } + }else { + const err = this.__push( + objname === undefined ? record : [record[objname], record] + , push); + if(err){ + return err; + } + } + } + } + this.__resetRecord(); + }, + __firstLineToColumns: function(record){ + const {firstLineToHeaders} = this.state; + try{ + const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record); + if(!Array.isArray(headers)){ + return this.__error( + new CsvError$1('CSV_INVALID_COLUMN_MAPPING', [ + 'Invalid Column Mapping:', + 'expect an array from column function,', + `got ${JSON.stringify(headers)}` + ], this.options, this.__infoField(), { + headers: headers, + }) + ); + } + const normalizedHeaders = normalize_columns_array(headers); + this.state.expectedRecordLength = normalizedHeaders.length; + this.options.columns = normalizedHeaders; + this.__resetRecord(); + return; + }catch(err){ + return err; + } + }, + __resetRecord: function(){ + if(this.options.raw === true){ + this.state.rawBuffer.reset(); + } + this.state.error = undefined; + this.state.record = []; + this.state.record_length = 0; + }, + __onField: function(){ + const {cast, encoding, rtrim, max_record_size} = this.options; + const {enabled, wasQuoting} = this.state; + // Short circuit for the from_line options + if(enabled === false){ + return this.__resetField(); + } + let field = this.state.field.toString(encoding); + if(rtrim === true && wasQuoting === false){ + field = field.trimRight(); + } + if(cast === true){ + const [err, f] = this.__cast(field); + if(err !== undefined) return err; + field = f; + } + this.state.record.push(field); + // Increment record length if record size must not exceed a limit + if(max_record_size !== 0 && typeof field === 'string'){ + this.state.record_length += field.length; + } + this.__resetField(); + }, + __resetField: function(){ + this.state.field.reset(); + this.state.wasQuoting = false; + }, + __push: function(record, push){ + const {on_record} = this.options; + if(on_record !== undefined){ + const info = this.__infoRecord(); + try{ + record = on_record.call(null, record, info); + }catch(err){ + return err; + } + if(record === undefined || record === null){ return; } + } + push(record); + }, + // Return a tuple with the error and the casted value + __cast: function(field){ + const {columns, relax_column_count} = this.options; + const isColumns = Array.isArray(columns); + // Dont loose time calling cast + // because the final record is an object + // and this field can't be associated to a key present in columns + if(isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length){ + return [undefined, undefined]; + } + if(this.state.castField !== null){ + try{ + const info = this.__infoField(); + return [undefined, this.state.castField.call(null, field, info)]; + }catch(err){ + return [err]; + } + } + if(this.__isFloat(field)){ + return [undefined, parseFloat(field)]; + }else if(this.options.cast_date !== false){ + const info = this.__infoField(); + return [undefined, this.options.cast_date.call(null, field, info)]; + } + return [undefined, field]; + }, + // Helper to test if a character is a space or a line delimiter + __isCharTrimable: function(buf, pos){ + const isTrim = (buf, pos) => { + const {timchars} = this.state; + loop1: for(let i = 0; i < timchars.length; i++){ + const timchar = timchars[i]; + for(let j = 0; j < timchar.length; j++){ + if(timchar[j] !== buf[pos+j]) continue loop1; + } + return timchar.length; + } + return 0; + }; + return isTrim(buf, pos); + }, + // Keep it in case we implement the `cast_int` option + // __isInt(value){ + // // return Number.isInteger(parseInt(value)) + // // return !isNaN( parseInt( obj ) ); + // return /^(\-|\+)?[1-9][0-9]*$/.test(value) + // } + __isFloat: function(value){ + return (value - parseFloat(value) + 1) >= 0; // Borrowed from jquery + }, + __compareBytes: function(sourceBuf, targetBuf, targetPos, firstByte){ + if(sourceBuf[0] !== firstByte) return 0; + const sourceLength = sourceBuf.length; + for(let i = 1; i < sourceLength; i++){ + if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0; + } + return sourceLength; + }, + __isDelimiter: function(buf, pos, chr){ + const {delimiter, ignore_last_delimiters} = this.options; + if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ + return 0; + }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ + return 0; + } + loop1: for(let i = 0; i < delimiter.length; i++){ + const del = delimiter[i]; + if(del[0] === chr){ + for(let j = 1; j < del.length; j++){ + if(del[j] !== buf[pos+j]) continue loop1; + } + return del.length; + } + } + return 0; + }, + __isRecordDelimiter: function(chr, buf, pos){ + const {record_delimiter} = this.options; + const recordDelimiterLength = record_delimiter.length; + loop1: for(let i = 0; i < recordDelimiterLength; i++){ + const rd = record_delimiter[i]; + const rdLength = rd.length; + if(rd[0] !== chr){ + continue; + } + for(let j = 1; j < rdLength; j++){ + if(rd[j] !== buf[pos+j]){ + continue loop1; + } + } + return rd.length; + } + return 0; + }, + __isEscape: function(buf, pos, chr){ + const {escape} = this.options; + if(escape === null) return false; + const l = escape.length; + if(escape[0] === chr){ + for(let i = 0; i < l; i++){ + if(escape[i] !== buf[pos+i]){ + return false; + } + } + return true; + } + return false; + }, + __isQuote: function(buf, pos){ + const {quote} = this.options; + if(quote === null) return false; + const l = quote.length; + for(let i = 0; i < l; i++){ + if(quote[i] !== buf[pos+i]){ + return false; + } + } + return true; + }, + __autoDiscoverRecordDelimiter: function(buf, pos){ + const { encoding } = this.options; + // Note, we don't need to cache this information in state, + // It is only called on the first line until we find out a suitable + // record delimiter. + const rds = [ + // Important, the windows line ending must be before mac os 9 + Buffer.from('\r\n', encoding), + Buffer.from('\n', encoding), + Buffer.from('\r', encoding), + ]; + loop: for(let i = 0; i < rds.length; i++){ + const l = rds[i].length; + for(let j = 0; j < l; j++){ + if(rds[i][j] !== buf[pos + j]){ + continue loop; + } + } + this.options.record_delimiter.push(rds[i]); + this.state.recordDelimiterMaxLength = rds[i].length; + return rds[i].length; + } + return 0; + }, + __error: function(msg){ + const {encoding, raw, skip_records_with_error} = this.options; + const err = typeof msg === 'string' ? new Error(msg) : msg; + if(skip_records_with_error){ + this.state.recordHasError = true; + if(this.options.on_skip !== undefined){ + this.options.on_skip(err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + } + // this.emit('skip', err, raw ? this.state.rawBuffer.toString(encoding) : undefined); + return undefined; + }else { + return err; + } + }, + __infoDataSet: function(){ + return { + ...this.info, + columns: this.options.columns + }; + }, + __infoRecord: function(){ + const {columns, raw, encoding} = this.options; + return { + ...this.__infoDataSet(), + error: this.state.error, + header: columns === true, + index: this.state.record.length, + raw: raw ? this.state.rawBuffer.toString(encoding) : undefined + }; + }, + __infoField: function(){ + const {columns} = this.options; + const isColumns = Array.isArray(columns); + return { + ...this.__infoRecord(), + column: isColumns === true ? + (columns.length > this.state.record.length ? + columns[this.state.record.length].name : + null + ) : + this.state.record.length, + quoting: this.state.wasQuoting, + }; + } + }; + }; + + const parse = function(data, opts={}){ + if(typeof data === 'string'){ + data = Buffer.from(data); + } + const records = opts && opts.objname ? {} : []; + const parser = transform$1(opts); + const push = (record) => { + if(parser.options.objname === undefined) + records.push(record); + else { + records[record[0]] = record[1]; + } + }; + const close = () => {}; + const err1 = parser.parse(data, false, push, close); + if(err1 !== undefined) throw err1; + const err2 = parser.parse(undefined, true, push, close); + if(err2 !== undefined) throw err2; + return records; + }; + + // Lodash implementation of `get` + + const charCodeOfDot = '.'.charCodeAt(0); + const reEscapeChar = /\\(\\)?/g; + const rePropName = RegExp( + // Match anything that isn't a dot or bracket. + '[^.[\\]]+' + '|' + + // Or match property names within brackets. + '\\[(?:' + + // Match a non-string expression. + '([^"\'][^[]*)' + '|' + + // Or match strings (supports escaping characters). + '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + + ')\\]'+ '|' + + // Or match "" as the space between consecutive dots or empty brackets. + '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' + , 'g'); + const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/; + const reIsPlainProp = /^\w*$/; + const getTag = function(value){ + return Object.prototype.toString.call(value); + }; + const isSymbol = function(value){ + const type = typeof value; + return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]'); + }; + const isKey = function(value, object){ + if(Array.isArray(value)){ + return false; + } + const type = typeof value; + if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); + }; + const stringToPath = function(string){ + const result = []; + if(string.charCodeAt(0) === charCodeOfDot){ + result.push(''); + } + string.replace(rePropName, function(match, expression, quote, subString){ + let key = match; + if(quote){ + key = subString.replace(reEscapeChar, '$1'); + }else if(expression){ + key = expression.trim(); + } + result.push(key); + }); + return result; + }; + const castPath = function(value, object){ + if(Array.isArray(value)){ + return value; + } else { + return isKey(value, object) ? [value] : stringToPath(value); + } + }; + const toKey = function(value){ + if(typeof value === 'string' || isSymbol(value)) + return value; + const result = `${value}`; + // eslint-disable-next-line + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + }; + const get = function(object, path){ + path = castPath(path, object); + let index = 0; + const length = path.length; + while(object != null && index < length){ + object = object[toKey(path[index++])]; + } + return (index && index === length) ? object : undefined; + }; + + const is_object = function(obj){ + return typeof obj === 'object' && obj !== null && ! Array.isArray(obj); + }; + + const normalize_columns = function(columns){ + if(columns === undefined || columns === null){ + return [undefined, undefined]; + } + if(typeof columns !== 'object'){ + return [Error('Invalid option "columns": expect an array or an object')]; + } + if(!Array.isArray(columns)){ + const newcolumns = []; + for(const k in columns){ + newcolumns.push({ + key: k, + header: columns[k] + }); + } + columns = newcolumns; + }else { + const newcolumns = []; + for(const column of columns){ + if(typeof column === 'string'){ + newcolumns.push({ + key: column, + header: column + }); + }else if(typeof column === 'object' && column !== null && !Array.isArray(column)){ + if(!column.key){ + return [Error('Invalid column definition: property "key" is required')]; + } + if(column.header === undefined){ + column.header = column.key; + } + newcolumns.push(column); + }else { + return [Error('Invalid column definition: expect a string or an object')]; + } + } + columns = newcolumns; + } + return [undefined, columns]; + }; + + class CsvError extends Error { + constructor(code, message, ...contexts) { + if(Array.isArray(message)) message = message.join(' '); + super(message); + if(Error.captureStackTrace !== undefined){ + Error.captureStackTrace(this, CsvError); + } + this.code = code; + for(const context of contexts){ + for(const key in context){ + const value = context[key]; + this[key] = isBuffer$1(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)); + } + } + } + } + + const underscore = function(str){ + return str.replace(/([A-Z])/g, function(_, match){ + return '_' + match.toLowerCase(); + }); + }; + + const normalize_options = function(opts) { + const options = {}; + // Merge with user options + for(const opt in opts){ + options[underscore(opt)] = opts[opt]; + } + // Normalize option `bom` + if(options.bom === undefined || options.bom === null || options.bom === false){ + options.bom = false; + }else if(options.bom !== true){ + return [new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ + 'option `bom` is optional and must be a boolean value,', + `got ${JSON.stringify(options.bom)}` + ])]; + } + // Normalize option `delimiter` + if(options.delimiter === undefined || options.delimiter === null){ + options.delimiter = ','; + }else if(isBuffer$1(options.delimiter)){ + options.delimiter = options.delimiter.toString(); + }else if(typeof options.delimiter !== 'string'){ + return [new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ + 'option `delimiter` must be a buffer or a string,', + `got ${JSON.stringify(options.delimiter)}` + ])]; + } + // Normalize option `quote` + if(options.quote === undefined || options.quote === null){ + options.quote = '"'; + }else if(options.quote === true){ + options.quote = '"'; + }else if(options.quote === false){ + options.quote = ''; + }else if (isBuffer$1(options.quote)){ + options.quote = options.quote.toString(); + }else if(typeof options.quote !== 'string'){ + return [new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ + 'option `quote` must be a boolean, a buffer or a string,', + `got ${JSON.stringify(options.quote)}` + ])]; + } + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `escape_formulas` + if(options.escape_formulas === undefined || options.escape_formulas === null){ + options.escape_formulas = false; + }else if(typeof options.escape_formulas !== 'boolean'){ + return [new CsvError('CSV_OPTION_ESCAPE_FORMULAS_INVALID_TYPE', [ + 'option `escape_formulas` must be a boolean,', + `got ${JSON.stringify(options.escape_formulas)}` + ])]; + } + // Normalize option `quoted_empty` + if(options.quoted_empty === undefined || options.quoted_empty === null){ + options.quoted_empty = undefined; + } + // Normalize option `quoted_match` + if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ + options.quoted_match = null; + }else if(!Array.isArray(options.quoted_match)){ + options.quoted_match = [options.quoted_match]; + } + if(options.quoted_match){ + for(const quoted_match of options.quoted_match){ + const isString = typeof quoted_match === 'string'; + const isRegExp = quoted_match instanceof RegExp; + if(!isString && !isRegExp){ + return [Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`)]; + } + } + } + // Normalize option `quoted_string` + if(options.quoted_string === undefined || options.quoted_string === null){ + options.quoted_string = false; + } + // Normalize option `eof` + if(options.eof === undefined || options.eof === null){ + options.eof = true; + } + // Normalize option `escape` + if(options.escape === undefined || options.escape === null){ + options.escape = '"'; + }else if(isBuffer$1(options.escape)){ + options.escape = options.escape.toString(); + }else if(typeof options.escape !== 'string'){ + return [Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`)]; + } + if (options.escape.length > 1){ + return [Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`)]; + } + // Normalize option `header` + if(options.header === undefined || options.header === null){ + options.header = false; + } + // Normalize option `columns` + const [errColumns, columns] = normalize_columns(options.columns); + if(errColumns !== undefined) return [errColumns]; + options.columns = columns; + // Normalize option `quoted` + if(options.quoted === undefined || options.quoted === null){ + options.quoted = false; + } + // Normalize option `cast` + if(options.cast === undefined || options.cast === null){ + options.cast = {}; + } + // Normalize option cast.bigint + if(options.cast.bigint === undefined || options.cast.bigint === null){ + // Cast boolean to string by default + options.cast.bigint = value => '' + value; + } + // Normalize option cast.boolean + if(options.cast.boolean === undefined || options.cast.boolean === null){ + // Cast boolean to string by default + options.cast.boolean = value => value ? '1' : ''; + } + // Normalize option cast.date + if(options.cast.date === undefined || options.cast.date === null){ + // Cast date to timestamp string by default + options.cast.date = value => '' + value.getTime(); + } + // Normalize option cast.number + if(options.cast.number === undefined || options.cast.number === null){ + // Cast number to string using native casting by default + options.cast.number = value => '' + value; + } + // Normalize option cast.object + if(options.cast.object === undefined || options.cast.object === null){ + // Stringify object as JSON by default + options.cast.object = value => JSON.stringify(value); + } + // Normalize option cast.string + if(options.cast.string === undefined || options.cast.string === null){ + // Leave string untouched + options.cast.string = function(value){return value;}; + } + // Normalize option `on_record` + if(options.on_record !== undefined && typeof options.on_record !== 'function'){ + return [Error(`Invalid Option: "on_record" must be a function.`)]; + } + // Normalize option `record_delimiter` + if(options.record_delimiter === undefined || options.record_delimiter === null){ + options.record_delimiter = '\n'; + }else if(isBuffer$1(options.record_delimiter)){ + options.record_delimiter = options.record_delimiter.toString(); + }else if(typeof options.record_delimiter !== 'string'){ + return [Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`)]; + } + switch(options.record_delimiter){ + case 'unix': + options.record_delimiter = "\n"; + break; + case 'mac': + options.record_delimiter = "\r"; + break; + case 'windows': + options.record_delimiter = "\r\n"; + break; + case 'ascii': + options.record_delimiter = "\u001e"; + break; + case 'unicode': + options.record_delimiter = "\u2028"; + break; + } + return [undefined, options]; + }; + + const bom_utf8 = Buffer.from([239, 187, 191]); + + const stringifier = function(options, state, info){ + return { + options: options, + state: state, + info: info, + __transform: function(chunk, push){ + // Chunk validation + if(!Array.isArray(chunk) && typeof chunk !== 'object'){ + return Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`); + } + // Detect columns from the first record + if(this.info.records === 0){ + if(Array.isArray(chunk)){ + if(this.options.header === true && this.options.columns === undefined){ + return Error('Undiscoverable Columns: header option requires column option or object records'); + } + }else if(this.options.columns === undefined){ + const [err, columns] = normalize_columns(Object.keys(chunk)); + if(err) return; + this.options.columns = columns; + } + } + // Emit the header + if(this.info.records === 0){ + this.bom(push); + const err = this.headers(push); + if(err) return err; + } + // Emit and stringify the record if an object or an array + try{ + // this.emit('record', chunk, this.info.records); + if(this.options.on_record){ + this.options.on_record(chunk, this.info.records); + } + }catch(err){ + return err; + } + // Convert the record into a string + let err, chunk_string; + if(this.options.eof){ + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + chunk_string = chunk_string + this.options.record_delimiter; + } + }else { + [err, chunk_string] = this.stringify(chunk); + if(err) return err; + if(chunk_string === undefined){ + return; + }else { + if(this.options.header || this.info.records){ + chunk_string = this.options.record_delimiter + chunk_string; + } + } + } + // Emit the csv + this.info.records++; + push(chunk_string); + }, + stringify: function(chunk, chunkIsHeader=false){ + if(typeof chunk !== 'object'){ + return [undefined, chunk]; + } + const {columns} = this.options; + const record = []; + // Record is an array + if(Array.isArray(chunk)){ + // We are getting an array but the user has specified output columns. In + // this case, we respect the columns indexes + if(columns){ + chunk.splice(columns.length); + } + // Cast record elements + for(let i=0; i { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + const shouldQuote = quotedMatch || true === quoted_empty || + (true === quoted_string && false !== quoted_empty); + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(value){ + if(typeof value !== 'string'){ + return [Error(`Formatter must return a string, null or undefined, got ${JSON.stringify(value)}`)]; + } + const containsdelimiter = delimiter.length && value.indexOf(delimiter) >= 0; + const containsQuote = (quote !== '') && value.indexOf(quote) >= 0; + const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote); + const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0; + const quotedString = quoted_string && typeof field === 'string'; + let quotedMatch = quoted_match && quoted_match.filter(quoted_match => { + if(typeof quoted_match === 'string'){ + return value.indexOf(quoted_match) !== -1; + }else { + return quoted_match.test(value); + } + }); + quotedMatch = quotedMatch && quotedMatch.length > 0; + // See https://github.com/adaltas/node-csv/pull/387 + // More about CSV injection or formula injection, when websites embed + // untrusted input inside CSV files: + // https://owasp.org/www-community/attacks/CSV_Injection + // http://georgemauer.net/2017/10/07/csv-injection.html + // Apple Numbers unicode normalization is empirical from testing + if (escape_formulas) { + switch (value[0]) { + case '=': + case '+': + case '-': + case '@': + case '\t': + case '\r': + case '\uFF1D': // Unicode '=' + case '\uFF0B': // Unicode '+' + case '\uFF0D': // Unicode '-' + case '\uFF20': // Unicode '@' + value = `'${value}`; + break; + } + } + const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch; + if(shouldQuote === true && containsEscape === true){ + const regexp = escape === '\\' + ? new RegExp(escape + escape, 'g') + : new RegExp(escape, 'g'); + value = value.replace(regexp, escape + escape); + } + if(containsQuote === true){ + const regexp = new RegExp(quote,'g'); + value = value.replace(regexp, escape + quote); + } + if(shouldQuote === true){ + value = quote + value + quote; + } + csvrecord += value; + }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ + csvrecord += quote + quote; + } + if(i !== record.length - 1){ + csvrecord += delimiter; + } + } + return [undefined, csvrecord]; + }, + bom: function(push){ + if(this.options.bom !== true){ + return; + } + push(bom_utf8); + }, + headers: function(push){ + if(this.options.header === false){ + return; + } + if(this.options.columns === undefined){ + return; + } + let err; + let headers = this.options.columns.map(column => column.header); + if(this.options.eof){ + [err, headers] = this.stringify(headers, true); + headers += this.options.record_delimiter; + }else { + [err, headers] = this.stringify(headers); + } + if(err) return err; + push(headers); + }, + __cast: function(value, context){ + const type = typeof value; + try{ + if(type === 'string'){ // Fine for 99% of the cases + return [undefined, this.options.cast.string(value, context)]; + }else if(type === 'bigint'){ + return [undefined, this.options.cast.bigint(value, context)]; + }else if(type === 'number'){ + return [undefined, this.options.cast.number(value, context)]; + }else if(type === 'boolean'){ + return [undefined, this.options.cast.boolean(value, context)]; + }else if(value instanceof Date){ + return [undefined, this.options.cast.date(value, context)]; + }else if(type === 'object' && value !== null){ + return [undefined, this.options.cast.object(value, context)]; + }else { + return [undefined, value, value]; + } + }catch(err){ + return [err]; + } + } + }; + }; + + const stringify = function(records, opts={}){ + const data = []; + const [err, options] = normalize_options(opts); + if(err !== undefined) throw err; + const state = { + stop: false + }; + // Information + const info = { + records: 0 + }; + const api = stringifier(options, state, info); + for(const record of records){ + const err = api.__transform(record, function(record){ + data.push(record); + }); + if(err !== undefined) throw err; + } + if(data.length === 0){ + api.bom((d) => { + data.push(d); + }); + const err = api.headers((headers) => { + data.push(headers); + }); + if(err !== undefined) throw err; + } + return data.join(''); + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + + const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; + }; + + exports.generate = generate; + exports.parse = parse; + exports.stringify = stringify; + exports.transform = transform; + +})); diff --git a/node_modules/csv/lib/browser/index.js b/node_modules/csv/lib/browser/index.js deleted file mode 100644 index 53bce88..0000000 --- a/node_modules/csv/lib/browser/index.js +++ /dev/null @@ -1,10947 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (name === '__proto__') { - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; -}; - -exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; - -},{}],2:[function(require,module,exports){ -(function (Buffer){(function (){ - -/* -CSV Generate - main module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ - -const stream = require('stream') -const util = require('util') - -module.exports = function(){ - let options - let callback - if(arguments.length === 2){ - options = arguments[0] - callback = arguments[1] - }else if(arguments.length === 1){ - if(typeof arguments[0] === 'function'){ - options = {} - callback = arguments[0] - }else{ - options = arguments[0] - } - }else if(arguments.length === 0){ - options = {} - } - const generator = new Generator(options) - if(callback){ - const data = [] - generator.on('readable', function(){ - let d; while(d = generator.read()){ - data.push(d) - } - }) - generator.on('error', callback) - generator.on('end', function(){ - if(generator.options.objectMode){ - callback(null, data) - }else{ - if(generator.options.encoding){ - callback(null, data.join('')) - }else{ - callback(null, Buffer.concat(data)) - } - } - }) - } - return generator -} - -Generator = function(options = {}){ - // Convert Stream Readable options if underscored - if(options.high_water_mark){ - options.highWaterMark = options.high_water_mark - } - if(options.object_mode){ - options.objectMode = options.object_mode - } - // Call parent constructor - stream.Readable.call(this, options) - // Clone and camelize options - this.options = {} - for(let k in options){ - this.options[Generator.camelize(k)] = options[k] - } - // Normalize options - const dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0, - } - for(const k in dft){ - if(this.options[k] === undefined){ - this.options[k] = dft[k] - } - } - // Default values - if(this.options.eof === true){ - this.options.eof = this.options.rowDelimiter - } - // State - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0, - } - if(typeof this.options.columns === 'number'){ - this.options.columns = new Array(this.options.columns) - } - const accepted_header_types = Object.keys(Generator).filter( (t) => ( !['super_', 'camelize'].includes(t) )) - for(let i = 0; i < this.options.columns.length; i++){ - const v = this.options.columns[i] || 'ascii' - if(typeof v === 'string'){ - if(!accepted_header_types.includes(v)){ - throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`) - } - this.options.columns[i] = Generator[v] - } - } - return this -} -util.inherits(Generator, stream.Readable) -// Export the class -module.exports.Generator = Generator -// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. -Generator.prototype.random = function(){ - if(this.options.seed){ - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100 - }else{ - return Math.random() - } -} -// Stop the generation. -Generator.prototype.end = function(){ - this.push(null) -} -// Put new data into the read queue. -Generator.prototype._read = function(size){ - // Already started - const data = [] - let length = this._.fixed_size_buffer.length - if(length !== 0){ - data.push(this._.fixed_size_buffer) - } - while(true){ - // Time for some rest: flush first and stop later - if( (this._.count_created === this.options.length) || (this.options.end && Date.now() > this.options.end) || (this.options.duration && Date.now() > this._.start_time + this.options.duration) ){ - // Flush - if(data.length){ - if(this.options.objectMode){ - for(const line of data){ - this.__push(line) - } - }else{ - this.__push(data.join('') + (this.options.eof ? this.options.eof : '')) - } - } - // Stop - return this.push(null) - } - // Create the line - let line = [] - let lineLength - this.options.columns.forEach((fn) => { - line.push(fn(this)) - }) - // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - if(this.options.objectMode){ - lineLength = 0 - for(const column of line) - lineLength += column.length - }else{ - // Stringify the line - line = (this._.count_created === 0 ? '' : this.options.rowDelimiter)+line.join(this.options.delimiter) - lineLength = line.length - } - this._.count_created++ - if(length + lineLength > size){ - if(this.options.objectMode){ - data.push(line) - for(const line of data){ - this.__push(line) - } - }else{ - if(this.options.fixedSize){ - this._.fixed_size_buffer = line.substr(size - length) - data.push(line.substr(0, size - length)) - }else{ - data.push(line) - } - this.__push(data.join('')) - } - return - } - length += lineLength - data.push(line) - } -} -// Put new data into the read queue. -Generator.prototype.__push = function(record){ - this._.count_written++ - if(this.options.sleep > 0){ - setTimeout( () => { - this.push(record) - }, this.options.sleep) - }else{ - this.push(record) - } -} -// Generate an ASCII value. -Generator.ascii = function(gen){ - // Column - const column = [] - const nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength) - for(let i=0; i= this.size){ - this.resize() - if(length >= this.size){ - throw Error('INVALID_BUFFER_STATE') - } - } - const buf = this.buf - this.buf = Buffer.alloc(this.size) - val.copy(this.buf, 0) - buf.copy(this.buf, val.length) - this.length += val.length - }else{ - const length = this.length++ - if(length === this.size){ - this.resize() - } - const buf = this.clone() - this.buf[0] = val - buf.copy(this.buf,1, 0, length) - } - } - append(val){ - const length = this.length++ - if(length === this.size){ - this.resize() - } - this.buf[length] = val - } - clone(){ - return Buffer.from(this.buf.slice(0, this.length)) - } - resize(){ - const length = this.length - this.size = this.size * 2 - const buf = Buffer.alloc(this.size) - this.buf.copy(buf,0, 0, length) - this.buf = buf - } - toString(encoding){ - if(encoding){ - return this.buf.slice(0, this.length).toString(encoding) - }else{ - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)) - } - } - toJSON(){ - return this.toString('utf8') - } - reset(){ - this.length = 0 - } -} - -module.exports = ResizeableBuffer - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":10}],4:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ - -/* -CSV Parse - -Please look at the [project documentation](https://csv.js.org/parse/) for -additional information. -*/ - -const { Transform } = require('stream') -const ResizeableBuffer = require('./ResizeableBuffer') - -// white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff -const tab = 9 -const nl = 10 // \n, 0x0A in hexadecimal, 10 in decimal -const np = 12 -const cr = 13 // \r, 0x0D in hexadécimal, 13 in decimal -const space = 32 -const boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -} - -class Parser extends Transform { - constructor(opts = {}){ - super({...{readableObjectMode: true}, ...opts, encoding: null}) - this.__originalOptions = opts - this.__normalizeOptions(opts) - } - __normalizeOptions(opts){ - const options = {} - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - if(options.encoding === undefined || options.encoding === true){ - options.encoding = 'utf8' - }else if(options.encoding === null || options.encoding === false){ - options.encoding = null - }else if(typeof options.encoding !== 'string' && options.encoding !== null){ - throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ - 'Invalid option encoding:', - 'encoding must be a string or null to return a buffer,', - `got ${JSON.stringify(options.encoding)}` - ], options) - } - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - throw new CsvError('CSV_INVALID_OPTION_BOM', [ - 'Invalid option bom:', 'bom must be true,', - `got ${JSON.stringify(options.bom)}` - ], options) - } - // Normalize option `cast` - let fnCastField = null - if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ - options.cast = undefined - }else if(typeof options.cast === 'function'){ - fnCastField = options.cast - options.cast = true - }else if(options.cast !== true){ - throw new CsvError('CSV_INVALID_OPTION_CAST', [ - 'Invalid option cast:', 'cast must be true or a function,', - `got ${JSON.stringify(options.cast)}` - ], options) - } - // Normalize option `cast_date` - if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ - options.cast_date = false - }else if(options.cast_date === true){ - options.cast_date = function(value){ - const date = Date.parse(value) - return !isNaN(date) ? new Date(date) : value - } - }else if(typeof options.cast_date !== 'function'){ - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ - 'Invalid option cast_date:', 'cast_date must be true or a function,', - `got ${JSON.stringify(options.cast_date)}` - ], options) - } - // Normalize option `columns` - let fnFirstLineToHeaders = null - if(options.columns === true){ - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined - }else if(typeof options.columns === 'function'){ - fnFirstLineToHeaders = options.columns - options.columns = true - }else if(Array.isArray(options.columns)){ - options.columns = normalizeColumnsArray(options.columns) - }else if(options.columns === undefined || options.columns === null || options.columns === false){ - options.columns = false - }else{ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ - 'Invalid option columns:', - 'expect an array, a function or true,', - `got ${JSON.stringify(options.columns)}` - ], options) - } - // Normalize option `columns_duplicates_to_array` - if(options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false){ - options.columns_duplicates_to_array = false - }else if(options.columns_duplicates_to_array !== true){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'expect an boolean,', - `got ${JSON.stringify(options.columns_duplicates_to_array)}` - ], options) - }else if(options.columns === false){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'the `columns` mode must be activated.' - ], options) - } - // Normalize option `comment` - if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ - options.comment = null - }else{ - if(typeof options.comment === 'string'){ - options.comment = Buffer.from(options.comment, options.encoding) - } - if(!Buffer.isBuffer(options.comment)){ - throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ - 'Invalid option comment:', - 'comment must be a buffer or a string,', - `got ${JSON.stringify(options.comment)}` - ], options) - } - } - // Normalize option `delimiter` - const delimiter_json = JSON.stringify(options.delimiter) - if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter] - if(options.delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - options.delimiter = options.delimiter.map(function(delimiter){ - if(delimiter === undefined || delimiter === null || delimiter === false){ - return Buffer.from(',', options.encoding) - } - if(typeof delimiter === 'string'){ - delimiter = Buffer.from(delimiter, options.encoding) - } - if( !Buffer.isBuffer(delimiter) || delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - return delimiter - }) - // Normalize option `escape` - if(options.escape === undefined || options.escape === true){ - options.escape = Buffer.from('"', options.encoding) - }else if(typeof options.escape === 'string'){ - options.escape = Buffer.from(options.escape, options.encoding) - }else if (options.escape === null || options.escape === false){ - options.escape = null - } - if(options.escape !== null){ - if(!Buffer.isBuffer(options.escape)){ - throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`) - } - } - // Normalize option `from` - if(options.from === undefined || options.from === null){ - options.from = 1 - }else{ - if(typeof options.from === 'string' && /\d+/.test(options.from)){ - options.from = parseInt(options.from) - } - if(Number.isInteger(options.from)){ - if(options.from < 0){ - throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`) - } - }else{ - throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`) - } - } - // Normalize option `from_line` - if(options.from_line === undefined || options.from_line === null){ - options.from_line = 1 - }else{ - if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ - options.from_line = parseInt(options.from_line) - } - if(Number.isInteger(options.from_line)){ - if(options.from_line <= 0){ - throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`) - } - }else{ - throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`) - } - } - // Normalize options `ignore_last_delimiters` - if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ - options.ignore_last_delimiters = false - }else if(typeof options.ignore_last_delimiters === 'number'){ - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters) - if(options.ignore_last_delimiters === 0){ - options.ignore_last_delimiters = false - } - }else if(typeof options.ignore_last_delimiters !== 'boolean'){ - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ - 'Invalid option `ignore_last_delimiters`:', - 'the value must be a boolean value or an integer,', - `got ${JSON.stringify(options.ignore_last_delimiters)}` - ], options) - } - if(options.ignore_last_delimiters === true && options.columns === false){ - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ - 'The option `ignore_last_delimiters`', - 'requires the activation of the `columns` option' - ], options) - } - // Normalize option `info` - if(options.info === undefined || options.info === null || options.info === false){ - options.info = false - }else if(options.info !== true){ - throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`) - } - // Normalize option `max_record_size` - if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ - options.max_record_size = 0 - }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0){ - // Great, nothing to do - }else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ - options.max_record_size = parseInt(options.max_record_size) - }else{ - throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`) - } - // Normalize option `objname` - if(options.objname === undefined || options.objname === null || options.objname === false){ - options.objname = undefined - }else if(Buffer.isBuffer(options.objname)){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty buffer`) - } - if(options.encoding === null){ - // Don't call `toString`, leave objname as a buffer - }else{ - options.objname = options.objname.toString(options.encoding) - } - }else if(typeof options.objname === 'string'){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty string`) - } - // Great, nothing to do - }else{ - throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`) - } - // Normalize option `on_record` - if(options.on_record === undefined || options.on_record === null){ - options.on_record = undefined - }else if(typeof options.on_record !== 'function'){ - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ - 'Invalid option `on_record`:', - 'expect a function,', - `got ${JSON.stringify(options.on_record)}` - ], options) - } - // Normalize option `quote` - if(options.quote === null || options.quote === false || options.quote === ''){ - options.quote = null - }else{ - if(options.quote === undefined || options.quote === true){ - options.quote = Buffer.from('"', options.encoding) - }else if(typeof options.quote === 'string'){ - options.quote = Buffer.from(options.quote, options.encoding) - } - if(!Buffer.isBuffer(options.quote)){ - throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`) - } - } - // Normalize option `raw` - if(options.raw === undefined || options.raw === null || options.raw === false){ - options.raw = false - }else if(options.raw !== true){ - throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`) - } - // Normalize option `record_delimiter` - if(!options.record_delimiter){ - options.record_delimiter = [] - }else if(!Array.isArray(options.record_delimiter)){ - options.record_delimiter = [options.record_delimiter] - } - options.record_delimiter = options.record_delimiter.map( function(rd){ - if(typeof rd === 'string'){ - rd = Buffer.from(rd, options.encoding) - } - return rd - }) - // Normalize option `relax` - if(typeof options.relax === 'boolean'){ - // Great, nothing to do - }else if(options.relax === undefined || options.relax === null){ - options.relax = false - }else{ - throw new Error(`Invalid Option: relax must be a boolean, got ${JSON.stringify(options.relax)}`) - } - // Normalize option `relax_column_count` - if(typeof options.relax_column_count === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count === undefined || options.relax_column_count === null){ - options.relax_column_count = false - }else{ - throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`) - } - if(typeof options.relax_column_count_less === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ - options.relax_column_count_less = false - }else{ - throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`) - } - if(typeof options.relax_column_count_more === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ - options.relax_column_count_more = false - }else{ - throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`) - } - // Normalize option `skip_empty_lines` - if(typeof options.skip_empty_lines === 'boolean'){ - // Great, nothing to do - }else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ - options.skip_empty_lines = false - }else{ - throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`) - } - // Normalize option `skip_lines_with_empty_values` - if(typeof options.skip_lines_with_empty_values === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null){ - options.skip_lines_with_empty_values = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_lines_with_empty_values)}`) - } - // Normalize option `skip_lines_with_error` - if(typeof options.skip_lines_with_error === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_error === undefined || options.skip_lines_with_error === null){ - options.skip_lines_with_error = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_error must be a boolean, got ${JSON.stringify(options.skip_lines_with_error)}`) - } - // Normalize option `rtrim` - if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ - options.rtrim = false - }else if(options.rtrim !== true){ - throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`) - } - // Normalize option `ltrim` - if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ - options.ltrim = false - }else if(options.ltrim !== true){ - throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`) - } - // Normalize option `trim` - if(options.trim === undefined || options.trim === null || options.trim === false){ - options.trim = false - }else if(options.trim !== true){ - throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`) - } - // Normalize options `trim`, `ltrim` and `rtrim` - if(options.trim === true && opts.ltrim !== false){ - options.ltrim = true - }else if(options.ltrim !== true){ - options.ltrim = false - } - if(options.trim === true && opts.rtrim !== false){ - options.rtrim = true - }else if(options.rtrim !== true){ - options.rtrim = false - } - // Normalize option `to` - if(options.to === undefined || options.to === null){ - options.to = -1 - }else{ - if(typeof options.to === 'string' && /\d+/.test(options.to)){ - options.to = parseInt(options.to) - } - if(Number.isInteger(options.to)){ - if(options.to <= 0){ - throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`) - } - }else{ - throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`) - } - } - // Normalize option `to_line` - if(options.to_line === undefined || options.to_line === null){ - options.to_line = -1 - }else{ - if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ - options.to_line = parseInt(options.to_line) - } - if(Number.isInteger(options.to_line)){ - if(options.to_line <= 0){ - throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`) - } - }else{ - throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`) - } - } - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - } - this.options = options - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max( - // Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0, - // Skip if the remaining buffer can be delimiter - ...options.delimiter.map( (delimiter) => delimiter.length), - // Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0, - ), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max(...options.record_delimiter.map( (v) => v.length)), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - } - } - // Implementation of `Transform._transform` - _transform(buf, encoding, callback){ - if(this.state.stop === true){ - return - } - const err = this.__parse(buf, false) - if(err !== undefined){ - this.state.stop = true - } - callback(err) - } - // Implementation of `Transform._flush` - _flush(callback){ - if(this.state.stop === true){ - return - } - const err = this.__parse(undefined, true) - callback(err) - } - // Central parser implementation - __parse(nextBuf, end){ - const {bom, comment, escape, from_line, ltrim, max_record_size, quote, raw, relax, rtrim, skip_empty_lines, to, to_line} = this.options - let {record_delimiter} = this.options - const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state - let buf - if(previousBuf === undefined){ - if(nextBuf === undefined){ - // Handle empty string - this.push(null) - return - }else{ - buf = nextBuf - } - }else if(previousBuf !== undefined && nextBuf === undefined){ - buf = previousBuf - }else{ - buf = Buffer.concat([previousBuf, nextBuf]) - } - // Handle UTF BOM - if(bomSkipped === false){ - if(bom === false){ - this.state.bomSkipped = true - }else if(buf.length < 3){ - // No enough data - if(end === false){ - // Wait for more data - this.state.previousBuf = buf - return - } - }else{ - for(let encoding in boms){ - if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ - // Skip BOM - let bomLength = boms[encoding].length - this.state.bufBytesStart += bomLength - buf = buf.slice(bomLength) - // Renormalize original options with the new encoding - this.__normalizeOptions({...this.__originalOptions, encoding: encoding}) - break - } - } - this.state.bomSkipped = true - } - } - const bufLen = buf.length - let pos - for(pos = 0; pos < bufLen; pos++){ - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if(this.__needMoreData(pos, bufLen, end)){ - break - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - if(to_line !== -1 && this.info.lines > to_line){ - this.state.stop = true - this.push(null) - return - } - // Auto discovery of record_delimiter, unix, mac and windows supported - if(this.state.quoting === false && record_delimiter.length === 0){ - const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos) - if(record_delimiterCount){ - record_delimiter = this.options.record_delimiter - } - } - const chr = buf[pos] - if(raw === true){ - rawBuffer.append(chr) - } - if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false ){ - this.state.wasRowDelimiter = true - } - // Previous char was a valid escape char - // treat the current char as a regular char - if(this.state.escaping === true){ - this.state.escaping = false - }else{ - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ - if(escapeIsQuote){ - if(this.__isQuote(buf, pos+escape.length)){ - this.state.escaping = true - pos += escape.length - 1 - continue - } - }else{ - this.state.escaping = true - pos += escape.length - 1 - continue - } - } - // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - if(this.state.commenting === false && this.__isQuote(buf, pos)){ - if(this.state.quoting === true){ - const nextChr = buf[pos+quote.length] - const isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr) - const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr) - const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr) - const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length) - // Escape a quote - // Treat next char as a regular character - if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ - pos += escape.length - 1 - }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ - this.state.quoting = false - this.state.wasQuoting = true - pos += quote.length - 1 - continue - }else if(relax === false){ - const err = this.__error( - new CsvError('CSV_INVALID_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - `got "${String.fromCharCode(nextChr)}"`, - `at line ${this.info.lines}`, - 'instead of delimiter, record delimiter, trimable character', - '(if activated) or comment', - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - this.state.quoting = false - this.state.wasQuoting = true - this.state.field.prepend(quote) - pos += quote.length - 1 - } - }else{ - if(this.state.field.length !== 0){ - // In relax mode, treat opening quote preceded by chrs as regular - if( relax === false ){ - const err = this.__error( - new CsvError('INVALID_OPENING_QUOTE', [ - 'Invalid Opening Quote:', - `a quote is found inside a field at line ${this.info.lines}`, - ], this.options, this.__infoField(), { - field: this.state.field, - }) - ) - if(err !== undefined) return err - } - }else{ - this.state.quoting = true - pos += quote.length - 1 - continue - } - } - } - if(this.state.quoting === false){ - let recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos) - if(recordDelimiterLength !== 0){ - // Do not emit comments which take a full line - const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) - if(skipCommentLine){ - this.info.comment_lines++ - // Skip full comment line - }else{ - // Activate records emition if above from_line - if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ - this.state.enabled = true - this.__resetField() - this.__resetRecord() - pos += recordDelimiterLength - 1 - continue - } - // Skip if line is empty and skip_empty_lines activated - if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ - this.info.empty_lines++ - pos += recordDelimiterLength - 1 - continue - } - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - if(to !== -1 && this.info.records >= to){ - this.state.stop = true - this.push(null) - return - } - } - this.state.commenting = false - pos += recordDelimiterLength - 1 - continue - } - if(this.state.commenting){ - continue - } - const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr) - if(commentCount !== 0){ - this.state.commenting = true - continue - } - let delimiterLength = this.__isDelimiter(buf, pos, chr) - if(delimiterLength !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - pos += delimiterLength - 1 - continue - } - } - } - if(this.state.commenting === false){ - if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ - const err = this.__error( - new CsvError('CSV_MAX_RECORD_SIZE', [ - 'Max Record Size:', - 'record exceed the maximum number of tolerated bytes', - `of ${max_record_size}`, - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr) - // rtrim in non quoting is handle in __onField - const rappend = rtrim === false || this.state.wasQuoting === false - if( lappend === true && rappend === true ){ - this.state.field.append(chr) - }else if(rtrim === true && !this.__isCharTrimable(chr)){ - const err = this.__error( - new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - 'found non trimable byte after quote', - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - if(end === true){ - // Ensure we are not ending in a quoting state - if(this.state.quoting === true){ - const err = this.__error( - new CsvError('CSV_QUOTE_NOT_CLOSED', [ - 'Quote Not Closed:', - `the parsing is finished with an opening quote at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - // Skip last line if it has no characters - if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - }else if(this.state.wasRowDelimiter === true){ - this.info.empty_lines++ - }else if(this.state.commenting === true){ - this.info.comment_lines++ - } - } - }else{ - this.state.bufBytesStart += pos - this.state.previousBuf = buf.slice(pos) - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - } - __onRecord(){ - const {columns, columns_duplicates_to_array, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_lines_with_empty_values} = this.options - const {enabled, record} = this.state - if(enabled === false){ - return this.__resetRecord() - } - // Convert the first line into column names - const recordLength = record.length - if(columns === true){ - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - return this.__firstLineToColumns(record) - } - if(columns === false && this.info.records === 0){ - this.state.expectedRecordLength = recordLength - } - if(recordLength !== this.state.expectedRecordLength){ - const err = columns === false ? - // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', [ - 'Invalid Record Length:', - `expect ${this.state.expectedRecordLength},`, - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - : - // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', [ - 'Invalid Record Length:', - `columns length is ${columns.length},`, // rename columns - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - if(relax_column_count === true || - (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || - (relax_column_count_more === true && recordLength > this.state.expectedRecordLength) ){ - this.info.invalid_field_length++ - this.state.error = err - // Error is undefined with skip_lines_with_error - }else{ - const finalErr = this.__error(err) - if(finalErr) return finalErr - } - } - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - if(this.state.recordHasError === true){ - this.__resetRecord() - this.state.recordHasError = false - return - } - this.info.records++ - if(from === 1 || this.info.records >= from){ - // With columns, records are object - if(columns !== false){ - const obj = {} - // Transform record array to an object - for(let i = 0, l = record.length; i < l; i++){ - if(columns[i] === undefined || columns[i].disabled) continue - // Turn duplicate columns into an array - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]) - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]] - } - } else { - obj[columns[i].name] = record[i] - } - } - const {objname} = this.options - // Without objname (default) - if(objname === undefined){ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: obj}, - (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), - (info === true ? {info: this.__infoRecord()}: {}) - )) - if(err){ - return err - } - }else{ - const err = this.__push(obj) - if(err){ - return err - } - } - // With objname (default) - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: [obj[objname], obj]}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push([obj[objname], obj]) - if(err){ - return err - } - } - } - // Without columns, records are array - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: record}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push(record) - if(err){ - return err - } - } - } - } - this.__resetRecord() - } - __firstLineToColumns(record){ - const {firstLineToHeaders} = this.state - try{ - const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record) - if(!Array.isArray(headers)){ - return this.__error( - new CsvError('CSV_INVALID_COLUMN_MAPPING', [ - 'Invalid Column Mapping:', - 'expect an array from column function,', - `got ${JSON.stringify(headers)}` - ], this.options, this.__infoField(), { - headers: headers, - }) - ) - } - const normalizedHeaders = normalizeColumnsArray(headers) - this.state.expectedRecordLength = normalizedHeaders.length - this.options.columns = normalizedHeaders - this.__resetRecord() - return - }catch(err){ - return err - } - } - __resetRecord(){ - if(this.options.raw === true){ - this.state.rawBuffer.reset() - } - this.state.error = undefined - this.state.record = [] - this.state.record_length = 0 - } - __onField(){ - const {cast, encoding, rtrim, max_record_size} = this.options - const {enabled, wasQuoting} = this.state - // Short circuit for the from_line options - if(enabled === false){ - return this.__resetField() - } - let field = this.state.field.toString(encoding) - if(rtrim === true && wasQuoting === false){ - field = field.trimRight() - } - if(cast === true){ - const [err, f] = this.__cast(field) - if(err !== undefined) return err - field = f - } - this.state.record.push(field) - // Increment record length if record size must not exceed a limit - if(max_record_size !== 0 && typeof field === 'string'){ - this.state.record_length += field.length - } - this.__resetField() - } - __resetField(){ - this.state.field.reset() - this.state.wasQuoting = false - } - __push(record){ - const {on_record} = this.options - if(on_record !== undefined){ - const info = this.__infoRecord() - try{ - record = on_record.call(null, record, info) - }catch(err){ - return err - } - if(record === undefined || record === null){ return } - } - this.push(record) - } - // Return a tuple with the error and the casted value - __cast(field){ - const {columns, relax_column_count} = this.options - const isColumns = Array.isArray(columns) - // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - if( isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length ){ - return [undefined, undefined] - } - if(this.state.castField !== null){ - try{ - const info = this.__infoField() - return [undefined, this.state.castField.call(null, field, info)] - }catch(err){ - return [err] - } - } - if(this.__isFloat(field)){ - return [undefined, parseFloat(field)] - }else if(this.options.cast_date !== false){ - const info = this.__infoField() - return [undefined, this.options.cast_date.call(null, field, info)] - } - return [undefined, field] - } - // Helper to test if a character is a space or a line delimiter - __isCharTrimable(chr){ - return chr === space || chr === tab || chr === cr || chr === nl || chr === np - } - // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - __isFloat(value){ - return (value - parseFloat( value ) + 1) >= 0 // Borrowed from jquery - } - __compareBytes(sourceBuf, targetBuf, targetPos, firstByte){ - if(sourceBuf[0] !== firstByte) return 0 - const sourceLength = sourceBuf.length - for(let i = 1; i < sourceLength; i++){ - if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0 - } - return sourceLength - } - __needMoreData(i, bufLen, end){ - if(end) return false - const {quote} = this.options - const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state - const numOfCharLeft = bufLen - i - 1 - const requiredLength = Math.max( - needMoreDataSize, - // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, - // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? (quote.length + recordDelimiterMaxLength) : 0, - ) - return numOfCharLeft < requiredLength - } - __isDelimiter(buf, pos, chr){ - const {delimiter, ignore_last_delimiters} = this.options - if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ - return 0 - }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ - return 0 - } - loop1: for(let i = 0; i < delimiter.length; i++){ - const del = delimiter[i] - if(del[0] === chr){ - for(let j = 1; j < del.length; j++){ - if(del[j] !== buf[pos+j]) continue loop1 - } - return del.length - } - } - return 0 - } - __isRecordDelimiter(chr, buf, pos){ - const {record_delimiter} = this.options - const recordDelimiterLength = record_delimiter.length - loop1: for(let i = 0; i < recordDelimiterLength; i++){ - const rd = record_delimiter[i] - const rdLength = rd.length - if(rd[0] !== chr){ - continue - } - for(let j = 1; j < rdLength; j++){ - if(rd[j] !== buf[pos+j]){ - continue loop1 - } - } - return rd.length - } - return 0 - } - __isEscape(buf, pos, chr){ - const {escape} = this.options - if(escape === null) return false - const l = escape.length - if(escape[0] === chr){ - for(let i = 0; i < l; i++){ - if(escape[i] !== buf[pos+i]){ - return false - } - } - return true - } - return false - } - __isQuote(buf, pos){ - const {quote} = this.options - if(quote === null) return false - const l = quote.length - for(let i = 0; i < l; i++){ - if(quote[i] !== buf[pos+i]){ - return false - } - } - return true - } - __autoDiscoverRecordDelimiter(buf, pos){ - const {encoding} = this.options - const chr = buf[pos] - if(chr === cr){ - if(buf[pos+1] === nl){ - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)) - this.state.recordDelimiterMaxLength = 2 - return 2 - }else{ - this.options.record_delimiter.push(Buffer.from('\r', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - }else if(chr === nl){ - this.options.record_delimiter.push(Buffer.from('\n', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - return 0 - } - __error(msg){ - const {skip_lines_with_error} = this.options - const err = typeof msg === 'string' ? new Error(msg) : msg - if(skip_lines_with_error){ - this.state.recordHasError = true - this.emit('skip', err) - return undefined - }else{ - return err - } - } - __infoDataSet(){ - return { - ...this.info, - columns: this.options.columns - } - } - __infoRecord(){ - const {columns} = this.options - return { - ...this.__infoDataSet(), - error: this.state.error, - header: columns === true, - index: this.state.record.length, - } - } - __infoField(){ - const {columns} = this.options - const isColumns = Array.isArray(columns) - return { - ...this.__infoRecord(), - column: isColumns === true ? - ( columns.length > this.state.record.length ? - columns[this.state.record.length].name : - null - ) : - this.state.record.length, - quoting: this.state.wasQuoting, - } - } -} - -const parse = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument - if(data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument - }else if(callback === undefined && type === 'function'){ - callback = argument - }else{ - throw new CsvError('CSV_INVALID_ARGUMENT', [ - 'Invalid argument:', - `got ${JSON.stringify(argument)} at index ${i}` - ], options || {}) - } - } - const parser = new Parser(options) - if(callback){ - const records = options === undefined || options.objname === undefined ? [] : {} - parser.on('readable', function(){ - let record - while((record = this.read()) !== null){ - if(options === undefined || options.objname === undefined){ - records.push(record) - }else{ - records[record[0]] = record[1] - } - } - }) - parser.on('error', function(err){ - callback(err, undefined, parser.__infoDataSet()) - }) - parser.on('end', function(){ - callback(undefined, records, parser.__infoDataSet()) - }) - } - if(data !== undefined){ - // Give a chance for events to be registered later - if(typeof setImmediate === 'function'){ - setImmediate(function(){ - parser.write(data) - parser.end() - }) - }else{ - parser.write(data) - parser.end() - } - } - return parser -} - -class CsvError extends Error { - constructor(code, message, options, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)) - } - } - } -} - -parse.Parser = Parser - -parse.CsvError = CsvError - -module.exports = parse - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -const isObject = function(obj){ - return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) -} - -const isRecordEmpty = function(record){ - return record.every( (field) => field == null || field.toString && field.toString().trim() === '' ) -} - -const normalizeColumnsArray = function(columns){ - const normalizedColumns = []; - for(let i = 0, l = columns.length; i < l; i++){ - const column = columns[i] - if(column === undefined || column === null || column === false){ - normalizedColumns[i] = { disabled: true } - }else if(typeof column === 'string'){ - normalizedColumns[i] = { name: column } - }else if(isObject(column)){ - if(typeof column.name !== 'string'){ - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ - 'Option columns missing name:', - `property "name" is required at position ${i}`, - 'when column is an object literal' - ]) - } - normalizedColumns[i] = column - }else{ - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ - 'Invalid column definition:', - 'expect a string or a literal object,', - `got ${JSON.stringify(column)} at position ${i}` - ]) - } - } - return normalizedColumns; -} - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"./ResizeableBuffer":3,"buffer":10,"stream":29,"timers":45}],5:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ - -/* -CSV Stringify - -Please look at the [project documentation](https://csv.js.org/stringify/) for -additional information. -*/ - -const { Transform } = require('stream') -const bom_utf8 = Buffer.from([239, 187, 191]) - -class Stringifier extends Transform { - constructor(opts = {}){ - super({...{writableObjectMode: true}, ...opts}) - const options = {} - let err - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - if(err = this.normalize(options)) throw err - switch(options.record_delimiter){ - case 'auto': - options.record_delimiter = null - break - case 'unix': - options.record_delimiter = "\n" - break - case 'mac': - options.record_delimiter = "\r" - break - case 'windows': - options.record_delimiter = "\r\n" - break - case 'ascii': - options.record_delimiter = "\u001e" - break - case 'unicode': - options.record_delimiter = "\u2028" - break - } - // Expose options - this.options = options - // Internal state - this.state = { - stop: false - } - // Information - this.info = { - records: 0 - } - } - normalize(options){ - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ - 'option `bom` is optional and must be a boolean value,', - `got ${JSON.stringify(options.bom)}` - ]) - } - // Normalize option `delimiter` - if(options.delimiter === undefined || options.delimiter === null){ - options.delimiter = ',' - }else if(Buffer.isBuffer(options.delimiter)){ - options.delimiter = options.delimiter.toString() - }else if(typeof options.delimiter !== 'string'){ - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ - 'option `delimiter` must be a buffer or a string,', - `got ${JSON.stringify(options.delimiter)}` - ]) - } - // Normalize option `quote` - if(options.quote === undefined || options.quote === null){ - options.quote = '"' - }else if(options.quote === true){ - options.quote = '"' - }else if(options.quote === false){ - options.quote = '' - }else if (Buffer.isBuffer(options.quote)){ - options.quote = options.quote.toString() - }else if(typeof options.quote !== 'string'){ - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ - 'option `quote` must be a boolean, a buffer or a string,', - `got ${JSON.stringify(options.quote)}` - ]) - } - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `quoted_empty` - if(options.quoted_empty === undefined || options.quoted_empty === null){ - options.quoted_empty = undefined - }else{ - // todo - } - // Normalize option `quoted_match` - if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ - options.quoted_match = null - }else if(!Array.isArray(options.quoted_match)){ - options.quoted_match = [options.quoted_match] - } - if(options.quoted_match){ - for(let quoted_match of options.quoted_match){ - const isString = typeof quoted_match === 'string' - const isRegExp = quoted_match instanceof RegExp - if(!isString && !isRegExp){ - return Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`) - } - } - } - // Normalize option `quoted_string` - if(options.quoted_string === undefined || options.quoted_string === null){ - options.quoted_string = false - }else{ - // todo - } - // Normalize option `eof` - if(options.eof === undefined || options.eof === null){ - options.eof = true - }else{ - // todo - } - // Normalize option `escape` - if(options.escape === undefined || options.escape === null){ - options.escape = '"' - }else if(Buffer.isBuffer(options.escape)){ - options.escape = options.escape.toString() - }else if(typeof options.escape !== 'string'){ - return Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`) - } - if (options.escape.length > 1){ - return Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`) - } - // Normalize option `header` - if(options.header === undefined || options.header === null){ - options.header = false - }else{ - // todo - } - // Normalize option `columns` - options.columns = this.normalize_columns(options.columns) - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `cast` - if(options.cast === undefined || options.cast === null){ - options.cast = {} - }else{ - // todo - } - // Normalize option cast.bigint - if(options.cast.bigint === undefined || options.cast.bigint === null){ - // Cast boolean to string by default - options.cast.bigint = value => '' + value - } - // Normalize option cast.boolean - if(options.cast.boolean === undefined || options.cast.boolean === null){ - // Cast boolean to string by default - options.cast.boolean = value => value ? '1' : '' - } - // Normalize option cast.date - if(options.cast.date === undefined || options.cast.date === null){ - // Cast date to timestamp string by default - options.cast.date = value => '' + value.getTime() - } - // Normalize option cast.number - if(options.cast.number === undefined || options.cast.number === null){ - // Cast number to string using native casting by default - options.cast.number = value => '' + value - } - // Normalize option cast.object - if(options.cast.object === undefined || options.cast.object === null){ - // Stringify object as JSON by default - options.cast.object = value => JSON.stringify(value) - } - // Normalize option cast.string - if(options.cast.string === undefined || options.cast.string === null){ - // Leave string untouched - options.cast.string = function(value){return value} - } - // Normalize option `record_delimiter` - if(options.record_delimiter === undefined || options.record_delimiter === null){ - options.record_delimiter = '\n' - }else if(Buffer.isBuffer(options.record_delimiter)){ - options.record_delimiter = options.record_delimiter.toString() - }else if(typeof options.record_delimiter !== 'string'){ - return Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`) - } - } - _transform(chunk, encoding, callback){ - if(this.state.stop === true){ - return - } - // Chunk validation - if(!Array.isArray(chunk) && typeof chunk !== 'object'){ - this.state.stop = true - return callback(Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`)) - } - // Detect columns from the first record - if(this.info.records === 0){ - if(Array.isArray(chunk)){ - if(this.options.header === true && !this.options.columns){ - this.state.stop = true - return callback(Error('Undiscoverable Columns: header option requires column option or object records')) - } - }else if(this.options.columns === undefined || this.options.columns === null){ - this.options.columns = this.normalize_columns(Object.keys(chunk)) - } - } - // Emit the header - if(this.info.records === 0){ - this.bom() - this.headers() - } - // Emit and stringify the record if an object or an array - try{ - this.emit('record', chunk, this.info.records) - }catch(err){ - this.state.stop = true - return this.emit('error', err) - } - // Convert the record into a string - let chunk_string - if(this.options.eof){ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - chunk_string = chunk_string + this.options.record_delimiter - } - }else{ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - if(this.options.header || this.info.records){ - chunk_string = this.options.record_delimiter + chunk_string - } - } - } - // Emit the csv - this.info.records++ - this.push(chunk_string) - callback() - } - _flush(callback){ - if(this.info.records === 0){ - this.bom() - this.headers() - } - callback() - } - stringify(chunk, chunkIsHeader=false){ - if(typeof chunk !== 'object'){ - return chunk - } - const {columns, header} = this.options - const record = [] - // Record is an array - if(Array.isArray(chunk)){ - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if(columns){ - chunk.splice(columns.length) - } - // Cast record elements - for(let i=0; i= 0 - const containsQuote = (quote !== '') && value.indexOf(quote) >= 0 - const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote) - const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0 - const quotedString = quoted_string && typeof field === 'string' - let quotedMatch = quoted_match && quoted_match.filter( quoted_match => { - if(typeof quoted_match === 'string'){ - return value.indexOf(quoted_match) !== -1 - }else{ - return quoted_match.test(value) - } - }) - quotedMatch = quotedMatch && quotedMatch.length > 0 - const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch - if(shouldQuote === true && containsEscape === true){ - const regexp = escape === '\\' - ? new RegExp(escape + escape, 'g') - : new RegExp(escape, 'g') - value = value.replace(regexp, escape + escape) - } - if(containsQuote === true){ - const regexp = new RegExp(quote,'g') - value = value.replace(regexp, escape + quote) - } - if(shouldQuote === true){ - value = quote + value + quote - } - csvrecord += value - }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ - csvrecord += quote + quote - } - if(i !== record.length - 1){ - csvrecord += delimiter - } - } - return csvrecord - } - bom(){ - if(this.options.bom !== true){ - return - } - this.push(bom_utf8) - } - headers(){ - if(this.options.header === false){ - return - } - if(this.options.columns === undefined){ - return - } - let headers = this.options.columns.map(column => column.header) - if(this.options.eof){ - headers = this.stringify(headers, true) + this.options.record_delimiter - }else{ - headers = this.stringify(headers) - } - this.push(headers) - } - __cast(value, context){ - const type = typeof value - try{ - if(type === 'string'){ // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)] - }else if(type === 'bigint'){ - return [undefined, this.options.cast.bigint(value, context)] - }else if(type === 'number'){ - return [undefined, this.options.cast.number(value, context)] - }else if(type === 'boolean'){ - return [undefined, this.options.cast.boolean(value, context)] - }else if(value instanceof Date){ - return [undefined, this.options.cast.date(value, context)] - }else if(type === 'object' && value !== null){ - return [undefined, this.options.cast.object(value, context)] - }else{ - return [undefined, value, value] - } - }catch(err){ - return [err] - } - } - normalize_columns(columns){ - if(columns === undefined || columns === null){ - return undefined - } - if(typeof columns !== 'object'){ - throw Error('Invalid option "columns": expect an array or an object') - } - if(!Array.isArray(columns)){ - const newcolumns = [] - for(let k in columns){ - newcolumns.push({ - key: k, - header: columns[k] - }) - } - columns = newcolumns - }else{ - const newcolumns = [] - for(let column of columns){ - if(typeof column === 'string'){ - newcolumns.push({ - key: column, - header: column - }) - }else if(typeof column === 'object' && column !== undefined && !Array.isArray(column)){ - if(!column.key){ - throw Error('Invalid column definition: property "key" is required') - } - if(column.header === undefined){ - column.header = column.key - } - newcolumns.push(column) - }else{ - throw Error('Invalid column definition: expect a string or an object') - } - } - columns = newcolumns - } - return columns - } -} - -const stringify = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument - if(data === undefined && (Array.isArray(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument - }else if(callback === undefined && type === 'function'){ - callback = argument - }else{ - throw new CsvError('CSV_INVALID_ARGUMENT', [ - 'Invalid argument:', - `got ${JSON.stringify(argument)} at index ${i}` - ]) - } - } - const stringifier = new Stringifier(options) - if(callback){ - const chunks = [] - stringifier.on('readable', function(){ - let chunk - while((chunk = this.read()) !== null){ - chunks.push(chunk) - } - }) - stringifier.on('error', function(err){ - callback(err) - }) - stringifier.on('end', function(){ - callback(undefined, chunks.join('')) - }) - } - if(data !== undefined){ - // Give a chance for events to be registered later - if(typeof setImmediate === 'function'){ - setImmediate(function(){ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - }) - }else{ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - } - } - return stringifier -} - -class CsvError extends Error { - constructor(code, message, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)) - } - } - } -} - -stringify.Stringifier = Stringifier - -stringify.CsvError = CsvError - -module.exports = stringify - -const isObject = function(obj){ - return typeof obj === 'object' && obj !== null && ! Array.isArray(obj) -} - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -// Lodash implementation of `get` - -const charCodeOfDot = '.'.charCodeAt(0) -const reEscapeChar = /\\(\\)?/g -const rePropName = RegExp( - // Match anything that isn't a dot or bracket. - '[^.[\\]]+' + '|' + - // Or match property names within brackets. - '\\[(?:' + - // Match a non-string expression. - '([^"\'][^[]*)' + '|' + - // Or match strings (supports escaping characters). - '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + - ')\\]'+ '|' + - // Or match "" as the space between consecutive dots or empty brackets. - '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' -, 'g') -const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/ -const reIsPlainProp = /^\w*$/ -const getTag = function(value){ - if(!value) - value === undefined ? '[object Undefined]' : '[object Null]' - return Object.prototype.toString.call(value) -} -const isKey = function(value, object){ - if(Array.isArray(value)){ - return false - } - const type = typeof value - if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ - return true - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)) -} -const isSymbol = function(value){ - const type = typeof value - return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]') -} -const stringToPath = function(string){ - const result = [] - if(string.charCodeAt(0) === charCodeOfDot){ - result.push('') - } - string.replace(rePropName, function(match, expression, quote, subString){ - let key = match - if(quote){ - key = subString.replace(reEscapeChar, '$1') - }else if(expression){ - key = expression.trim() - } - result.push(key) - }) - return result -} -const castPath = function(value, object){ - if(Array.isArray(value)){ - return value - } else { - return isKey(value, object) ? [value] : stringToPath(value) - } -} -const toKey = function(value){ - if(typeof value === 'string' || isSymbol(value)) - return value - const result = `${value}` - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result -} -const get = function(object, path){ - path = castPath(path, object) - let index = 0 - const length = path.length - while(object != null && index < length){ - object = object[toKey(path[index++])] - } - return (index && index === length) ? object : undefined -} - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"buffer":10,"stream":29,"timers":45}],6:[function(require,module,exports){ -// Alias to the ES6 modules exposing the stream and callback APIs -module.exports = { - generate: require('csv-generate/lib'), - parse: require('csv-parse/lib'), - transform: require('stream-transform/lib'), - stringify: require('csv-stringify/lib') -}; - -},{"csv-generate/lib":2,"csv-parse/lib":4,"csv-stringify/lib":5,"stream-transform/lib":51}],7:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],8:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],9:[function(require,module,exports){ - -},{}],10:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":8,"buffer":10,"ieee754":22}],11:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":12,"get-intrinsic":18}],12:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":17,"get-intrinsic":18}],13:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":18}],14:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],15:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],16:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],17:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":16}],18:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":17,"has":21,"has-symbols":19}],19:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":20}],20:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],21:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":17}],22:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],23:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],24:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":11}],25:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],26:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":7,"call-bind/callBound":11,"es-abstract/helpers/getOwnPropertyDescriptor":13,"foreach":15,"has-symbols":19}],27:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],28:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":10}],29:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":14,"inherits":23,"readable-stream/lib/_stream_duplex.js":31,"readable-stream/lib/_stream_passthrough.js":32,"readable-stream/lib/_stream_readable.js":33,"readable-stream/lib/_stream_transform.js":34,"readable-stream/lib/_stream_writable.js":35,"readable-stream/lib/internal/streams/end-of-stream.js":39,"readable-stream/lib/internal/streams/pipeline.js":41}],30:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],31:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":33,"./_stream_writable":35,"_process":27,"inherits":23}],32:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":34,"inherits":23}],33:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":30,"./_stream_duplex":31,"./internal/streams/async_iterator":36,"./internal/streams/buffer_list":37,"./internal/streams/destroy":38,"./internal/streams/from":40,"./internal/streams/state":42,"./internal/streams/stream":43,"_process":27,"buffer":10,"events":14,"inherits":23,"string_decoder/":44,"util":9}],34:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":30,"./_stream_duplex":31,"inherits":23}],35:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":30,"./_stream_duplex":31,"./internal/streams/destroy":38,"./internal/streams/state":42,"./internal/streams/stream":43,"_process":27,"buffer":10,"inherits":23,"util-deprecate":46}],36:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":39,"_process":27}],37:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":10,"util":9}],38:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":27}],39:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":30}],40:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],41:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":30,"./end-of-stream":39}],42:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":30}],43:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":14}],44:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":28}],45:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":27,"timers":45}],46:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],47:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],48:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":24,"is-generator-function":25,"is-typed-array":26,"which-typed-array":50}],49:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":47,"./support/types":48,"_process":27,"inherits":23}],50:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":7,"call-bind/callBound":11,"es-abstract/helpers/getOwnPropertyDescriptor":13,"foreach":15,"has-symbols":19,"is-typed-array":26}],51:[function(require,module,exports){ -(function (setImmediate){(function (){ -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer - -// Pass all elements of an array or a stream to transform, filter and add. Features include: - -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. - -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; - -stream = require('stream'); - -util = require('util'); - -({clone} = require('mixme')); - -// ## Usage - -// Callback approach, for ease of use: - -// `transform(records, [options], handler, callback)` - -// Stream API, for maximum of power: - -// `transform([records], [options], handler, [callback])` -module.exports = function() { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = typeof argument; - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); - } - } - transform = new Transformer(options, handler); - error = false; - if (records) { - setImmediate(function() { - var k, len1, record; - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - if (error) { - break; - } - transform.write(record); - } - return transform.end(); - }); - } - if (callback || options.consume) { - result = []; - transform.on('readable', function() { - var record, results; - results = []; - while ((record = transform.read())) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - return results; - }); - transform.on('error', function(err) { - error = true; - if (callback) { - return callback(err); - } - }); - transform.on('end', function() { - if (callback && !error) { - return callback(null, result); - } - }); - } - return transform; -}; - -// ## Transformer - -// Options are documented [here](http://csv.js.org/transform/options/). -Transformer = function(options1 = {}, handler1) { - var base, base1; - this.options = options1; - this.handler = handler1; - if ((base = this.options).consume == null) { - base.consume = false; - } - this.options.objectMode = true; - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; - } - stream.Transform.call(this, this.options); - this.state = { - running: 0, - started: 0, - finished: 0 - }; - return this; -}; - -util.inherits(Transformer, stream.Transform); - -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function(chunk, encoding, cb) { - var callback, err, l; - this.state.started++; - this.state.running++; - if (this.state.running < this.options.parallel) { - cb(); - cb = null; - } - try { - l = this.handler.length; - if (this.options.params != null) { - l--; - } - if (l === 1) { // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { // async - callback = (err, ...chunks) => { - return this.__done(err, chunks, cb); - }; - this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); - } - return false; - } catch (error1) { - err = error1; - return this.__done(err); - } -}; - -Transformer.prototype._flush = function(cb) { - this._ending = function() { - if (this.state.running === 0) { - this._ending = undefined - return cb(); - } - }; - return this._ending(); -}; - -Transformer.prototype.__done = function(err, chunks, cb) { - var chunk, j, len; - this.state.running--; - if (err) { - return this.emit('error', err); - } - this.state.finished++; - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - if (typeof chunk === 'number') { - chunk = `${chunk}`; - } - if ((chunk != null) && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); - } - } - if (cb) { - cb(); - } - if (this._ending) { - return this._ending(); - } -}; - -// [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test - -}).call(this)}).call(this,require("timers").setImmediate) -},{"mixme":1,"stream":29,"timers":45,"util":49}]},{},[6])(6) -}); diff --git a/node_modules/csv/lib/browser/sync.js b/node_modules/csv/lib/browser/sync.js deleted file mode 100644 index a7ab2e7..0000000 --- a/node_modules/csv/lib/browser/sync.js +++ /dev/null @@ -1,11131 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (name === '__proto__') { - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; -}; - -exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; - -},{}],2:[function(require,module,exports){ -(function (Buffer){(function (){ - -/* -CSV Generate - main module - -Please look at the [project documentation](https://csv.js.org/generate/) for -additional information. -*/ - -const stream = require('stream') -const util = require('util') - -module.exports = function(){ - let options - let callback - if(arguments.length === 2){ - options = arguments[0] - callback = arguments[1] - }else if(arguments.length === 1){ - if(typeof arguments[0] === 'function'){ - options = {} - callback = arguments[0] - }else{ - options = arguments[0] - } - }else if(arguments.length === 0){ - options = {} - } - const generator = new Generator(options) - if(callback){ - const data = [] - generator.on('readable', function(){ - let d; while(d = generator.read()){ - data.push(d) - } - }) - generator.on('error', callback) - generator.on('end', function(){ - if(generator.options.objectMode){ - callback(null, data) - }else{ - if(generator.options.encoding){ - callback(null, data.join('')) - }else{ - callback(null, Buffer.concat(data)) - } - } - }) - } - return generator -} - -Generator = function(options = {}){ - // Convert Stream Readable options if underscored - if(options.high_water_mark){ - options.highWaterMark = options.high_water_mark - } - if(options.object_mode){ - options.objectMode = options.object_mode - } - // Call parent constructor - stream.Readable.call(this, options) - // Clone and camelize options - this.options = {} - for(let k in options){ - this.options[Generator.camelize(k)] = options[k] - } - // Normalize options - const dft = { - columns: 8, - delimiter: ',', - duration: null, - encoding: null, - end: null, - eof: false, - fixedSize: false, - length: -1, - maxWordLength: 16, - rowDelimiter: '\n', - seed: false, - sleep: 0, - } - for(const k in dft){ - if(this.options[k] === undefined){ - this.options[k] = dft[k] - } - } - // Default values - if(this.options.eof === true){ - this.options.eof = this.options.rowDelimiter - } - // State - this._ = { - start_time: this.options.duration ? Date.now() : null, - fixed_size_buffer: '', - count_written: 0, - count_created: 0, - } - if(typeof this.options.columns === 'number'){ - this.options.columns = new Array(this.options.columns) - } - const accepted_header_types = Object.keys(Generator).filter( (t) => ( !['super_', 'camelize'].includes(t) )) - for(let i = 0; i < this.options.columns.length; i++){ - const v = this.options.columns[i] || 'ascii' - if(typeof v === 'string'){ - if(!accepted_header_types.includes(v)){ - throw Error(`Invalid column type: got "${v}", default values are ${JSON.stringify(accepted_header_types)}`) - } - this.options.columns[i] = Generator[v] - } - } - return this -} -util.inherits(Generator, stream.Readable) -// Export the class -module.exports.Generator = Generator -// Generate a random number between 0 and 1 with 2 decimals. The function is idempotent if it detect the "seed" option. -Generator.prototype.random = function(){ - if(this.options.seed){ - return this.options.seed = this.options.seed * Math.PI * 100 % 100 / 100 - }else{ - return Math.random() - } -} -// Stop the generation. -Generator.prototype.end = function(){ - this.push(null) -} -// Put new data into the read queue. -Generator.prototype._read = function(size){ - // Already started - const data = [] - let length = this._.fixed_size_buffer.length - if(length !== 0){ - data.push(this._.fixed_size_buffer) - } - while(true){ - // Time for some rest: flush first and stop later - if( (this._.count_created === this.options.length) || (this.options.end && Date.now() > this.options.end) || (this.options.duration && Date.now() > this._.start_time + this.options.duration) ){ - // Flush - if(data.length){ - if(this.options.objectMode){ - for(const line of data){ - this.__push(line) - } - }else{ - this.__push(data.join('') + (this.options.eof ? this.options.eof : '')) - } - } - // Stop - return this.push(null) - } - // Create the line - let line = [] - let lineLength - this.options.columns.forEach((fn) => { - line.push(fn(this)) - }) - // for(const header in this.options.columns){ - // // Create the field - // line.push(header(this)) - // } - // Obtain line length - if(this.options.objectMode){ - lineLength = 0 - for(const column of line) - lineLength += column.length - }else{ - // Stringify the line - line = (this._.count_created === 0 ? '' : this.options.rowDelimiter)+line.join(this.options.delimiter) - lineLength = line.length - } - this._.count_created++ - if(length + lineLength > size){ - if(this.options.objectMode){ - data.push(line) - for(const line of data){ - this.__push(line) - } - }else{ - if(this.options.fixedSize){ - this._.fixed_size_buffer = line.substr(size - length) - data.push(line.substr(0, size - length)) - }else{ - data.push(line) - } - this.__push(data.join('')) - } - return - } - length += lineLength - data.push(line) - } -} -// Put new data into the read queue. -Generator.prototype.__push = function(record){ - this._.count_written++ - if(this.options.sleep > 0){ - setTimeout( () => { - this.push(record) - }, this.options.sleep) - }else{ - this.push(record) - } -} -// Generate an ASCII value. -Generator.ascii = function(gen){ - // Column - const column = [] - const nb_chars = Math.ceil(gen.random() * gen.options.maxWordLength) - for(let i=0; i= this.size){ - this.resize() - if(length >= this.size){ - throw Error('INVALID_BUFFER_STATE') - } - } - const buf = this.buf - this.buf = Buffer.alloc(this.size) - val.copy(this.buf, 0) - buf.copy(this.buf, val.length) - this.length += val.length - }else{ - const length = this.length++ - if(length === this.size){ - this.resize() - } - const buf = this.clone() - this.buf[0] = val - buf.copy(this.buf,1, 0, length) - } - } - append(val){ - const length = this.length++ - if(length === this.size){ - this.resize() - } - this.buf[length] = val - } - clone(){ - return Buffer.from(this.buf.slice(0, this.length)) - } - resize(){ - const length = this.length - this.size = this.size * 2 - const buf = Buffer.alloc(this.size) - this.buf.copy(buf,0, 0, length) - this.buf = buf - } - toString(encoding){ - if(encoding){ - return this.buf.slice(0, this.length).toString(encoding) - }else{ - return Uint8Array.prototype.slice.call(this.buf.slice(0, this.length)) - } - } - toJSON(){ - return this.toString('utf8') - } - reset(){ - this.length = 0 - } -} - -module.exports = ResizeableBuffer - -}).call(this)}).call(this,require("buffer").Buffer) -},{"buffer":13}],5:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ - -/* -CSV Parse - -Please look at the [project documentation](https://csv.js.org/parse/) for -additional information. -*/ - -const { Transform } = require('stream') -const ResizeableBuffer = require('./ResizeableBuffer') - -// white space characters -// https://en.wikipedia.org/wiki/Whitespace_character -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Character_Classes#Types -// \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff -const tab = 9 -const nl = 10 // \n, 0x0A in hexadecimal, 10 in decimal -const np = 12 -const cr = 13 // \r, 0x0D in hexadécimal, 13 in decimal -const space = 32 -const boms = { - // Note, the following are equals: - // Buffer.from("\ufeff") - // Buffer.from([239, 187, 191]) - // Buffer.from('EFBBBF', 'hex') - 'utf8': Buffer.from([239, 187, 191]), - // Note, the following are equals: - // Buffer.from "\ufeff", 'utf16le - // Buffer.from([255, 254]) - 'utf16le': Buffer.from([255, 254]) -} - -class Parser extends Transform { - constructor(opts = {}){ - super({...{readableObjectMode: true}, ...opts, encoding: null}) - this.__originalOptions = opts - this.__normalizeOptions(opts) - } - __normalizeOptions(opts){ - const options = {} - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - // Normalize option `encoding` - // Note: defined first because other options depends on it - // to convert chars/strings into buffers. - if(options.encoding === undefined || options.encoding === true){ - options.encoding = 'utf8' - }else if(options.encoding === null || options.encoding === false){ - options.encoding = null - }else if(typeof options.encoding !== 'string' && options.encoding !== null){ - throw new CsvError('CSV_INVALID_OPTION_ENCODING', [ - 'Invalid option encoding:', - 'encoding must be a string or null to return a buffer,', - `got ${JSON.stringify(options.encoding)}` - ], options) - } - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - throw new CsvError('CSV_INVALID_OPTION_BOM', [ - 'Invalid option bom:', 'bom must be true,', - `got ${JSON.stringify(options.bom)}` - ], options) - } - // Normalize option `cast` - let fnCastField = null - if(options.cast === undefined || options.cast === null || options.cast === false || options.cast === ''){ - options.cast = undefined - }else if(typeof options.cast === 'function'){ - fnCastField = options.cast - options.cast = true - }else if(options.cast !== true){ - throw new CsvError('CSV_INVALID_OPTION_CAST', [ - 'Invalid option cast:', 'cast must be true or a function,', - `got ${JSON.stringify(options.cast)}` - ], options) - } - // Normalize option `cast_date` - if(options.cast_date === undefined || options.cast_date === null || options.cast_date === false || options.cast_date === ''){ - options.cast_date = false - }else if(options.cast_date === true){ - options.cast_date = function(value){ - const date = Date.parse(value) - return !isNaN(date) ? new Date(date) : value - } - }else if(typeof options.cast_date !== 'function'){ - throw new CsvError('CSV_INVALID_OPTION_CAST_DATE', [ - 'Invalid option cast_date:', 'cast_date must be true or a function,', - `got ${JSON.stringify(options.cast_date)}` - ], options) - } - // Normalize option `columns` - let fnFirstLineToHeaders = null - if(options.columns === true){ - // Fields in the first line are converted as-is to columns - fnFirstLineToHeaders = undefined - }else if(typeof options.columns === 'function'){ - fnFirstLineToHeaders = options.columns - options.columns = true - }else if(Array.isArray(options.columns)){ - options.columns = normalizeColumnsArray(options.columns) - }else if(options.columns === undefined || options.columns === null || options.columns === false){ - options.columns = false - }else{ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS', [ - 'Invalid option columns:', - 'expect an array, a function or true,', - `got ${JSON.stringify(options.columns)}` - ], options) - } - // Normalize option `columns_duplicates_to_array` - if(options.columns_duplicates_to_array === undefined || options.columns_duplicates_to_array === null || options.columns_duplicates_to_array === false){ - options.columns_duplicates_to_array = false - }else if(options.columns_duplicates_to_array !== true){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'expect an boolean,', - `got ${JSON.stringify(options.columns_duplicates_to_array)}` - ], options) - }else if(options.columns === false){ - throw new CsvError('CSV_INVALID_OPTION_COLUMNS_DUPLICATES_TO_ARRAY', [ - 'Invalid option columns_duplicates_to_array:', - 'the `columns` mode must be activated.' - ], options) - } - // Normalize option `comment` - if(options.comment === undefined || options.comment === null || options.comment === false || options.comment === ''){ - options.comment = null - }else{ - if(typeof options.comment === 'string'){ - options.comment = Buffer.from(options.comment, options.encoding) - } - if(!Buffer.isBuffer(options.comment)){ - throw new CsvError('CSV_INVALID_OPTION_COMMENT', [ - 'Invalid option comment:', - 'comment must be a buffer or a string,', - `got ${JSON.stringify(options.comment)}` - ], options) - } - } - // Normalize option `delimiter` - const delimiter_json = JSON.stringify(options.delimiter) - if(!Array.isArray(options.delimiter)) options.delimiter = [options.delimiter] - if(options.delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - options.delimiter = options.delimiter.map(function(delimiter){ - if(delimiter === undefined || delimiter === null || delimiter === false){ - return Buffer.from(',', options.encoding) - } - if(typeof delimiter === 'string'){ - delimiter = Buffer.from(delimiter, options.encoding) - } - if( !Buffer.isBuffer(delimiter) || delimiter.length === 0){ - throw new CsvError('CSV_INVALID_OPTION_DELIMITER', [ - 'Invalid option delimiter:', - 'delimiter must be a non empty string or buffer or array of string|buffer,', - `got ${delimiter_json}` - ], options) - } - return delimiter - }) - // Normalize option `escape` - if(options.escape === undefined || options.escape === true){ - options.escape = Buffer.from('"', options.encoding) - }else if(typeof options.escape === 'string'){ - options.escape = Buffer.from(options.escape, options.encoding) - }else if (options.escape === null || options.escape === false){ - options.escape = null - } - if(options.escape !== null){ - if(!Buffer.isBuffer(options.escape)){ - throw new Error(`Invalid Option: escape must be a buffer, a string or a boolean, got ${JSON.stringify(options.escape)}`) - } - } - // Normalize option `from` - if(options.from === undefined || options.from === null){ - options.from = 1 - }else{ - if(typeof options.from === 'string' && /\d+/.test(options.from)){ - options.from = parseInt(options.from) - } - if(Number.isInteger(options.from)){ - if(options.from < 0){ - throw new Error(`Invalid Option: from must be a positive integer, got ${JSON.stringify(opts.from)}`) - } - }else{ - throw new Error(`Invalid Option: from must be an integer, got ${JSON.stringify(options.from)}`) - } - } - // Normalize option `from_line` - if(options.from_line === undefined || options.from_line === null){ - options.from_line = 1 - }else{ - if(typeof options.from_line === 'string' && /\d+/.test(options.from_line)){ - options.from_line = parseInt(options.from_line) - } - if(Number.isInteger(options.from_line)){ - if(options.from_line <= 0){ - throw new Error(`Invalid Option: from_line must be a positive integer greater than 0, got ${JSON.stringify(opts.from_line)}`) - } - }else{ - throw new Error(`Invalid Option: from_line must be an integer, got ${JSON.stringify(opts.from_line)}`) - } - } - // Normalize options `ignore_last_delimiters` - if(options.ignore_last_delimiters === undefined || options.ignore_last_delimiters === null){ - options.ignore_last_delimiters = false - }else if(typeof options.ignore_last_delimiters === 'number'){ - options.ignore_last_delimiters = Math.floor(options.ignore_last_delimiters) - if(options.ignore_last_delimiters === 0){ - options.ignore_last_delimiters = false - } - }else if(typeof options.ignore_last_delimiters !== 'boolean'){ - throw new CsvError('CSV_INVALID_OPTION_IGNORE_LAST_DELIMITERS', [ - 'Invalid option `ignore_last_delimiters`:', - 'the value must be a boolean value or an integer,', - `got ${JSON.stringify(options.ignore_last_delimiters)}` - ], options) - } - if(options.ignore_last_delimiters === true && options.columns === false){ - throw new CsvError('CSV_IGNORE_LAST_DELIMITERS_REQUIRES_COLUMNS', [ - 'The option `ignore_last_delimiters`', - 'requires the activation of the `columns` option' - ], options) - } - // Normalize option `info` - if(options.info === undefined || options.info === null || options.info === false){ - options.info = false - }else if(options.info !== true){ - throw new Error(`Invalid Option: info must be true, got ${JSON.stringify(options.info)}`) - } - // Normalize option `max_record_size` - if(options.max_record_size === undefined || options.max_record_size === null || options.max_record_size === false){ - options.max_record_size = 0 - }else if(Number.isInteger(options.max_record_size) && options.max_record_size >= 0){ - // Great, nothing to do - }else if(typeof options.max_record_size === 'string' && /\d+/.test(options.max_record_size)){ - options.max_record_size = parseInt(options.max_record_size) - }else{ - throw new Error(`Invalid Option: max_record_size must be a positive integer, got ${JSON.stringify(options.max_record_size)}`) - } - // Normalize option `objname` - if(options.objname === undefined || options.objname === null || options.objname === false){ - options.objname = undefined - }else if(Buffer.isBuffer(options.objname)){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty buffer`) - } - if(options.encoding === null){ - // Don't call `toString`, leave objname as a buffer - }else{ - options.objname = options.objname.toString(options.encoding) - } - }else if(typeof options.objname === 'string'){ - if(options.objname.length === 0){ - throw new Error(`Invalid Option: objname must be a non empty string`) - } - // Great, nothing to do - }else{ - throw new Error(`Invalid Option: objname must be a string or a buffer, got ${options.objname}`) - } - // Normalize option `on_record` - if(options.on_record === undefined || options.on_record === null){ - options.on_record = undefined - }else if(typeof options.on_record !== 'function'){ - throw new CsvError('CSV_INVALID_OPTION_ON_RECORD', [ - 'Invalid option `on_record`:', - 'expect a function,', - `got ${JSON.stringify(options.on_record)}` - ], options) - } - // Normalize option `quote` - if(options.quote === null || options.quote === false || options.quote === ''){ - options.quote = null - }else{ - if(options.quote === undefined || options.quote === true){ - options.quote = Buffer.from('"', options.encoding) - }else if(typeof options.quote === 'string'){ - options.quote = Buffer.from(options.quote, options.encoding) - } - if(!Buffer.isBuffer(options.quote)){ - throw new Error(`Invalid Option: quote must be a buffer or a string, got ${JSON.stringify(options.quote)}`) - } - } - // Normalize option `raw` - if(options.raw === undefined || options.raw === null || options.raw === false){ - options.raw = false - }else if(options.raw !== true){ - throw new Error(`Invalid Option: raw must be true, got ${JSON.stringify(options.raw)}`) - } - // Normalize option `record_delimiter` - if(!options.record_delimiter){ - options.record_delimiter = [] - }else if(!Array.isArray(options.record_delimiter)){ - options.record_delimiter = [options.record_delimiter] - } - options.record_delimiter = options.record_delimiter.map( function(rd){ - if(typeof rd === 'string'){ - rd = Buffer.from(rd, options.encoding) - } - return rd - }) - // Normalize option `relax` - if(typeof options.relax === 'boolean'){ - // Great, nothing to do - }else if(options.relax === undefined || options.relax === null){ - options.relax = false - }else{ - throw new Error(`Invalid Option: relax must be a boolean, got ${JSON.stringify(options.relax)}`) - } - // Normalize option `relax_column_count` - if(typeof options.relax_column_count === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count === undefined || options.relax_column_count === null){ - options.relax_column_count = false - }else{ - throw new Error(`Invalid Option: relax_column_count must be a boolean, got ${JSON.stringify(options.relax_column_count)}`) - } - if(typeof options.relax_column_count_less === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_less === undefined || options.relax_column_count_less === null){ - options.relax_column_count_less = false - }else{ - throw new Error(`Invalid Option: relax_column_count_less must be a boolean, got ${JSON.stringify(options.relax_column_count_less)}`) - } - if(typeof options.relax_column_count_more === 'boolean'){ - // Great, nothing to do - }else if(options.relax_column_count_more === undefined || options.relax_column_count_more === null){ - options.relax_column_count_more = false - }else{ - throw new Error(`Invalid Option: relax_column_count_more must be a boolean, got ${JSON.stringify(options.relax_column_count_more)}`) - } - // Normalize option `skip_empty_lines` - if(typeof options.skip_empty_lines === 'boolean'){ - // Great, nothing to do - }else if(options.skip_empty_lines === undefined || options.skip_empty_lines === null){ - options.skip_empty_lines = false - }else{ - throw new Error(`Invalid Option: skip_empty_lines must be a boolean, got ${JSON.stringify(options.skip_empty_lines)}`) - } - // Normalize option `skip_lines_with_empty_values` - if(typeof options.skip_lines_with_empty_values === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_empty_values === undefined || options.skip_lines_with_empty_values === null){ - options.skip_lines_with_empty_values = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_empty_values must be a boolean, got ${JSON.stringify(options.skip_lines_with_empty_values)}`) - } - // Normalize option `skip_lines_with_error` - if(typeof options.skip_lines_with_error === 'boolean'){ - // Great, nothing to do - }else if(options.skip_lines_with_error === undefined || options.skip_lines_with_error === null){ - options.skip_lines_with_error = false - }else{ - throw new Error(`Invalid Option: skip_lines_with_error must be a boolean, got ${JSON.stringify(options.skip_lines_with_error)}`) - } - // Normalize option `rtrim` - if(options.rtrim === undefined || options.rtrim === null || options.rtrim === false){ - options.rtrim = false - }else if(options.rtrim !== true){ - throw new Error(`Invalid Option: rtrim must be a boolean, got ${JSON.stringify(options.rtrim)}`) - } - // Normalize option `ltrim` - if(options.ltrim === undefined || options.ltrim === null || options.ltrim === false){ - options.ltrim = false - }else if(options.ltrim !== true){ - throw new Error(`Invalid Option: ltrim must be a boolean, got ${JSON.stringify(options.ltrim)}`) - } - // Normalize option `trim` - if(options.trim === undefined || options.trim === null || options.trim === false){ - options.trim = false - }else if(options.trim !== true){ - throw new Error(`Invalid Option: trim must be a boolean, got ${JSON.stringify(options.trim)}`) - } - // Normalize options `trim`, `ltrim` and `rtrim` - if(options.trim === true && opts.ltrim !== false){ - options.ltrim = true - }else if(options.ltrim !== true){ - options.ltrim = false - } - if(options.trim === true && opts.rtrim !== false){ - options.rtrim = true - }else if(options.rtrim !== true){ - options.rtrim = false - } - // Normalize option `to` - if(options.to === undefined || options.to === null){ - options.to = -1 - }else{ - if(typeof options.to === 'string' && /\d+/.test(options.to)){ - options.to = parseInt(options.to) - } - if(Number.isInteger(options.to)){ - if(options.to <= 0){ - throw new Error(`Invalid Option: to must be a positive integer greater than 0, got ${JSON.stringify(opts.to)}`) - } - }else{ - throw new Error(`Invalid Option: to must be an integer, got ${JSON.stringify(opts.to)}`) - } - } - // Normalize option `to_line` - if(options.to_line === undefined || options.to_line === null){ - options.to_line = -1 - }else{ - if(typeof options.to_line === 'string' && /\d+/.test(options.to_line)){ - options.to_line = parseInt(options.to_line) - } - if(Number.isInteger(options.to_line)){ - if(options.to_line <= 0){ - throw new Error(`Invalid Option: to_line must be a positive integer greater than 0, got ${JSON.stringify(opts.to_line)}`) - } - }else{ - throw new Error(`Invalid Option: to_line must be an integer, got ${JSON.stringify(opts.to_line)}`) - } - } - this.info = { - bytes: 0, - comment_lines: 0, - empty_lines: 0, - invalid_field_length: 0, - lines: 1, - records: 0 - } - this.options = options - this.state = { - bomSkipped: false, - bufBytesStart: 0, - castField: fnCastField, - commenting: false, - // Current error encountered by a record - error: undefined, - enabled: options.from_line === 1, - escaping: false, - // escapeIsQuote: options.escape === options.quote, - escapeIsQuote: Buffer.isBuffer(options.escape) && Buffer.isBuffer(options.quote) && Buffer.compare(options.escape, options.quote) === 0, - // columns can be `false`, `true`, `Array` - expectedRecordLength: Array.isArray(options.columns) ? options.columns.length : undefined, - field: new ResizeableBuffer(20), - firstLineToHeaders: fnFirstLineToHeaders, - needMoreDataSize: Math.max( - // Skip if the remaining buffer smaller than comment - options.comment !== null ? options.comment.length : 0, - // Skip if the remaining buffer can be delimiter - ...options.delimiter.map( (delimiter) => delimiter.length), - // Skip if the remaining buffer can be escape sequence - options.quote !== null ? options.quote.length : 0, - ), - previousBuf: undefined, - quoting: false, - stop: false, - rawBuffer: new ResizeableBuffer(100), - record: [], - recordHasError: false, - record_length: 0, - recordDelimiterMaxLength: options.record_delimiter.length === 0 ? 2 : Math.max(...options.record_delimiter.map( (v) => v.length)), - trimChars: [Buffer.from(' ', options.encoding)[0], Buffer.from('\t', options.encoding)[0]], - wasQuoting: false, - wasRowDelimiter: false - } - } - // Implementation of `Transform._transform` - _transform(buf, encoding, callback){ - if(this.state.stop === true){ - return - } - const err = this.__parse(buf, false) - if(err !== undefined){ - this.state.stop = true - } - callback(err) - } - // Implementation of `Transform._flush` - _flush(callback){ - if(this.state.stop === true){ - return - } - const err = this.__parse(undefined, true) - callback(err) - } - // Central parser implementation - __parse(nextBuf, end){ - const {bom, comment, escape, from_line, ltrim, max_record_size, quote, raw, relax, rtrim, skip_empty_lines, to, to_line} = this.options - let {record_delimiter} = this.options - const {bomSkipped, previousBuf, rawBuffer, escapeIsQuote} = this.state - let buf - if(previousBuf === undefined){ - if(nextBuf === undefined){ - // Handle empty string - this.push(null) - return - }else{ - buf = nextBuf - } - }else if(previousBuf !== undefined && nextBuf === undefined){ - buf = previousBuf - }else{ - buf = Buffer.concat([previousBuf, nextBuf]) - } - // Handle UTF BOM - if(bomSkipped === false){ - if(bom === false){ - this.state.bomSkipped = true - }else if(buf.length < 3){ - // No enough data - if(end === false){ - // Wait for more data - this.state.previousBuf = buf - return - } - }else{ - for(let encoding in boms){ - if(boms[encoding].compare(buf, 0, boms[encoding].length) === 0){ - // Skip BOM - let bomLength = boms[encoding].length - this.state.bufBytesStart += bomLength - buf = buf.slice(bomLength) - // Renormalize original options with the new encoding - this.__normalizeOptions({...this.__originalOptions, encoding: encoding}) - break - } - } - this.state.bomSkipped = true - } - } - const bufLen = buf.length - let pos - for(pos = 0; pos < bufLen; pos++){ - // Ensure we get enough space to look ahead - // There should be a way to move this out of the loop - if(this.__needMoreData(pos, bufLen, end)){ - break - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - if(to_line !== -1 && this.info.lines > to_line){ - this.state.stop = true - this.push(null) - return - } - // Auto discovery of record_delimiter, unix, mac and windows supported - if(this.state.quoting === false && record_delimiter.length === 0){ - const record_delimiterCount = this.__autoDiscoverRecordDelimiter(buf, pos) - if(record_delimiterCount){ - record_delimiter = this.options.record_delimiter - } - } - const chr = buf[pos] - if(raw === true){ - rawBuffer.append(chr) - } - if((chr === cr || chr === nl) && this.state.wasRowDelimiter === false ){ - this.state.wasRowDelimiter = true - } - // Previous char was a valid escape char - // treat the current char as a regular char - if(this.state.escaping === true){ - this.state.escaping = false - }else{ - // Escape is only active inside quoted fields - // We are quoting, the char is an escape chr and there is a chr to escape - // if(escape !== null && this.state.quoting === true && chr === escape && pos + 1 < bufLen){ - if(escape !== null && this.state.quoting === true && this.__isEscape(buf, pos, chr) && pos + escape.length < bufLen){ - if(escapeIsQuote){ - if(this.__isQuote(buf, pos+escape.length)){ - this.state.escaping = true - pos += escape.length - 1 - continue - } - }else{ - this.state.escaping = true - pos += escape.length - 1 - continue - } - } - // Not currently escaping and chr is a quote - // TODO: need to compare bytes instead of single char - if(this.state.commenting === false && this.__isQuote(buf, pos)){ - if(this.state.quoting === true){ - const nextChr = buf[pos+quote.length] - const isNextChrTrimable = rtrim && this.__isCharTrimable(nextChr) - const isNextChrComment = comment !== null && this.__compareBytes(comment, buf, pos+quote.length, nextChr) - const isNextChrDelimiter = this.__isDelimiter(buf, pos+quote.length, nextChr) - const isNextChrRecordDelimiter = record_delimiter.length === 0 ? this.__autoDiscoverRecordDelimiter(buf, pos+quote.length) : this.__isRecordDelimiter(nextChr, buf, pos+quote.length) - // Escape a quote - // Treat next char as a regular character - if(escape !== null && this.__isEscape(buf, pos, chr) && this.__isQuote(buf, pos + escape.length)){ - pos += escape.length - 1 - }else if(!nextChr || isNextChrDelimiter || isNextChrRecordDelimiter || isNextChrComment || isNextChrTrimable){ - this.state.quoting = false - this.state.wasQuoting = true - pos += quote.length - 1 - continue - }else if(relax === false){ - const err = this.__error( - new CsvError('CSV_INVALID_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - `got "${String.fromCharCode(nextChr)}"`, - `at line ${this.info.lines}`, - 'instead of delimiter, record delimiter, trimable character', - '(if activated) or comment', - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - this.state.quoting = false - this.state.wasQuoting = true - this.state.field.prepend(quote) - pos += quote.length - 1 - } - }else{ - if(this.state.field.length !== 0){ - // In relax mode, treat opening quote preceded by chrs as regular - if( relax === false ){ - const err = this.__error( - new CsvError('INVALID_OPENING_QUOTE', [ - 'Invalid Opening Quote:', - `a quote is found inside a field at line ${this.info.lines}`, - ], this.options, this.__infoField(), { - field: this.state.field, - }) - ) - if(err !== undefined) return err - } - }else{ - this.state.quoting = true - pos += quote.length - 1 - continue - } - } - } - if(this.state.quoting === false){ - let recordDelimiterLength = this.__isRecordDelimiter(chr, buf, pos) - if(recordDelimiterLength !== 0){ - // Do not emit comments which take a full line - const skipCommentLine = this.state.commenting && (this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0) - if(skipCommentLine){ - this.info.comment_lines++ - // Skip full comment line - }else{ - // Activate records emition if above from_line - if(this.state.enabled === false && this.info.lines + (this.state.wasRowDelimiter === true ? 1: 0) >= from_line){ - this.state.enabled = true - this.__resetField() - this.__resetRecord() - pos += recordDelimiterLength - 1 - continue - } - // Skip if line is empty and skip_empty_lines activated - if(skip_empty_lines === true && this.state.wasQuoting === false && this.state.record.length === 0 && this.state.field.length === 0){ - this.info.empty_lines++ - pos += recordDelimiterLength - 1 - continue - } - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - this.info.bytes = this.state.bufBytesStart + pos + recordDelimiterLength; - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - if(to !== -1 && this.info.records >= to){ - this.state.stop = true - this.push(null) - return - } - } - this.state.commenting = false - pos += recordDelimiterLength - 1 - continue - } - if(this.state.commenting){ - continue - } - const commentCount = comment === null ? 0 : this.__compareBytes(comment, buf, pos, chr) - if(commentCount !== 0){ - this.state.commenting = true - continue - } - let delimiterLength = this.__isDelimiter(buf, pos, chr) - if(delimiterLength !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - pos += delimiterLength - 1 - continue - } - } - } - if(this.state.commenting === false){ - if(max_record_size !== 0 && this.state.record_length + this.state.field.length > max_record_size){ - const err = this.__error( - new CsvError('CSV_MAX_RECORD_SIZE', [ - 'Max Record Size:', - 'record exceed the maximum number of tolerated bytes', - `of ${max_record_size}`, - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - const lappend = ltrim === false || this.state.quoting === true || this.state.field.length !== 0 || !this.__isCharTrimable(chr) - // rtrim in non quoting is handle in __onField - const rappend = rtrim === false || this.state.wasQuoting === false - if( lappend === true && rappend === true ){ - this.state.field.append(chr) - }else if(rtrim === true && !this.__isCharTrimable(chr)){ - const err = this.__error( - new CsvError('CSV_NON_TRIMABLE_CHAR_AFTER_CLOSING_QUOTE', [ - 'Invalid Closing Quote:', - 'found non trimable byte after quote', - `at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - } - } - if(end === true){ - // Ensure we are not ending in a quoting state - if(this.state.quoting === true){ - const err = this.__error( - new CsvError('CSV_QUOTE_NOT_CLOSED', [ - 'Quote Not Closed:', - `the parsing is finished with an opening quote at line ${this.info.lines}`, - ], this.options, this.__infoField()) - ) - if(err !== undefined) return err - }else{ - // Skip last line if it has no characters - if(this.state.wasQuoting === true || this.state.record.length !== 0 || this.state.field.length !== 0){ - this.info.bytes = this.state.bufBytesStart + pos; - const errField = this.__onField() - if(errField !== undefined) return errField - const errRecord = this.__onRecord() - if(errRecord !== undefined) return errRecord - }else if(this.state.wasRowDelimiter === true){ - this.info.empty_lines++ - }else if(this.state.commenting === true){ - this.info.comment_lines++ - } - } - }else{ - this.state.bufBytesStart += pos - this.state.previousBuf = buf.slice(pos) - } - if(this.state.wasRowDelimiter === true){ - this.info.lines++ - this.state.wasRowDelimiter = false - } - } - __onRecord(){ - const {columns, columns_duplicates_to_array, encoding, info, from, relax_column_count, relax_column_count_less, relax_column_count_more, raw, skip_lines_with_empty_values} = this.options - const {enabled, record} = this.state - if(enabled === false){ - return this.__resetRecord() - } - // Convert the first line into column names - const recordLength = record.length - if(columns === true){ - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - return this.__firstLineToColumns(record) - } - if(columns === false && this.info.records === 0){ - this.state.expectedRecordLength = recordLength - } - if(recordLength !== this.state.expectedRecordLength){ - const err = columns === false ? - // Todo: rename CSV_INCONSISTENT_RECORD_LENGTH to - // CSV_RECORD_INCONSISTENT_FIELDS_LENGTH - new CsvError('CSV_INCONSISTENT_RECORD_LENGTH', [ - 'Invalid Record Length:', - `expect ${this.state.expectedRecordLength},`, - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - : - // Todo: rename CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH to - // CSV_RECORD_INCONSISTENT_COLUMNS - new CsvError('CSV_RECORD_DONT_MATCH_COLUMNS_LENGTH', [ - 'Invalid Record Length:', - `columns length is ${columns.length},`, // rename columns - `got ${recordLength} on line ${this.info.lines}`, - ], this.options, this.__infoField(), { - record: record, - }) - if(relax_column_count === true || - (relax_column_count_less === true && recordLength < this.state.expectedRecordLength) || - (relax_column_count_more === true && recordLength > this.state.expectedRecordLength) ){ - this.info.invalid_field_length++ - this.state.error = err - // Error is undefined with skip_lines_with_error - }else{ - const finalErr = this.__error(err) - if(finalErr) return finalErr - } - } - if(skip_lines_with_empty_values === true && isRecordEmpty(record)){ - this.__resetRecord() - return - } - if(this.state.recordHasError === true){ - this.__resetRecord() - this.state.recordHasError = false - return - } - this.info.records++ - if(from === 1 || this.info.records >= from){ - // With columns, records are object - if(columns !== false){ - const obj = {} - // Transform record array to an object - for(let i = 0, l = record.length; i < l; i++){ - if(columns[i] === undefined || columns[i].disabled) continue - // Turn duplicate columns into an array - if (columns_duplicates_to_array === true && obj[columns[i].name] !== undefined) { - if (Array.isArray(obj[columns[i].name])) { - obj[columns[i].name] = obj[columns[i].name].concat(record[i]) - } else { - obj[columns[i].name] = [obj[columns[i].name], record[i]] - } - } else { - obj[columns[i].name] = record[i] - } - } - const {objname} = this.options - // Without objname (default) - if(objname === undefined){ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: obj}, - (raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}), - (info === true ? {info: this.__infoRecord()}: {}) - )) - if(err){ - return err - } - }else{ - const err = this.__push(obj) - if(err){ - return err - } - } - // With objname (default) - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: [obj[objname], obj]}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push([obj[objname], obj]) - if(err){ - return err - } - } - } - // Without columns, records are array - }else{ - if(raw === true || info === true){ - const err = this.__push(Object.assign( - {record: record}, - raw === true ? {raw: this.state.rawBuffer.toString(encoding)}: {}, - info === true ? {info: this.__infoRecord()}: {} - )) - if(err){ - return err - } - }else{ - const err = this.__push(record) - if(err){ - return err - } - } - } - } - this.__resetRecord() - } - __firstLineToColumns(record){ - const {firstLineToHeaders} = this.state - try{ - const headers = firstLineToHeaders === undefined ? record : firstLineToHeaders.call(null, record) - if(!Array.isArray(headers)){ - return this.__error( - new CsvError('CSV_INVALID_COLUMN_MAPPING', [ - 'Invalid Column Mapping:', - 'expect an array from column function,', - `got ${JSON.stringify(headers)}` - ], this.options, this.__infoField(), { - headers: headers, - }) - ) - } - const normalizedHeaders = normalizeColumnsArray(headers) - this.state.expectedRecordLength = normalizedHeaders.length - this.options.columns = normalizedHeaders - this.__resetRecord() - return - }catch(err){ - return err - } - } - __resetRecord(){ - if(this.options.raw === true){ - this.state.rawBuffer.reset() - } - this.state.error = undefined - this.state.record = [] - this.state.record_length = 0 - } - __onField(){ - const {cast, encoding, rtrim, max_record_size} = this.options - const {enabled, wasQuoting} = this.state - // Short circuit for the from_line options - if(enabled === false){ - return this.__resetField() - } - let field = this.state.field.toString(encoding) - if(rtrim === true && wasQuoting === false){ - field = field.trimRight() - } - if(cast === true){ - const [err, f] = this.__cast(field) - if(err !== undefined) return err - field = f - } - this.state.record.push(field) - // Increment record length if record size must not exceed a limit - if(max_record_size !== 0 && typeof field === 'string'){ - this.state.record_length += field.length - } - this.__resetField() - } - __resetField(){ - this.state.field.reset() - this.state.wasQuoting = false - } - __push(record){ - const {on_record} = this.options - if(on_record !== undefined){ - const info = this.__infoRecord() - try{ - record = on_record.call(null, record, info) - }catch(err){ - return err - } - if(record === undefined || record === null){ return } - } - this.push(record) - } - // Return a tuple with the error and the casted value - __cast(field){ - const {columns, relax_column_count} = this.options - const isColumns = Array.isArray(columns) - // Dont loose time calling cast - // because the final record is an object - // and this field can't be associated to a key present in columns - if( isColumns === true && relax_column_count && this.options.columns.length <= this.state.record.length ){ - return [undefined, undefined] - } - if(this.state.castField !== null){ - try{ - const info = this.__infoField() - return [undefined, this.state.castField.call(null, field, info)] - }catch(err){ - return [err] - } - } - if(this.__isFloat(field)){ - return [undefined, parseFloat(field)] - }else if(this.options.cast_date !== false){ - const info = this.__infoField() - return [undefined, this.options.cast_date.call(null, field, info)] - } - return [undefined, field] - } - // Helper to test if a character is a space or a line delimiter - __isCharTrimable(chr){ - return chr === space || chr === tab || chr === cr || chr === nl || chr === np - } - // Keep it in case we implement the `cast_int` option - // __isInt(value){ - // // return Number.isInteger(parseInt(value)) - // // return !isNaN( parseInt( obj ) ); - // return /^(\-|\+)?[1-9][0-9]*$/.test(value) - // } - __isFloat(value){ - return (value - parseFloat( value ) + 1) >= 0 // Borrowed from jquery - } - __compareBytes(sourceBuf, targetBuf, targetPos, firstByte){ - if(sourceBuf[0] !== firstByte) return 0 - const sourceLength = sourceBuf.length - for(let i = 1; i < sourceLength; i++){ - if(sourceBuf[i] !== targetBuf[targetPos+i]) return 0 - } - return sourceLength - } - __needMoreData(i, bufLen, end){ - if(end) return false - const {quote} = this.options - const {quoting, needMoreDataSize, recordDelimiterMaxLength} = this.state - const numOfCharLeft = bufLen - i - 1 - const requiredLength = Math.max( - needMoreDataSize, - // Skip if the remaining buffer smaller than record delimiter - recordDelimiterMaxLength, - // Skip if the remaining buffer can be record delimiter following the closing quote - // 1 is for quote.length - quoting ? (quote.length + recordDelimiterMaxLength) : 0, - ) - return numOfCharLeft < requiredLength - } - __isDelimiter(buf, pos, chr){ - const {delimiter, ignore_last_delimiters} = this.options - if(ignore_last_delimiters === true && this.state.record.length === this.options.columns.length - 1){ - return 0 - }else if(ignore_last_delimiters !== false && typeof ignore_last_delimiters === 'number' && this.state.record.length === ignore_last_delimiters - 1){ - return 0 - } - loop1: for(let i = 0; i < delimiter.length; i++){ - const del = delimiter[i] - if(del[0] === chr){ - for(let j = 1; j < del.length; j++){ - if(del[j] !== buf[pos+j]) continue loop1 - } - return del.length - } - } - return 0 - } - __isRecordDelimiter(chr, buf, pos){ - const {record_delimiter} = this.options - const recordDelimiterLength = record_delimiter.length - loop1: for(let i = 0; i < recordDelimiterLength; i++){ - const rd = record_delimiter[i] - const rdLength = rd.length - if(rd[0] !== chr){ - continue - } - for(let j = 1; j < rdLength; j++){ - if(rd[j] !== buf[pos+j]){ - continue loop1 - } - } - return rd.length - } - return 0 - } - __isEscape(buf, pos, chr){ - const {escape} = this.options - if(escape === null) return false - const l = escape.length - if(escape[0] === chr){ - for(let i = 0; i < l; i++){ - if(escape[i] !== buf[pos+i]){ - return false - } - } - return true - } - return false - } - __isQuote(buf, pos){ - const {quote} = this.options - if(quote === null) return false - const l = quote.length - for(let i = 0; i < l; i++){ - if(quote[i] !== buf[pos+i]){ - return false - } - } - return true - } - __autoDiscoverRecordDelimiter(buf, pos){ - const {encoding} = this.options - const chr = buf[pos] - if(chr === cr){ - if(buf[pos+1] === nl){ - this.options.record_delimiter.push(Buffer.from('\r\n', encoding)) - this.state.recordDelimiterMaxLength = 2 - return 2 - }else{ - this.options.record_delimiter.push(Buffer.from('\r', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - }else if(chr === nl){ - this.options.record_delimiter.push(Buffer.from('\n', encoding)) - this.state.recordDelimiterMaxLength = 1 - return 1 - } - return 0 - } - __error(msg){ - const {skip_lines_with_error} = this.options - const err = typeof msg === 'string' ? new Error(msg) : msg - if(skip_lines_with_error){ - this.state.recordHasError = true - this.emit('skip', err) - return undefined - }else{ - return err - } - } - __infoDataSet(){ - return { - ...this.info, - columns: this.options.columns - } - } - __infoRecord(){ - const {columns} = this.options - return { - ...this.__infoDataSet(), - error: this.state.error, - header: columns === true, - index: this.state.record.length, - } - } - __infoField(){ - const {columns} = this.options - const isColumns = Array.isArray(columns) - return { - ...this.__infoRecord(), - column: isColumns === true ? - ( columns.length > this.state.record.length ? - columns[this.state.record.length].name : - null - ) : - this.state.record.length, - quoting: this.state.wasQuoting, - } - } -} - -const parse = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument - if(data === undefined && (typeof argument === 'string' || Buffer.isBuffer(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument - }else if(callback === undefined && type === 'function'){ - callback = argument - }else{ - throw new CsvError('CSV_INVALID_ARGUMENT', [ - 'Invalid argument:', - `got ${JSON.stringify(argument)} at index ${i}` - ], options || {}) - } - } - const parser = new Parser(options) - if(callback){ - const records = options === undefined || options.objname === undefined ? [] : {} - parser.on('readable', function(){ - let record - while((record = this.read()) !== null){ - if(options === undefined || options.objname === undefined){ - records.push(record) - }else{ - records[record[0]] = record[1] - } - } - }) - parser.on('error', function(err){ - callback(err, undefined, parser.__infoDataSet()) - }) - parser.on('end', function(){ - callback(undefined, records, parser.__infoDataSet()) - }) - } - if(data !== undefined){ - // Give a chance for events to be registered later - if(typeof setImmediate === 'function'){ - setImmediate(function(){ - parser.write(data) - parser.end() - }) - }else{ - parser.write(data) - parser.end() - } - } - return parser -} - -class CsvError extends Error { - constructor(code, message, options, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString(options.encoding) : value == null ? value : JSON.parse(JSON.stringify(value)) - } - } - } -} - -parse.Parser = Parser - -parse.CsvError = CsvError - -module.exports = parse - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -const isObject = function(obj){ - return (typeof obj === 'object' && obj !== null && !Array.isArray(obj)) -} - -const isRecordEmpty = function(record){ - return record.every( (field) => field == null || field.toString && field.toString().trim() === '' ) -} - -const normalizeColumnsArray = function(columns){ - const normalizedColumns = []; - for(let i = 0, l = columns.length; i < l; i++){ - const column = columns[i] - if(column === undefined || column === null || column === false){ - normalizedColumns[i] = { disabled: true } - }else if(typeof column === 'string'){ - normalizedColumns[i] = { name: column } - }else if(isObject(column)){ - if(typeof column.name !== 'string'){ - throw new CsvError('CSV_OPTION_COLUMNS_MISSING_NAME', [ - 'Option columns missing name:', - `property "name" is required at position ${i}`, - 'when column is an object literal' - ]) - } - normalizedColumns[i] = column - }else{ - throw new CsvError('CSV_INVALID_COLUMN_DEFINITION', [ - 'Invalid column definition:', - 'expect a string or a literal object,', - `got ${JSON.stringify(column)} at position ${i}` - ]) - } - } - return normalizedColumns; -} - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"./ResizeableBuffer":4,"buffer":13,"stream":33,"timers":49}],6:[function(require,module,exports){ -(function (Buffer){(function (){ - -const parse = require('.') - -module.exports = function(data, options={}){ - if(typeof data === 'string'){ - data = Buffer.from(data) - } - const records = options && options.objname ? {} : [] - const parser = new parse.Parser(options) - parser.push = function(record){ - if(record === null){ - return - } - if(options.objname === undefined) - records.push(record) - else{ - records[record[0]] = record[1] - } - } - const err1 = parser.__parse(data, false) - if(err1 !== undefined) throw err1 - const err2 = parser.__parse(undefined, true) - if(err2 !== undefined) throw err2 - return records -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{".":5,"buffer":13}],7:[function(require,module,exports){ -(function (Buffer,setImmediate){(function (){ - -/* -CSV Stringify - -Please look at the [project documentation](https://csv.js.org/stringify/) for -additional information. -*/ - -const { Transform } = require('stream') -const bom_utf8 = Buffer.from([239, 187, 191]) - -class Stringifier extends Transform { - constructor(opts = {}){ - super({...{writableObjectMode: true}, ...opts}) - const options = {} - let err - // Merge with user options - for(let opt in opts){ - options[underscore(opt)] = opts[opt] - } - if(err = this.normalize(options)) throw err - switch(options.record_delimiter){ - case 'auto': - options.record_delimiter = null - break - case 'unix': - options.record_delimiter = "\n" - break - case 'mac': - options.record_delimiter = "\r" - break - case 'windows': - options.record_delimiter = "\r\n" - break - case 'ascii': - options.record_delimiter = "\u001e" - break - case 'unicode': - options.record_delimiter = "\u2028" - break - } - // Expose options - this.options = options - // Internal state - this.state = { - stop: false - } - // Information - this.info = { - records: 0 - } - } - normalize(options){ - // Normalize option `bom` - if(options.bom === undefined || options.bom === null || options.bom === false){ - options.bom = false - }else if(options.bom !== true){ - return new CsvError('CSV_OPTION_BOOLEAN_INVALID_TYPE', [ - 'option `bom` is optional and must be a boolean value,', - `got ${JSON.stringify(options.bom)}` - ]) - } - // Normalize option `delimiter` - if(options.delimiter === undefined || options.delimiter === null){ - options.delimiter = ',' - }else if(Buffer.isBuffer(options.delimiter)){ - options.delimiter = options.delimiter.toString() - }else if(typeof options.delimiter !== 'string'){ - return new CsvError('CSV_OPTION_DELIMITER_INVALID_TYPE', [ - 'option `delimiter` must be a buffer or a string,', - `got ${JSON.stringify(options.delimiter)}` - ]) - } - // Normalize option `quote` - if(options.quote === undefined || options.quote === null){ - options.quote = '"' - }else if(options.quote === true){ - options.quote = '"' - }else if(options.quote === false){ - options.quote = '' - }else if (Buffer.isBuffer(options.quote)){ - options.quote = options.quote.toString() - }else if(typeof options.quote !== 'string'){ - return new CsvError('CSV_OPTION_QUOTE_INVALID_TYPE', [ - 'option `quote` must be a boolean, a buffer or a string,', - `got ${JSON.stringify(options.quote)}` - ]) - } - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `quoted_empty` - if(options.quoted_empty === undefined || options.quoted_empty === null){ - options.quoted_empty = undefined - }else{ - // todo - } - // Normalize option `quoted_match` - if(options.quoted_match === undefined || options.quoted_match === null || options.quoted_match === false){ - options.quoted_match = null - }else if(!Array.isArray(options.quoted_match)){ - options.quoted_match = [options.quoted_match] - } - if(options.quoted_match){ - for(let quoted_match of options.quoted_match){ - const isString = typeof quoted_match === 'string' - const isRegExp = quoted_match instanceof RegExp - if(!isString && !isRegExp){ - return Error(`Invalid Option: quoted_match must be a string or a regex, got ${JSON.stringify(quoted_match)}`) - } - } - } - // Normalize option `quoted_string` - if(options.quoted_string === undefined || options.quoted_string === null){ - options.quoted_string = false - }else{ - // todo - } - // Normalize option `eof` - if(options.eof === undefined || options.eof === null){ - options.eof = true - }else{ - // todo - } - // Normalize option `escape` - if(options.escape === undefined || options.escape === null){ - options.escape = '"' - }else if(Buffer.isBuffer(options.escape)){ - options.escape = options.escape.toString() - }else if(typeof options.escape !== 'string'){ - return Error(`Invalid Option: escape must be a buffer or a string, got ${JSON.stringify(options.escape)}`) - } - if (options.escape.length > 1){ - return Error(`Invalid Option: escape must be one character, got ${options.escape.length} characters`) - } - // Normalize option `header` - if(options.header === undefined || options.header === null){ - options.header = false - }else{ - // todo - } - // Normalize option `columns` - options.columns = this.normalize_columns(options.columns) - // Normalize option `quoted` - if(options.quoted === undefined || options.quoted === null){ - options.quoted = false - }else{ - // todo - } - // Normalize option `cast` - if(options.cast === undefined || options.cast === null){ - options.cast = {} - }else{ - // todo - } - // Normalize option cast.bigint - if(options.cast.bigint === undefined || options.cast.bigint === null){ - // Cast boolean to string by default - options.cast.bigint = value => '' + value - } - // Normalize option cast.boolean - if(options.cast.boolean === undefined || options.cast.boolean === null){ - // Cast boolean to string by default - options.cast.boolean = value => value ? '1' : '' - } - // Normalize option cast.date - if(options.cast.date === undefined || options.cast.date === null){ - // Cast date to timestamp string by default - options.cast.date = value => '' + value.getTime() - } - // Normalize option cast.number - if(options.cast.number === undefined || options.cast.number === null){ - // Cast number to string using native casting by default - options.cast.number = value => '' + value - } - // Normalize option cast.object - if(options.cast.object === undefined || options.cast.object === null){ - // Stringify object as JSON by default - options.cast.object = value => JSON.stringify(value) - } - // Normalize option cast.string - if(options.cast.string === undefined || options.cast.string === null){ - // Leave string untouched - options.cast.string = function(value){return value} - } - // Normalize option `record_delimiter` - if(options.record_delimiter === undefined || options.record_delimiter === null){ - options.record_delimiter = '\n' - }else if(Buffer.isBuffer(options.record_delimiter)){ - options.record_delimiter = options.record_delimiter.toString() - }else if(typeof options.record_delimiter !== 'string'){ - return Error(`Invalid Option: record_delimiter must be a buffer or a string, got ${JSON.stringify(options.record_delimiter)}`) - } - } - _transform(chunk, encoding, callback){ - if(this.state.stop === true){ - return - } - // Chunk validation - if(!Array.isArray(chunk) && typeof chunk !== 'object'){ - this.state.stop = true - return callback(Error(`Invalid Record: expect an array or an object, got ${JSON.stringify(chunk)}`)) - } - // Detect columns from the first record - if(this.info.records === 0){ - if(Array.isArray(chunk)){ - if(this.options.header === true && !this.options.columns){ - this.state.stop = true - return callback(Error('Undiscoverable Columns: header option requires column option or object records')) - } - }else if(this.options.columns === undefined || this.options.columns === null){ - this.options.columns = this.normalize_columns(Object.keys(chunk)) - } - } - // Emit the header - if(this.info.records === 0){ - this.bom() - this.headers() - } - // Emit and stringify the record if an object or an array - try{ - this.emit('record', chunk, this.info.records) - }catch(err){ - this.state.stop = true - return this.emit('error', err) - } - // Convert the record into a string - let chunk_string - if(this.options.eof){ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - chunk_string = chunk_string + this.options.record_delimiter - } - }else{ - chunk_string = this.stringify(chunk) - if(chunk_string === undefined){ - return - }else{ - if(this.options.header || this.info.records){ - chunk_string = this.options.record_delimiter + chunk_string - } - } - } - // Emit the csv - this.info.records++ - this.push(chunk_string) - callback() - } - _flush(callback){ - if(this.info.records === 0){ - this.bom() - this.headers() - } - callback() - } - stringify(chunk, chunkIsHeader=false){ - if(typeof chunk !== 'object'){ - return chunk - } - const {columns, header} = this.options - const record = [] - // Record is an array - if(Array.isArray(chunk)){ - // We are getting an array but the user has specified output columns. In - // this case, we respect the columns indexes - if(columns){ - chunk.splice(columns.length) - } - // Cast record elements - for(let i=0; i= 0 - const containsQuote = (quote !== '') && value.indexOf(quote) >= 0 - const containsEscape = value.indexOf(escape) >= 0 && (escape !== quote) - const containsRecordDelimiter = value.indexOf(record_delimiter) >= 0 - const quotedString = quoted_string && typeof field === 'string' - let quotedMatch = quoted_match && quoted_match.filter( quoted_match => { - if(typeof quoted_match === 'string'){ - return value.indexOf(quoted_match) !== -1 - }else{ - return quoted_match.test(value) - } - }) - quotedMatch = quotedMatch && quotedMatch.length > 0 - const shouldQuote = containsQuote === true || containsdelimiter || containsRecordDelimiter || quoted || quotedString || quotedMatch - if(shouldQuote === true && containsEscape === true){ - const regexp = escape === '\\' - ? new RegExp(escape + escape, 'g') - : new RegExp(escape, 'g') - value = value.replace(regexp, escape + escape) - } - if(containsQuote === true){ - const regexp = new RegExp(quote,'g') - value = value.replace(regexp, escape + quote) - } - if(shouldQuote === true){ - value = quote + value + quote - } - csvrecord += value - }else if(quoted_empty === true || (field === '' && quoted_string === true && quoted_empty !== false)){ - csvrecord += quote + quote - } - if(i !== record.length - 1){ - csvrecord += delimiter - } - } - return csvrecord - } - bom(){ - if(this.options.bom !== true){ - return - } - this.push(bom_utf8) - } - headers(){ - if(this.options.header === false){ - return - } - if(this.options.columns === undefined){ - return - } - let headers = this.options.columns.map(column => column.header) - if(this.options.eof){ - headers = this.stringify(headers, true) + this.options.record_delimiter - }else{ - headers = this.stringify(headers) - } - this.push(headers) - } - __cast(value, context){ - const type = typeof value - try{ - if(type === 'string'){ // Fine for 99% of the cases - return [undefined, this.options.cast.string(value, context)] - }else if(type === 'bigint'){ - return [undefined, this.options.cast.bigint(value, context)] - }else if(type === 'number'){ - return [undefined, this.options.cast.number(value, context)] - }else if(type === 'boolean'){ - return [undefined, this.options.cast.boolean(value, context)] - }else if(value instanceof Date){ - return [undefined, this.options.cast.date(value, context)] - }else if(type === 'object' && value !== null){ - return [undefined, this.options.cast.object(value, context)] - }else{ - return [undefined, value, value] - } - }catch(err){ - return [err] - } - } - normalize_columns(columns){ - if(columns === undefined || columns === null){ - return undefined - } - if(typeof columns !== 'object'){ - throw Error('Invalid option "columns": expect an array or an object') - } - if(!Array.isArray(columns)){ - const newcolumns = [] - for(let k in columns){ - newcolumns.push({ - key: k, - header: columns[k] - }) - } - columns = newcolumns - }else{ - const newcolumns = [] - for(let column of columns){ - if(typeof column === 'string'){ - newcolumns.push({ - key: column, - header: column - }) - }else if(typeof column === 'object' && column !== undefined && !Array.isArray(column)){ - if(!column.key){ - throw Error('Invalid column definition: property "key" is required') - } - if(column.header === undefined){ - column.header = column.key - } - newcolumns.push(column) - }else{ - throw Error('Invalid column definition: expect a string or an object') - } - } - columns = newcolumns - } - return columns - } -} - -const stringify = function(){ - let data, options, callback - for(let i in arguments){ - const argument = arguments[i] - const type = typeof argument - if(data === undefined && (Array.isArray(argument))){ - data = argument - }else if(options === undefined && isObject(argument)){ - options = argument - }else if(callback === undefined && type === 'function'){ - callback = argument - }else{ - throw new CsvError('CSV_INVALID_ARGUMENT', [ - 'Invalid argument:', - `got ${JSON.stringify(argument)} at index ${i}` - ]) - } - } - const stringifier = new Stringifier(options) - if(callback){ - const chunks = [] - stringifier.on('readable', function(){ - let chunk - while((chunk = this.read()) !== null){ - chunks.push(chunk) - } - }) - stringifier.on('error', function(err){ - callback(err) - }) - stringifier.on('end', function(){ - callback(undefined, chunks.join('')) - }) - } - if(data !== undefined){ - // Give a chance for events to be registered later - if(typeof setImmediate === 'function'){ - setImmediate(function(){ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - }) - }else{ - for(let record of data){ - stringifier.write(record) - } - stringifier.end() - } - } - return stringifier -} - -class CsvError extends Error { - constructor(code, message, ...contexts) { - if(Array.isArray(message)) message = message.join(' ') - super(message) - if(Error.captureStackTrace !== undefined){ - Error.captureStackTrace(this, CsvError) - } - this.code = code - for(const context of contexts){ - for(const key in context){ - const value = context[key] - this[key] = Buffer.isBuffer(value) ? value.toString() : value == null ? value : JSON.parse(JSON.stringify(value)) - } - } - } -} - -stringify.Stringifier = Stringifier - -stringify.CsvError = CsvError - -module.exports = stringify - -const isObject = function(obj){ - return typeof obj === 'object' && obj !== null && ! Array.isArray(obj) -} - -const underscore = function(str){ - return str.replace(/([A-Z])/g, function(_, match){ - return '_' + match.toLowerCase() - }) -} - -// Lodash implementation of `get` - -const charCodeOfDot = '.'.charCodeAt(0) -const reEscapeChar = /\\(\\)?/g -const rePropName = RegExp( - // Match anything that isn't a dot or bracket. - '[^.[\\]]+' + '|' + - // Or match property names within brackets. - '\\[(?:' + - // Match a non-string expression. - '([^"\'][^[]*)' + '|' + - // Or match strings (supports escaping characters). - '(["\'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2' + - ')\\]'+ '|' + - // Or match "" as the space between consecutive dots or empty brackets. - '(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))' -, 'g') -const reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/ -const reIsPlainProp = /^\w*$/ -const getTag = function(value){ - if(!value) - value === undefined ? '[object Undefined]' : '[object Null]' - return Object.prototype.toString.call(value) -} -const isKey = function(value, object){ - if(Array.isArray(value)){ - return false - } - const type = typeof value - if(type === 'number' || type === 'symbol' || type === 'boolean' || !value || isSymbol(value)){ - return true - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)) -} -const isSymbol = function(value){ - const type = typeof value - return type === 'symbol' || (type === 'object' && value && getTag(value) === '[object Symbol]') -} -const stringToPath = function(string){ - const result = [] - if(string.charCodeAt(0) === charCodeOfDot){ - result.push('') - } - string.replace(rePropName, function(match, expression, quote, subString){ - let key = match - if(quote){ - key = subString.replace(reEscapeChar, '$1') - }else if(expression){ - key = expression.trim() - } - result.push(key) - }) - return result -} -const castPath = function(value, object){ - if(Array.isArray(value)){ - return value - } else { - return isKey(value, object) ? [value] : stringToPath(value) - } -} -const toKey = function(value){ - if(typeof value === 'string' || isSymbol(value)) - return value - const result = `${value}` - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result -} -const get = function(object, path){ - path = castPath(path, object) - let index = 0 - const length = path.length - while(object != null && index < length){ - object = object[toKey(path[index++])] - } - return (index && index === length) ? object : undefined -} - -}).call(this)}).call(this,require("buffer").Buffer,require("timers").setImmediate) -},{"buffer":13,"stream":33,"timers":49}],8:[function(require,module,exports){ -(function (Buffer){(function (){ - -const stringify = require('.') -const {StringDecoder} = require('string_decoder') - -module.exports = function(records, options={}){ - const data = [] - if(Buffer.isBuffer(records)){ - const decoder = new StringDecoder() - records = decoder.write(records) - } - function onData(record){ - if(record){ - data.push(record.toString()) - } - } - let stringifier = new stringify.Stringifier(options) - stringifier.on('data', onData); - for(let record of records){ - stringifier.write(record) - } - stringifier.end() - stringifier.off('data', onData); - return data.join('') -} - -}).call(this)}).call(this,{"isBuffer":require("../../../packages/csv/node_modules/is-buffer/index.js")}) -},{".":7,"../../../packages/csv/node_modules/is-buffer/index.js":28,"string_decoder":48}],9:[function(require,module,exports){ -// Alias to the ES6 modules exposing the sync API -module.exports = { - generate: require('csv-generate/lib/sync'), - parse: require('csv-parse/lib/sync'), - transform: require('stream-transform/lib/sync'), - stringify: require('csv-stringify/lib/sync') -}; - -},{"csv-generate/lib/sync":3,"csv-parse/lib/sync":6,"csv-stringify/lib/sync":8,"stream-transform/lib/sync":56}],10:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],11:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],12:[function(require,module,exports){ - -},{}],13:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":11,"buffer":13,"ieee754":25}],14:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":15,"get-intrinsic":21}],15:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":20,"get-intrinsic":21}],16:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":21}],17:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],18:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],19:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],20:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":19}],21:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":20,"has":24,"has-symbols":22}],22:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":23}],23:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],24:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":20}],25:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],26:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],27:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":14}],28:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],29:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],30:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":10,"call-bind/callBound":14,"es-abstract/helpers/getOwnPropertyDescriptor":16,"foreach":18,"has-symbols":22}],31:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],32:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":13}],33:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":17,"inherits":26,"readable-stream/lib/_stream_duplex.js":35,"readable-stream/lib/_stream_passthrough.js":36,"readable-stream/lib/_stream_readable.js":37,"readable-stream/lib/_stream_transform.js":38,"readable-stream/lib/_stream_writable.js":39,"readable-stream/lib/internal/streams/end-of-stream.js":43,"readable-stream/lib/internal/streams/pipeline.js":45}],34:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],35:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":37,"./_stream_writable":39,"_process":31,"inherits":26}],36:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":38,"inherits":26}],37:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":34,"./_stream_duplex":35,"./internal/streams/async_iterator":40,"./internal/streams/buffer_list":41,"./internal/streams/destroy":42,"./internal/streams/from":44,"./internal/streams/state":46,"./internal/streams/stream":47,"_process":31,"buffer":13,"events":17,"inherits":26,"string_decoder/":48,"util":12}],38:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":34,"./_stream_duplex":35,"inherits":26}],39:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":34,"./_stream_duplex":35,"./internal/streams/destroy":42,"./internal/streams/state":46,"./internal/streams/stream":47,"_process":31,"buffer":13,"inherits":26,"util-deprecate":50}],40:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":43,"_process":31}],41:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":13,"util":12}],42:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":31}],43:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":34}],44:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],45:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":34,"./end-of-stream":43}],46:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":34}],47:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":17}],48:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":32}],49:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":31,"timers":49}],50:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],51:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],52:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":27,"is-generator-function":29,"is-typed-array":30,"which-typed-array":54}],53:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":51,"./support/types":52,"_process":31,"inherits":26}],54:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":10,"call-bind/callBound":14,"es-abstract/helpers/getOwnPropertyDescriptor":16,"foreach":18,"has-symbols":22,"is-typed-array":30}],55:[function(require,module,exports){ -(function (setImmediate){(function (){ -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer - -// Pass all elements of an array or a stream to transform, filter and add. Features include: - -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. - -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; - -stream = require('stream'); - -util = require('util'); - -({clone} = require('mixme')); - -// ## Usage - -// Callback approach, for ease of use: - -// `transform(records, [options], handler, callback)` - -// Stream API, for maximum of power: - -// `transform([records], [options], handler, [callback])` -module.exports = function() { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = typeof argument; - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); - } - } - transform = new Transformer(options, handler); - error = false; - if (records) { - setImmediate(function() { - var k, len1, record; - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - if (error) { - break; - } - transform.write(record); - } - return transform.end(); - }); - } - if (callback || options.consume) { - result = []; - transform.on('readable', function() { - var record, results; - results = []; - while ((record = transform.read())) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - return results; - }); - transform.on('error', function(err) { - error = true; - if (callback) { - return callback(err); - } - }); - transform.on('end', function() { - if (callback && !error) { - return callback(null, result); - } - }); - } - return transform; -}; - -// ## Transformer - -// Options are documented [here](http://csv.js.org/transform/options/). -Transformer = function(options1 = {}, handler1) { - var base, base1; - this.options = options1; - this.handler = handler1; - if ((base = this.options).consume == null) { - base.consume = false; - } - this.options.objectMode = true; - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; - } - stream.Transform.call(this, this.options); - this.state = { - running: 0, - started: 0, - finished: 0 - }; - return this; -}; - -util.inherits(Transformer, stream.Transform); - -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function(chunk, encoding, cb) { - var callback, err, l; - this.state.started++; - this.state.running++; - if (this.state.running < this.options.parallel) { - cb(); - cb = null; - } - try { - l = this.handler.length; - if (this.options.params != null) { - l--; - } - if (l === 1) { // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { // async - callback = (err, ...chunks) => { - return this.__done(err, chunks, cb); - }; - this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); - } - return false; - } catch (error1) { - err = error1; - return this.__done(err); - } -}; - -Transformer.prototype._flush = function(cb) { - this._ending = function() { - if (this.state.running === 0) { - this._ending = undefined - return cb(); - } - }; - return this._ending(); -}; - -Transformer.prototype.__done = function(err, chunks, cb) { - var chunk, j, len; - this.state.running--; - if (err) { - return this.emit('error', err); - } - this.state.finished++; - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - if (typeof chunk === 'number') { - chunk = `${chunk}`; - } - if ((chunk != null) && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); - } - } - if (cb) { - cb(); - } - if (this._ending) { - return this._ending(); - } -}; - -// [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test - -}).call(this)}).call(this,require("timers").setImmediate) -},{"mixme":1,"stream":33,"timers":49,"util":53}],56:[function(require,module,exports){ - -/* -Stream Transform - sync module - -Please look at the [project documentation](https://csv.js.org/transform/) for -additional information. -*/ - -const transform = require('.') -const {clone} = require('mixme') - -module.exports = function(){ - // Import arguments normalization - let handler, callback - let options = {} - for(i in arguments){ - const argument = arguments[i] - let type = typeof argument - if(argument === null){ - type = 'null' - }else if(type === 'object' && Array.isArray(argument)){ - type = 'array' - } - if(type === 'array'){ - records = argument - }else if(type === 'object'){ - options = clone(argument) - }else if(type === 'function'){ - if(handler && i === arguments.length - 1){ - callback = argument - }else{ - handler = argument - } - }else if(type !== 'null'){ - throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`) - } - } - // Validate arguments - let expected_handler_length = 1 - if(options.params){ - expected_handler_length++ - } - if(handler.length > expected_handler_length){ - throw Error('Invalid Handler: only synchonous handlers are supported') - } - // Start transformation - const chunks = [] - const transformer = new transform.Transformer(options, handler) - transformer.push = function(chunk){ - chunks.push(chunk) - } - for(const record of records){ - transformer._transform(record, null, function(){}) - } - return chunks -} - -},{".":55,"mixme":1}]},{},[9])(9) -}); diff --git a/node_modules/csv/lib/es5/index.d.ts b/node_modules/csv/lib/es5/index.d.ts deleted file mode 100644 index c4f35a8..0000000 --- a/node_modules/csv/lib/es5/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Alias to the ES6 modules exposing the stream and callback APIs - -import * as generateImport from 'csv-generate'; -import * as parseImport from 'csv-parse'; -import * as transformImport from 'stream-transform'; -import * as stringifyImport from 'csv-stringify'; - -export var generate: typeof generateImport; -export var parse: typeof parseImport; -export var transform: typeof transformImport; -export var stringify: typeof stringifyImport; - -export as namespace csv; diff --git a/node_modules/csv/lib/es5/index.js b/node_modules/csv/lib/es5/index.js deleted file mode 100644 index b41d8b8..0000000 --- a/node_modules/csv/lib/es5/index.js +++ /dev/null @@ -1,7 +0,0 @@ -// Alias to the ES6 modules exposing the stream and callback APIs -module.exports = { - generate: require('csv-generate/lib'), - parse: require('csv-parse/lib'), - transform: require('stream-transform/lib'), - stringify: require('csv-stringify/lib') -}; \ No newline at end of file diff --git a/node_modules/csv/lib/es5/sync.d.ts b/node_modules/csv/lib/es5/sync.d.ts deleted file mode 100644 index 90f747f..0000000 --- a/node_modules/csv/lib/es5/sync.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Alias to the ES6 modules exposing the stream and callback APIs - -//import * as generate from "csv-generate/lib/sync"; -import * as parseImport from 'csv-parse/lib/sync'; -import * as transformImport from 'stream-transform/lib/sync'; -import * as stringifyImport from 'csv-stringify/lib/sync'; - -//export var generate: typeof generateImport, -export var parse: typeof parseImport; -export var transform: typeof transformImport; -export var stringify: typeof stringifyImport; - -export as namespace csv; diff --git a/node_modules/csv/lib/es5/sync.js b/node_modules/csv/lib/es5/sync.js deleted file mode 100644 index 24ee7cd..0000000 --- a/node_modules/csv/lib/es5/sync.js +++ /dev/null @@ -1,7 +0,0 @@ -// Alias to the ES6 modules exposing the sync API -module.exports = { - generate: require('csv-generate/lib/sync'), - parse: require('csv-parse/lib/sync'), - transform: require('stream-transform/lib/sync'), - stringify: require('csv-stringify/lib/sync') -}; \ No newline at end of file diff --git a/node_modules/csv/lib/index.d.ts b/node_modules/csv/lib/index.d.ts index c4f35a8..c9770f8 100644 --- a/node_modules/csv/lib/index.d.ts +++ b/node_modules/csv/lib/index.d.ts @@ -1,13 +1,14 @@ -// Alias to the ES6 modules exposing the stream and callback APIs -import * as generateImport from 'csv-generate'; -import * as parseImport from 'csv-parse'; -import * as transformImport from 'stream-transform'; -import * as stringifyImport from 'csv-stringify'; +// Alias to the modules exposing the stream and callback APIs -export var generate: typeof generateImport; -export var parse: typeof parseImport; -export var transform: typeof transformImport; -export var stringify: typeof stringifyImport; +import { generate } from 'csv-generate'; +import { parse } from 'csv-parse'; +import { transform } from 'stream-transform'; +import { stringify } from 'csv-stringify'; -export as namespace csv; +export { generate, parse, transform, stringify }; + +export * as generator from 'csv-generate'; +export * as parser from 'csv-parse'; +export * as transformer from 'stream-transform'; +export * as stringifier from 'csv-stringify'; diff --git a/node_modules/csv/lib/index.js b/node_modules/csv/lib/index.js index bcdaad2..b8e5329 100644 --- a/node_modules/csv/lib/index.js +++ b/node_modules/csv/lib/index.js @@ -1,9 +1,9 @@ -// Alias to the ES6 modules exposing the stream and callback APIs +// Alias to the modules exposing the stream and callback APIs -module.exports = { - generate: require('csv-generate/lib'), - parse: require('csv-parse/lib'), - transform: require('stream-transform/lib'), - stringify: require('csv-stringify/lib') -} +import { generate } from 'csv-generate'; +import { parse } from 'csv-parse'; +import { transform } from 'stream-transform'; +import { stringify } from 'csv-stringify'; + +export { generate, parse, stringify, transform }; diff --git a/node_modules/csv/lib/sync.d.ts b/node_modules/csv/lib/sync.d.ts index 90f747f..b181259 100644 --- a/node_modules/csv/lib/sync.d.ts +++ b/node_modules/csv/lib/sync.d.ts @@ -1,13 +1,14 @@ -// Alias to the ES6 modules exposing the stream and callback APIs -//import * as generate from "csv-generate/lib/sync"; -import * as parseImport from 'csv-parse/lib/sync'; -import * as transformImport from 'stream-transform/lib/sync'; -import * as stringifyImport from 'csv-stringify/lib/sync'; +// Alias to the modules exposing the sync APIs -//export var generate: typeof generateImport, -export var parse: typeof parseImport; -export var transform: typeof transformImport; -export var stringify: typeof stringifyImport; +import { generate } from 'csv-generate/sync' +import { parse } from 'csv-parse/sync'; +import { transform } from 'stream-transform/sync'; +import { stringify } from 'csv-stringify/sync'; -export as namespace csv; +export { generate, parse, transform, stringify } + +export * as generator from 'csv-generate/sync'; +export * as parser from 'csv-parse/sync'; +export * as transformer from 'stream-transform/sync'; +export * as stringifier from 'csv-stringify/sync'; diff --git a/node_modules/csv/lib/sync.js b/node_modules/csv/lib/sync.js index ca3d4e9..3709f75 100644 --- a/node_modules/csv/lib/sync.js +++ b/node_modules/csv/lib/sync.js @@ -1,9 +1,9 @@ -// Alias to the ES6 modules exposing the sync API +// Alias to the modules exposing the sync API -module.exports = { - generate: require('csv-generate/lib/sync'), - parse: require('csv-parse/lib/sync'), - transform: require('stream-transform/lib/sync'), - stringify: require('csv-stringify/lib/sync') -} +import { generate } from 'csv-generate/sync'; +import { parse } from 'csv-parse/sync'; +import { stringify } from 'csv-stringify/sync'; +import { transform } from 'stream-transform/sync'; + +export { generate, parse, stringify, transform }; diff --git a/node_modules/csv/package.json b/node_modules/csv/package.json index a4e5380..9e77177 100644 --- a/node_modules/csv/package.json +++ b/node_modules/csv/package.json @@ -1,6 +1,6 @@ { "name": "csv", - "version": "5.5.3", + "version": "6.3.8", "description": "A mature CSV toolset with simple api, full of options and tested against large datasets.", "keywords": [ "node", @@ -13,75 +13,126 @@ "transform", "stream", "generate", - "generation" + "generation", + "backend", + "frontend" ], - "homepage": "https://csv.js.org/", "bugs": "https://github.com/adaltas/node-csv/issues", "author": "David Worms (https://www.adaltas.com)", "contributors": [ "David Worms (https://www.adaltas.com)" ], - "license": "MIT", + "dependencies": { + "csv-generate": "^4.4.0", + "csv-parse": "^5.5.5", + "csv-stringify": "^6.4.6", + "stream-transform": "^3.3.1" + }, + "devDependencies": { + "@rollup/plugin-eslint": "^9.0.4", + "@rollup/plugin-node-resolve": "^15.2.1", + "@types/mocha": "^10.0.1", + "@types/node": "^20.5.6", + "@types/should": "^13.0.0", + "coffeescript": "~2.7.0", + "each": "^2.4.0", + "eslint": "^8.47.0", + "mocha": "~10.2.0", + "rollup": "^3.28.1", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", + "should": "~13.2.3", + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, "engines": { "node": ">= 0.1.90" }, - "main": "./lib", - "repository": { - "type": "git", - "url": "https://github.com/adaltas/node-csv.git" - }, - "coffeelintConfig": { - "indentation": { - "level": "error", - "value": 2 + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./sync": { + "import": { + "types": "./lib/sync.d.ts", + "default": "./lib/sync.js" + }, + "require": { + "types": "./dist/cjs/sync.d.cts", + "default": "./dist/cjs/sync.cjs" + } }, - "line_endings": { - "level": "error", - "value": "unix" + "./browser/esm": { + "types": "./lib/index.d.ts", + "default": "./dist/esm/index.js" }, - "max_line_length": { - "level": "ignore" + "./browser/esm/sync": { + "types": "./lib/sync.d.ts", + "default": "./dist/esm/sync.js" } }, - "dependencies": { - "csv-generate": "^3.4.3", - "csv-parse": "^4.16.3", - "csv-stringify": "^5.6.5", - "stream-transform": "^2.1.3" - }, - "devDependencies": { - "@babel/core": "^7.15.0", - "@types/mocha": "^9.0.0", - "@types/node": "^16.7.8", - "@types/should": "^13.0.0", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "coffeescript": "~2.5.1", - "mocha": "~9.1.1", - "should": "~13.2.3", - "ts-node": "^10.2.1", - "typescript": "^4.4.2" - }, + "homepage": "https://csv.js.org", + "files": [ + "dist", + "lib" + ], + "license": "MIT", + "main": "./dist/cjs/index.cjs", "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "coffeescript/register", - "ts-node/register" - ], "inline-diffs": true, - "timeout": 40000, + "loader": "./test/loaders/all.js", + "recursive": true, "reporter": "spec", - "recursive": true + "require": [ + "should" + ], + "throw-deprecation": true, + "timeout": 40000 + }, + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-csv.git", + "directory": "packages/csv" }, - "files": [ - "lib" - ], "scripts": { - "build": "browserify lib/index.js --transform babelify --standalone parse > lib/browser/index.js && browserify lib/sync.js --transform babelify --standalone parse > lib/browser/sync.js", - "preversion": "cp lib/*.ts lib/es5 && git add lib/es5/*.ts", - "test": "mocha test/**/*.{coffee,ts}" + "build": "npm run build:rollup && npm run build:ts", + "build:rollup": "npx rollup -c", + "build:ts": "cp lib/index.d.ts dist/cjs/index.d.cts && cp lib/sync.d.ts dist/cjs/sync.d.cts && cp lib/*.ts dist/esm", + "postbuild:ts": "find dist/cjs -name '*.d.cts' -exec sh -c \"sed -i \"s/\\.js'/\\.cjs'/g\" {} || sed -i '' \"s/\\.js'/\\.cjs'/g\" {}\" \\;", + "lint": "npm run lint:lib && npm run lint:samples && npm run lint:test", + "postlint": "tsc --noEmit true", + "lint:lib": "eslint --fix lib/*.js", + "lint:samples": "eslint --fix samples/*.js", + "lint:test": "coffeelint --fix test/*.coffee", + "preversion": "npm run build && git add dist", + "pretest": "npm run build", + "test": "mocha 'test/**/*.{coffee,ts}'", + "test:legacy": "mocha --ignore test/samples.coffee --loader=./test/loaders/legacy/all.js 'test/**/*.{coffee,ts}'" + }, + "type": "module", + "types": "dist/esm/index.d.ts", + "typesVersions": { + "*": { + ".": [ + "dist/esm/index.d.ts" + ], + "sync": [ + "dist/esm/sync.d.ts" + ], + "browser/esm": [ + "dist/esm/index.d.ts" + ], + "browser/esm/sync": [ + "dist/esm/sync.d.ts" + ] + } }, - "types": "./lib/index.d.ts", - "gitHead": "0fd5209b6862655c384cda052abf38019b959e70" + "gitHead": "410e7b172ce19e975825fcc95dbcfc0340f75af2" } diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE index 658c933..1a9820e 100644 --- a/node_modules/debug/LICENSE +++ b/node_modules/debug/LICENSE @@ -1,19 +1,20 @@ (The MIT License) -Copyright (c) 2014 TJ Holowaychuk +Copyright (c) 2014-2017 TJ Holowaychuk +Copyright (c) 2018-2021 Josh Junon -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, +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 +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 +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. diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md index 88dae35..e9c3e04 100644 --- a/node_modules/debug/README.md +++ b/node_modules/debug/README.md @@ -1,5 +1,5 @@ # debug -[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![Build Status](https://travis-ci.org/debug-js/debug.svg?branch=master)](https://travis-ci.org/debug-js/debug) [![Coverage Status](https://coveralls.io/repos/github/debug-js/debug/badge.svg?branch=master)](https://coveralls.io/github/debug-js/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) [![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) @@ -241,6 +241,9 @@ setInterval(function(){ }, 1200); ``` +In Chromium-based web browsers (e.g. Brave, Chrome, and Electron), the JavaScript console will—by default—only show messages logged by `debug` if the "Verbose" log level is _enabled_. + + ## Output streams @@ -351,12 +354,34 @@ if (debug.enabled) { You can also manually toggle this property to force the debug instance to be enabled or disabled. +## Usage in child processes + +Due to the way `debug` detects if the output is a TTY or not, colors are not shown in child processes when `stderr` is piped. A solution is to pass the `DEBUG_COLORS=1` environment variable to the child process. +For example: + +```javascript +worker = fork(WORKER_WRAP_PATH, [workerPath], { + stdio: [ + /* stdin: */ 0, + /* stdout: */ 'pipe', + /* stderr: */ 'pipe', + 'ipc', + ], + env: Object.assign({}, process.env, { + DEBUG_COLORS: 1 // without this settings, colors won't be shown + }), +}); + +worker.stderr.pipe(process.stderr, { end: false }); +``` + ## Authors - TJ Holowaychuk - Nathan Rajlich - Andrew Rhyne + - Josh Junon ## Backers @@ -434,6 +459,7 @@ Become a sponsor and get your logo on our README on Github with a link to your s (The MIT License) Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> +Copyright (c) 2018-2021 Josh Junon Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json index da809d2..3bcdc24 100644 --- a/node_modules/debug/package.json +++ b/node_modules/debug/package.json @@ -1,11 +1,11 @@ { "name": "debug", - "version": "4.3.1", + "version": "4.3.4", "repository": { "type": "git", - "url": "git://github.com/visionmedia/debug.git" + "url": "git://github.com/debug-js/debug.git" }, - "description": "small debugging utility", + "description": "Lightweight debugging utility for Node.js and the browser", "keywords": [ "debug", "log", @@ -16,11 +16,11 @@ "LICENSE", "README.md" ], - "author": "TJ Holowaychuk ", + "author": "Josh Junon ", "contributors": [ + "TJ Holowaychuk ", "Nathan Rajlich (http://n8.io)", - "Andrew Rhyne ", - "Josh Junon " + "Andrew Rhyne " ], "license": "MIT", "scripts": { diff --git a/node_modules/debug/src/common.js b/node_modules/debug/src/common.js index 392a8e0..e3291b2 100644 --- a/node_modules/debug/src/common.js +++ b/node_modules/debug/src/common.js @@ -34,7 +34,7 @@ function setup(env) { /** * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored + * @param {String} namespace The namespace string for the debug instance to be colored * @return {Number|String} An ANSI color code for the given namespace * @api private */ @@ -60,6 +60,8 @@ function setup(env) { function createDebug(namespace) { let prevTime; let enableOverride = null; + let namespacesCache; + let enabledCache; function debug(...args) { // Disabled? @@ -120,7 +122,17 @@ function setup(env) { Object.defineProperty(debug, 'enabled', { enumerable: true, configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, set: v => { enableOverride = v; } @@ -149,6 +161,7 @@ function setup(env) { */ function enable(namespaces) { createDebug.save(namespaces); + createDebug.namespaces = namespaces; createDebug.names = []; createDebug.skips = []; @@ -166,7 +179,7 @@ function setup(env) { namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); } else { createDebug.names.push(new RegExp('^' + namespaces + '$')); } diff --git a/node_modules/ejs/README.md b/node_modules/ejs/README.md index 0dcb676..6daf40c 100644 --- a/node_modules/ejs/README.md +++ b/node_modules/ejs/README.md @@ -1,9 +1,23 @@ Embedded JavaScript templates
-[![Build Status](https://img.shields.io/travis/mde/ejs/master.svg?style=flat)](https://travis-ci.org/mde/ejs) -[![Developing Dependencies](https://img.shields.io/david/dev/mde/ejs.svg?style=flat)](https://david-dm.org/mde/ejs?type=dev) [![Known Vulnerabilities](https://snyk.io/test/npm/ejs/badge.svg?style=flat)](https://snyk.io/test/npm/ejs) ============================= +## Security + +Security professionals, before reporting any security issues, please reference the +SECURITY.md +in this project, in particular, the following: "EJS is effectively a JavaScript runtime. +Its entire job is to execute JavaScript. If you run the EJS render method without +checking the inputs yourself, you are responsible for the results." + +In short, DO NOT submit 'vulnerabilities' that include this snippet of code: + +```javascript +app.get('/', (req, res) => { + res.render('index', req.query); +}); +``` + ## Installation ```bash @@ -63,7 +77,7 @@ You should never give end-users unfettered access to the EJS render method, If y - `cache` Compiled functions are cached, requires `filename` - `filename` The name of the file being rendered. Not required if you are using `renderFile()`. Used by `cache` to key caches, and for includes. - - `root` Set project root for includes with an absolute path (e.g, /file.ejs). + - `root` Set template root(s) for includes with an absolute path (e.g, /file.ejs). Can be array to try to resolve include from multiple directories. - `views` An array of paths to use when resolving includes with relative paths. - `context` Function execution context diff --git a/node_modules/ejs/bin/cli.js b/node_modules/ejs/bin/cli.js old mode 100755 new mode 100644 index 0feab0b..cb11aa4 --- a/node_modules/ejs/bin/cli.js +++ b/node_modules/ejs/bin/cli.js @@ -17,6 +17,7 @@ * */ +let path = require('path'); let program = require('jake').program; delete global.jake; // NO NOT WANT @@ -149,9 +150,6 @@ function run() { } } - // Default to having views relative from the current working directory - opts.views = ['.']; - // Ensure there's a template to render if (!templatePath) { throw new Error('Please provide a template path. (Run ejs -h for help)'); @@ -197,7 +195,8 @@ function run() { vals[p] = pVals[p]; } - let template = fs.readFileSync(templatePath).toString(); + opts.filename = path.resolve(process.cwd(), templatePath); + let template = fs.readFileSync(opts.filename).toString(); let output = ejs.render(template, vals, opts); if (pOpts.outputFile) { fs.writeFileSync(pOpts.outputFile, output); diff --git a/node_modules/ejs/ejs.js b/node_modules/ejs/ejs.js index 6efbd79..2cbeb57 100644 --- a/node_modules/ejs/ejs.js +++ b/node_modules/ejs/ejs.js @@ -507,8 +507,8 @@ exports.clearCache = function () { exports.cache.reset(); }; -function Template(text, opts) { - opts = opts || utils.createNullProtoObjWherePossible(); +function Template(text, optsParam) { + var opts = utils.hasOwnOnlyObject(optsParam); var options = utils.createNullProtoObjWherePossible(); this.templateText = text; /** @type {string | null} */ @@ -951,6 +951,7 @@ if (typeof window != 'undefined') { window.ejs = exports; } + },{"../package.json":6,"./utils":2,"fs":3,"path":4}],2:[function(require,module,exports){ /* * EJS Embedded JavaScript templates @@ -1053,9 +1054,25 @@ exports.escapeXML = function (markup) { : String(markup) .replace(_MATCH_HTML, encode_char); }; -exports.escapeXML.toString = function () { + +function escapeXMLToString() { return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; -}; +} + +try { + if (typeof Object.defineProperty === 'function') { + // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property + // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict + // mode, attempting that will be silently ignored. + // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. + Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString }); + } else { + // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator. + exports.escapeXML.toString = escapeXMLToString; + } +} catch (err) { + console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)'); +} /** * Naive copy of properties from one object to another. @@ -1176,6 +1193,15 @@ exports.createNullProtoObjWherePossible = (function () { }; })(); +exports.hasOwnOnlyObject = function (obj) { + var o = exports.createNullProtoObjWherePossible(); + for (var p in obj) { + if (hasOwn(obj, p)) { + o[p] = obj[p]; + } + } + return o; +}; },{}],3:[function(require,module,exports){ @@ -1681,7 +1707,7 @@ module.exports={ "engine", "ejs" ], - "version": "3.1.7", + "version": "3.1.9", "author": "Matthew Eernisse (http://fleegix.org)", "license": "Apache-2.0", "bin": { @@ -1703,16 +1729,16 @@ module.exports={ "browserify": "^16.5.1", "eslint": "^6.8.0", "git-directory-deploy": "^1.5.1", - "jsdoc": "^3.6.7", + "jsdoc": "^4.0.2", "lru-cache": "^4.0.1", - "mocha": "^7.1.1", + "mocha": "^10.2.0", "uglify-js": "^3.3.16" }, "engines": { "node": ">=0.10.0" }, "scripts": { - "test": "mocha" + "test": "npx jake test" } } diff --git a/node_modules/ejs/ejs.min.js b/node_modules/ejs/ejs.min.js index 934d530..ef65bd3 100644 --- a/node_modules/ejs/ejs.min.js +++ b/node_modules/ejs/ejs.min.js @@ -1 +1 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i1;if(options.cache){if(!filename){throw new Error("cache option requires a filename")}func=exports.cache.get(filename);if(func){return func}if(!hasTemplate){template=fileLoader(filename).toString().replace(_BOM,"")}}else if(!hasTemplate){if(!filename){throw new Error("Internal EJS error: no file name or template "+"provided")}template=fileLoader(filename).toString().replace(_BOM,"")}func=exports.compile(template,options);if(options.cache){exports.cache.set(filename,func)}return func}function tryHandleCache(options,data,cb){var result;if(!cb){if(typeof exports.promiseImpl=="function"){return new exports.promiseImpl(function(resolve,reject){try{result=handleCache(options)(data);resolve(result)}catch(err){reject(err)}})}else{throw new Error("Please provide a callback function")}}else{try{result=handleCache(options)(data)}catch(err){return cb(err)}cb(null,result)}}function fileLoader(filePath){return exports.fileLoader(filePath)}function includeFile(path,options){var opts=utils.shallowCopy(utils.createNullProtoObjWherePossible(),options);opts.filename=getIncludePath(path,opts);if(typeof options.includer==="function"){var includerResult=options.includer(path,opts.filename);if(includerResult){if(includerResult.filename){opts.filename=includerResult.filename}if(includerResult.template){return handleCache(opts,includerResult.template)}}}return handleCache(opts)}function rethrow(err,str,flnm,lineno,esc){var lines=str.split("\n");var start=Math.max(lineno-3,0);var end=Math.min(lines.length,lineno+3);var filename=esc(flnm);var context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" >> ":" ")+curr+"| "+line}).join("\n");err.path=filename;err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}function stripSemi(str){return str.replace(/;(\s*$)/,"$1")}exports.compile=function compile(template,opts){var templ;if(opts&&opts.scope){if(!scopeOptionWarned){console.warn("`scope` option is deprecated and will be removed in EJS 3");scopeOptionWarned=true}if(!opts.context){opts.context=opts.scope}delete opts.scope}templ=new Template(template,opts);return templ.compile()};exports.render=function(template,d,o){var data=d||utils.createNullProtoObjWherePossible();var opts=o||utils.createNullProtoObjWherePossible();if(arguments.length==2){utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA)}return handleCache(opts,template)(data)};exports.renderFile=function(){var args=Array.prototype.slice.call(arguments);var filename=args.shift();var cb;var opts={filename:filename};var data;var viewOpts;if(typeof arguments[arguments.length-1]=="function"){cb=args.pop()}if(args.length){data=args.shift();if(args.length){utils.shallowCopy(opts,args.pop())}else{if(data.settings){if(data.settings.views){opts.views=data.settings.views}if(data.settings["view cache"]){opts.cache=true}viewOpts=data.settings["view options"];if(viewOpts){utils.shallowCopy(opts,viewOpts)}}utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA_EXPRESS)}opts.filename=filename}else{data=utils.createNullProtoObjWherePossible()}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,opts){opts=opts||utils.createNullProtoObjWherePossible();var options=utils.createNullProtoObjWherePossible();this.templateText=text;this.mode=null;this.truncate=false;this.currentLine=1;this.source="";options.client=opts.client||false;options.escapeFunction=opts.escape||opts.escapeFunction||utils.escapeXML;options.compileDebug=opts.compileDebug!==false;options.debug=!!opts.debug;options.filename=opts.filename;options.openDelimiter=opts.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER;options.closeDelimiter=opts.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER;options.delimiter=opts.delimiter||exports.delimiter||_DEFAULT_DELIMITER;options.strict=opts.strict||false;options.context=opts.context;options.cache=opts.cache||false;options.rmWhitespace=opts.rmWhitespace;options.root=opts.root;options.includer=opts.includer;options.outputFunctionName=opts.outputFunctionName;options.localsName=opts.localsName||exports.localsName||_DEFAULT_LOCALS_NAME;options.views=opts.views;options.async=opts.async;options.destructuredLocals=opts.destructuredLocals;options.legacyInclude=typeof opts.legacyInclude!="undefined"?!!opts.legacyInclude:true;if(options.strict){options._with=false}else{options._with=typeof opts._with!="undefined"?opts._with:true}this.opts=options;this.regex=this.createRegex()}Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Template.prototype={createRegex:function(){var str=_REGEX_STRING;var delim=utils.escapeRegExpChars(this.opts.delimiter);var open=utils.escapeRegExpChars(this.opts.openDelimiter);var close=utils.escapeRegExpChars(this.opts.closeDelimiter);str=str.replace(/%/g,delim).replace(//g,close);return new RegExp(str)},compile:function(){var src;var fn;var opts=this.opts;var prepended="";var appended="";var escapeFn=opts.escapeFunction;var ctor;var sanitizedFilename=opts.filename?JSON.stringify(opts.filename):"undefined";if(!this.source){this.generateSource();prepended+=' var __output = "";\n'+" function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){if(!_JS_IDENTIFIER.test(opts.outputFunctionName)){throw new Error("outputFunctionName is not a valid JS identifier.")}prepended+=" var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.localsName&&!_JS_IDENTIFIER.test(opts.localsName)){throw new Error("localsName is not a valid JS identifier.")}if(opts.destructuredLocals&&opts.destructuredLocals.length){var destructuring=" var __locals = ("+opts.localsName+" || {}),\n";for(var i=0;i0){destructuring+=",\n "}destructuring+=name+" = __locals."+name}prepended+=destructuring+";\n"}if(opts._with!==false){prepended+=" with ("+opts.localsName+" || {}) {"+"\n";appended+=" }"+"\n"}appended+=" return __output;"+"\n";this.source=prepended+this.source+appended}if(opts.compileDebug){src="var __line = 1"+"\n"+" , __lines = "+JSON.stringify(this.templateText)+"\n"+" , __filename = "+sanitizedFilename+";"+"\n"+"try {"+"\n"+this.source+"} catch (e) {"+"\n"+" rethrow(e, __lines, __filename, __line, escapeFn);"+"\n"+"}"+"\n"}else{src=this.source}if(opts.client){src="escapeFn = escapeFn || "+escapeFn.toString()+";"+"\n"+src;if(opts.compileDebug){src="rethrow = rethrow || "+rethrow.toString()+";"+"\n"+src}}if(opts.strict){src='"use strict";\n'+src}if(opts.debug){console.log(src)}if(opts.compileDebug&&opts.filename){src=src+"\n"+"//# sourceURL="+sanitizedFilename+"\n"}try{if(opts.async){try{ctor=new Function("return (async function(){}).constructor;")()}catch(e){if(e instanceof SyntaxError){throw new Error("This environment does not support async/await")}else{throw e}}}else{ctor=Function}fn=new ctor(opts.localsName+", escapeFn, include, rethrow",src)}catch(e){if(e instanceof SyntaxError){if(opts.filename){e.message+=" in "+opts.filename}e.message+=" while compiling ejs\n\n";e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n";e.message+="https://github.com/RyanZim/EJS-Lint";if(!opts.async){e.message+="\n";e.message+="Or, if you meant to create an async function, pass `async: true` as an option."}}throw e}var returnedFn=opts.client?fn:function anonymous(data){var include=function(path,includeData){var d=utils.shallowCopy(utils.createNullProtoObjWherePossible(),data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||utils.createNullProtoObjWherePossible(),escapeFn,include,rethrow])};if(opts.filename&&typeof Object.defineProperty==="function"){var filename=opts.filename;var basename=path.basename(filename,path.extname(filename));try{Object.defineProperty(returnedFn,"name",{value:basename,writable:false,enumerable:false,configurable:true})}catch(e){}}return returnedFn},generateSource:function(){var opts=this.opts;if(opts.rmWhitespace){this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")}this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var self=this;var matches=this.parseTemplateText();var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;if(matches&&matches.length){matches.forEach(function(line,index){var closing;if(line.indexOf(o+d)===0&&line.indexOf(o+d+d)!==0){closing=matches[index+2];if(!(closing==d+c||closing=="-"+d+c||closing=="_"+d+c)){throw new Error('Could not find matching close tag for "'+line+'".')}}self.scanLine(line)})}},parseTemplateText:function(){var str=this.templateText;var pat=this.regex;var result=pat.exec(str);var arr=[];var firstPos;while(result){firstPos=result.index;if(firstPos!==0){arr.push(str.substring(0,firstPos));str=str.slice(firstPos)}arr.push(result[0]);str=str.slice(result[0].length);result=pat.exec(str)}if(str){arr.push(str)}return arr},_addOutput:function(line){if(this.truncate){line=line.replace(/^(?:\r\n|\r|\n)/,"");this.truncate=false}if(!line){return line}line=line.replace(/\\/g,"\\\\");line=line.replace(/\n/g,"\\n");line=line.replace(/\r/g,"\\r");line=line.replace(/"/g,'\\"');this.source+=' ; __append("'+line+'")'+"\n"},scanLine:function(line){var self=this;var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;var newLineCount=0;newLineCount=line.split("\n").length-1;switch(line){case o+d:case o+d+"_":this.mode=Template.modes.EVAL;break;case o+d+"=":this.mode=Template.modes.ESCAPED;break;case o+d+"-":this.mode=Template.modes.RAW;break;case o+d+"#":this.mode=Template.modes.COMMENT;break;case o+d+d:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(o+d+d,o+d)+'")'+"\n";break;case d+d+c:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(d+d+c,d+c)+'")'+"\n";break;case d+c:case"-"+d+c:case"_"+d+c:if(this.mode==Template.modes.LITERAL){this._addOutput(line)}this.mode=null;this.truncate=line.indexOf("-")===0||line.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:if(line.lastIndexOf("//")>line.lastIndexOf("\n")){line+="\n"}}switch(this.mode){case Template.modes.EVAL:this.source+=" ; "+line+"\n";break;case Template.modes.ESCAPED:this.source+=" ; __append(escapeFn("+stripSemi(line)+"))"+"\n";break;case Template.modes.RAW:this.source+=" ; __append("+stripSemi(line)+")"+"\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(line);break}}else{this._addOutput(line)}}if(self.opts.compileDebug&&newLineCount){this.currentLine+=newLineCount;this.source+=" ; __line = "+this.currentLine+"\n"}}};exports.escapeXML=utils.escapeXML;exports.__express=exports.renderFile;exports.VERSION=_VERSION_STRING;exports.name=_NAME;if(typeof window!="undefined"){window.ejs=exports}},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(require,module,exports){"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;var hasOwnProperty=Object.prototype.hasOwnProperty;var hasOwn=function(obj,key){return hasOwnProperty.apply(obj,[key])};exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&","<":"<",">":">",'"':""","'":"'"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+' "&": "&"\n'+' , "<": "<"\n'+' , ">": ">"\n'+' , \'"\': """\n'+' , "\'": "'"\n'+" }\n"+" , _MATCH_HTML = /[&<>'\"]/g;\n"+"function encode_char(c) {\n"+" return _ENCODE_HTML_RULES[c] || c;\n"+"};\n";exports.escapeXML=function(markup){return markup==undefined?"":String(markup).replace(_MATCH_HTML,encode_char)};exports.escapeXML.toString=function(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr};exports.shallowCopy=function(to,from){from=from||{};if(to!==null&&to!==undefined){for(var p in from){if(!hasOwn(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}return to};exports.shallowCopyFromList=function(to,from,list){list=list||[];from=from||{};if(to!==null&&to!==undefined){for(var i=0;i=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){return"/"}return path.slice(0,end)};function basename(path){if(typeof path!=="string")path=path+"";var start=0;var end=-1;var matchedSlash=true;var i;for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}exports.basename=function(path,ext){var f=basename(path);if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){if(typeof path!=="string")path=path+"";var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i1){for(var i=1;i (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^3.6.7","lru-cache":"^4.0.1",mocha:"^7.1.1","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"mocha"}}},{}]},{},[1])(1)}); +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.ejs=f()}})(function(){var define,module,exports;return function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i1;if(options.cache){if(!filename){throw new Error("cache option requires a filename")}func=exports.cache.get(filename);if(func){return func}if(!hasTemplate){template=fileLoader(filename).toString().replace(_BOM,"")}}else if(!hasTemplate){if(!filename){throw new Error("Internal EJS error: no file name or template "+"provided")}template=fileLoader(filename).toString().replace(_BOM,"")}func=exports.compile(template,options);if(options.cache){exports.cache.set(filename,func)}return func}function tryHandleCache(options,data,cb){var result;if(!cb){if(typeof exports.promiseImpl=="function"){return new exports.promiseImpl(function(resolve,reject){try{result=handleCache(options)(data);resolve(result)}catch(err){reject(err)}})}else{throw new Error("Please provide a callback function")}}else{try{result=handleCache(options)(data)}catch(err){return cb(err)}cb(null,result)}}function fileLoader(filePath){return exports.fileLoader(filePath)}function includeFile(path,options){var opts=utils.shallowCopy(utils.createNullProtoObjWherePossible(),options);opts.filename=getIncludePath(path,opts);if(typeof options.includer==="function"){var includerResult=options.includer(path,opts.filename);if(includerResult){if(includerResult.filename){opts.filename=includerResult.filename}if(includerResult.template){return handleCache(opts,includerResult.template)}}}return handleCache(opts)}function rethrow(err,str,flnm,lineno,esc){var lines=str.split("\n");var start=Math.max(lineno-3,0);var end=Math.min(lines.length,lineno+3);var filename=esc(flnm);var context=lines.slice(start,end).map(function(line,i){var curr=i+start+1;return(curr==lineno?" >> ":" ")+curr+"| "+line}).join("\n");err.path=filename;err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}function stripSemi(str){return str.replace(/;(\s*$)/,"$1")}exports.compile=function compile(template,opts){var templ;if(opts&&opts.scope){if(!scopeOptionWarned){console.warn("`scope` option is deprecated and will be removed in EJS 3");scopeOptionWarned=true}if(!opts.context){opts.context=opts.scope}delete opts.scope}templ=new Template(template,opts);return templ.compile()};exports.render=function(template,d,o){var data=d||utils.createNullProtoObjWherePossible();var opts=o||utils.createNullProtoObjWherePossible();if(arguments.length==2){utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA)}return handleCache(opts,template)(data)};exports.renderFile=function(){var args=Array.prototype.slice.call(arguments);var filename=args.shift();var cb;var opts={filename:filename};var data;var viewOpts;if(typeof arguments[arguments.length-1]=="function"){cb=args.pop()}if(args.length){data=args.shift();if(args.length){utils.shallowCopy(opts,args.pop())}else{if(data.settings){if(data.settings.views){opts.views=data.settings.views}if(data.settings["view cache"]){opts.cache=true}viewOpts=data.settings["view options"];if(viewOpts){utils.shallowCopy(opts,viewOpts)}}utils.shallowCopyFromList(opts,data,_OPTS_PASSABLE_WITH_DATA_EXPRESS)}opts.filename=filename}else{data=utils.createNullProtoObjWherePossible()}return tryHandleCache(opts,data,cb)};exports.Template=Template;exports.clearCache=function(){exports.cache.reset()};function Template(text,optsParam){var opts=utils.hasOwnOnlyObject(optsParam);var options=utils.createNullProtoObjWherePossible();this.templateText=text;this.mode=null;this.truncate=false;this.currentLine=1;this.source="";options.client=opts.client||false;options.escapeFunction=opts.escape||opts.escapeFunction||utils.escapeXML;options.compileDebug=opts.compileDebug!==false;options.debug=!!opts.debug;options.filename=opts.filename;options.openDelimiter=opts.openDelimiter||exports.openDelimiter||_DEFAULT_OPEN_DELIMITER;options.closeDelimiter=opts.closeDelimiter||exports.closeDelimiter||_DEFAULT_CLOSE_DELIMITER;options.delimiter=opts.delimiter||exports.delimiter||_DEFAULT_DELIMITER;options.strict=opts.strict||false;options.context=opts.context;options.cache=opts.cache||false;options.rmWhitespace=opts.rmWhitespace;options.root=opts.root;options.includer=opts.includer;options.outputFunctionName=opts.outputFunctionName;options.localsName=opts.localsName||exports.localsName||_DEFAULT_LOCALS_NAME;options.views=opts.views;options.async=opts.async;options.destructuredLocals=opts.destructuredLocals;options.legacyInclude=typeof opts.legacyInclude!="undefined"?!!opts.legacyInclude:true;if(options.strict){options._with=false}else{options._with=typeof opts._with!="undefined"?opts._with:true}this.opts=options;this.regex=this.createRegex()}Template.modes={EVAL:"eval",ESCAPED:"escaped",RAW:"raw",COMMENT:"comment",LITERAL:"literal"};Template.prototype={createRegex:function(){var str=_REGEX_STRING;var delim=utils.escapeRegExpChars(this.opts.delimiter);var open=utils.escapeRegExpChars(this.opts.openDelimiter);var close=utils.escapeRegExpChars(this.opts.closeDelimiter);str=str.replace(/%/g,delim).replace(//g,close);return new RegExp(str)},compile:function(){var src;var fn;var opts=this.opts;var prepended="";var appended="";var escapeFn=opts.escapeFunction;var ctor;var sanitizedFilename=opts.filename?JSON.stringify(opts.filename):"undefined";if(!this.source){this.generateSource();prepended+=' var __output = "";\n'+" function __append(s) { if (s !== undefined && s !== null) __output += s }\n";if(opts.outputFunctionName){if(!_JS_IDENTIFIER.test(opts.outputFunctionName)){throw new Error("outputFunctionName is not a valid JS identifier.")}prepended+=" var "+opts.outputFunctionName+" = __append;"+"\n"}if(opts.localsName&&!_JS_IDENTIFIER.test(opts.localsName)){throw new Error("localsName is not a valid JS identifier.")}if(opts.destructuredLocals&&opts.destructuredLocals.length){var destructuring=" var __locals = ("+opts.localsName+" || {}),\n";for(var i=0;i0){destructuring+=",\n "}destructuring+=name+" = __locals."+name}prepended+=destructuring+";\n"}if(opts._with!==false){prepended+=" with ("+opts.localsName+" || {}) {"+"\n";appended+=" }"+"\n"}appended+=" return __output;"+"\n";this.source=prepended+this.source+appended}if(opts.compileDebug){src="var __line = 1"+"\n"+" , __lines = "+JSON.stringify(this.templateText)+"\n"+" , __filename = "+sanitizedFilename+";"+"\n"+"try {"+"\n"+this.source+"} catch (e) {"+"\n"+" rethrow(e, __lines, __filename, __line, escapeFn);"+"\n"+"}"+"\n"}else{src=this.source}if(opts.client){src="escapeFn = escapeFn || "+escapeFn.toString()+";"+"\n"+src;if(opts.compileDebug){src="rethrow = rethrow || "+rethrow.toString()+";"+"\n"+src}}if(opts.strict){src='"use strict";\n'+src}if(opts.debug){console.log(src)}if(opts.compileDebug&&opts.filename){src=src+"\n"+"//# sourceURL="+sanitizedFilename+"\n"}try{if(opts.async){try{ctor=new Function("return (async function(){}).constructor;")()}catch(e){if(e instanceof SyntaxError){throw new Error("This environment does not support async/await")}else{throw e}}}else{ctor=Function}fn=new ctor(opts.localsName+", escapeFn, include, rethrow",src)}catch(e){if(e instanceof SyntaxError){if(opts.filename){e.message+=" in "+opts.filename}e.message+=" while compiling ejs\n\n";e.message+="If the above error is not helpful, you may want to try EJS-Lint:\n";e.message+="https://github.com/RyanZim/EJS-Lint";if(!opts.async){e.message+="\n";e.message+="Or, if you meant to create an async function, pass `async: true` as an option."}}throw e}var returnedFn=opts.client?fn:function anonymous(data){var include=function(path,includeData){var d=utils.shallowCopy(utils.createNullProtoObjWherePossible(),data);if(includeData){d=utils.shallowCopy(d,includeData)}return includeFile(path,opts)(d)};return fn.apply(opts.context,[data||utils.createNullProtoObjWherePossible(),escapeFn,include,rethrow])};if(opts.filename&&typeof Object.defineProperty==="function"){var filename=opts.filename;var basename=path.basename(filename,path.extname(filename));try{Object.defineProperty(returnedFn,"name",{value:basename,writable:false,enumerable:false,configurable:true})}catch(e){}}return returnedFn},generateSource:function(){var opts=this.opts;if(opts.rmWhitespace){this.templateText=this.templateText.replace(/[\r\n]+/g,"\n").replace(/^\s+|\s+$/gm,"")}this.templateText=this.templateText.replace(/[ \t]*<%_/gm,"<%_").replace(/_%>[ \t]*/gm,"_%>");var self=this;var matches=this.parseTemplateText();var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;if(matches&&matches.length){matches.forEach(function(line,index){var closing;if(line.indexOf(o+d)===0&&line.indexOf(o+d+d)!==0){closing=matches[index+2];if(!(closing==d+c||closing=="-"+d+c||closing=="_"+d+c)){throw new Error('Could not find matching close tag for "'+line+'".')}}self.scanLine(line)})}},parseTemplateText:function(){var str=this.templateText;var pat=this.regex;var result=pat.exec(str);var arr=[];var firstPos;while(result){firstPos=result.index;if(firstPos!==0){arr.push(str.substring(0,firstPos));str=str.slice(firstPos)}arr.push(result[0]);str=str.slice(result[0].length);result=pat.exec(str)}if(str){arr.push(str)}return arr},_addOutput:function(line){if(this.truncate){line=line.replace(/^(?:\r\n|\r|\n)/,"");this.truncate=false}if(!line){return line}line=line.replace(/\\/g,"\\\\");line=line.replace(/\n/g,"\\n");line=line.replace(/\r/g,"\\r");line=line.replace(/"/g,'\\"');this.source+=' ; __append("'+line+'")'+"\n"},scanLine:function(line){var self=this;var d=this.opts.delimiter;var o=this.opts.openDelimiter;var c=this.opts.closeDelimiter;var newLineCount=0;newLineCount=line.split("\n").length-1;switch(line){case o+d:case o+d+"_":this.mode=Template.modes.EVAL;break;case o+d+"=":this.mode=Template.modes.ESCAPED;break;case o+d+"-":this.mode=Template.modes.RAW;break;case o+d+"#":this.mode=Template.modes.COMMENT;break;case o+d+d:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(o+d+d,o+d)+'")'+"\n";break;case d+d+c:this.mode=Template.modes.LITERAL;this.source+=' ; __append("'+line.replace(d+d+c,d+c)+'")'+"\n";break;case d+c:case"-"+d+c:case"_"+d+c:if(this.mode==Template.modes.LITERAL){this._addOutput(line)}this.mode=null;this.truncate=line.indexOf("-")===0||line.indexOf("_")===0;break;default:if(this.mode){switch(this.mode){case Template.modes.EVAL:case Template.modes.ESCAPED:case Template.modes.RAW:if(line.lastIndexOf("//")>line.lastIndexOf("\n")){line+="\n"}}switch(this.mode){case Template.modes.EVAL:this.source+=" ; "+line+"\n";break;case Template.modes.ESCAPED:this.source+=" ; __append(escapeFn("+stripSemi(line)+"))"+"\n";break;case Template.modes.RAW:this.source+=" ; __append("+stripSemi(line)+")"+"\n";break;case Template.modes.COMMENT:break;case Template.modes.LITERAL:this._addOutput(line);break}}else{this._addOutput(line)}}if(self.opts.compileDebug&&newLineCount){this.currentLine+=newLineCount;this.source+=" ; __line = "+this.currentLine+"\n"}}};exports.escapeXML=utils.escapeXML;exports.__express=exports.renderFile;exports.VERSION=_VERSION_STRING;exports.name=_NAME;if(typeof window!="undefined"){window.ejs=exports}},{"../package.json":6,"./utils":2,fs:3,path:4}],2:[function(require,module,exports){"use strict";var regExpChars=/[|\\{}()[\]^$+*?.]/g;var hasOwnProperty=Object.prototype.hasOwnProperty;var hasOwn=function(obj,key){return hasOwnProperty.apply(obj,[key])};exports.escapeRegExpChars=function(string){if(!string){return""}return String(string).replace(regExpChars,"\\$&")};var _ENCODE_HTML_RULES={"&":"&","<":"<",">":">",'"':""","'":"'"};var _MATCH_HTML=/[&<>'"]/g;function encode_char(c){return _ENCODE_HTML_RULES[c]||c}var escapeFuncStr="var _ENCODE_HTML_RULES = {\n"+' "&": "&"\n'+' , "<": "<"\n'+' , ">": ">"\n'+' , \'"\': """\n'+' , "\'": "'"\n'+" }\n"+" , _MATCH_HTML = /[&<>'\"]/g;\n"+"function encode_char(c) {\n"+" return _ENCODE_HTML_RULES[c] || c;\n"+"};\n";exports.escapeXML=function(markup){return markup==undefined?"":String(markup).replace(_MATCH_HTML,encode_char)};function escapeXMLToString(){return Function.prototype.toString.call(this)+";\n"+escapeFuncStr}try{if(typeof Object.defineProperty==="function"){Object.defineProperty(exports.escapeXML,"toString",{value:escapeXMLToString})}else{exports.escapeXML.toString=escapeXMLToString}}catch(err){console.warn("Unable to set escapeXML.toString (is the Function prototype frozen?)")}exports.shallowCopy=function(to,from){from=from||{};if(to!==null&&to!==undefined){for(var p in from){if(!hasOwn(from,p)){continue}if(p==="__proto__"||p==="constructor"){continue}to[p]=from[p]}}return to};exports.shallowCopyFromList=function(to,from,list){list=list||[];from=from||{};if(to!==null&&to!==undefined){for(var i=0;i=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i=1;--i){code=path.charCodeAt(i);if(code===47){if(!matchedSlash){end=i;break}}else{matchedSlash=false}}if(end===-1)return hasRoot?"/":".";if(hasRoot&&end===1){return"/"}return path.slice(0,end)};function basename(path){if(typeof path!=="string")path=path+"";var start=0;var end=-1;var matchedSlash=true;var i;for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47){if(!matchedSlash){start=i+1;break}}else if(end===-1){matchedSlash=false;end=i+1}}if(end===-1)return"";return path.slice(start,end)}exports.basename=function(path,ext){var f=basename(path);if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){if(typeof path!=="string")path=path+"";var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47){if(!matchedSlash){startPart=i+1;break}continue}if(end===-1){matchedSlash=false;end=i+1}if(code===46){if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1}else if(startDot!==-1){preDotState=-1}}if(startDot===-1||end===-1||preDotState===0||preDotState===1&&startDot===end-1&&startDot===startPart+1){return""}return path.slice(startDot,end)};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i1){for(var i=1;i (http://fleegix.org)",license:"Apache-2.0",bin:{ejs:"./bin/cli.js"},main:"./lib/ejs.js",jsdelivr:"ejs.min.js",unpkg:"ejs.min.js",repository:{type:"git",url:"git://github.com/mde/ejs.git"},bugs:"https://github.com/mde/ejs/issues",homepage:"https://github.com/mde/ejs",dependencies:{jake:"^10.8.5"},devDependencies:{browserify:"^16.5.1",eslint:"^6.8.0","git-directory-deploy":"^1.5.1",jsdoc:"^4.0.2","lru-cache":"^4.0.1",mocha:"^10.2.0","uglify-js":"^3.3.16"},engines:{node:">=0.10.0"},scripts:{test:"npx jake test"}}},{}]},{},[1])(1)}); diff --git a/node_modules/ejs/jakefile.js b/node_modules/ejs/jakefile.js index 7f60105..0d6b6ab 100644 --- a/node_modules/ejs/jakefile.js +++ b/node_modules/ejs/jakefile.js @@ -64,7 +64,7 @@ task('docPublish', ['doc'], function () { desc('Runs the EJS test suite'); task('test', ['lint'], function () { - exec(path.join('./node_modules/.bin/mocha')); + exec(path.join('./node_modules/.bin/mocha --u tdd')); }); publishTask('ejs', ['build'], function () { diff --git a/node_modules/ejs/lib/ejs.js b/node_modules/ejs/lib/ejs.js old mode 100755 new mode 100644 index 65590ea..1153b53 --- a/node_modules/ejs/lib/ejs.js +++ b/node_modules/ejs/lib/ejs.js @@ -506,8 +506,8 @@ exports.clearCache = function () { exports.cache.reset(); }; -function Template(text, opts) { - opts = opts || utils.createNullProtoObjWherePossible(); +function Template(text, optsParam) { + var opts = utils.hasOwnOnlyObject(optsParam); var options = utils.createNullProtoObjWherePossible(); this.templateText = text; /** @type {string | null} */ @@ -949,3 +949,4 @@ exports.name = _NAME; if (typeof window != 'undefined') { window.ejs = exports; } + diff --git a/node_modules/ejs/lib/utils.js b/node_modules/ejs/lib/utils.js index 6859abf..396edb3 100644 --- a/node_modules/ejs/lib/utils.js +++ b/node_modules/ejs/lib/utils.js @@ -99,9 +99,25 @@ exports.escapeXML = function (markup) { : String(markup) .replace(_MATCH_HTML, encode_char); }; -exports.escapeXML.toString = function () { + +function escapeXMLToString() { return Function.prototype.toString.call(this) + ';\n' + escapeFuncStr; -}; +} + +try { + if (typeof Object.defineProperty === 'function') { + // If the Function prototype is frozen, the "toString" property is non-writable. This means that any objects which inherit this property + // cannot have the property changed using an assignment. If using strict mode, attempting that will cause an error. If not using strict + // mode, attempting that will be silently ignored. + // However, we can still explicitly shadow the prototype's "toString" property by defining a new "toString" property on this object. + Object.defineProperty(exports.escapeXML, 'toString', { value: escapeXMLToString }); + } else { + // If Object.defineProperty() doesn't exist, attempt to shadow this property using the assignment operator. + exports.escapeXML.toString = escapeXMLToString; + } +} catch (err) { + console.warn('Unable to set escapeXML.toString (is the Function prototype frozen?)'); +} /** * Naive copy of properties from one object to another. @@ -222,4 +238,13 @@ exports.createNullProtoObjWherePossible = (function () { }; })(); +exports.hasOwnOnlyObject = function (obj) { + var o = exports.createNullProtoObjWherePossible(); + for (var p in obj) { + if (hasOwn(obj, p)) { + o[p] = obj[p]; + } + } + return o; +}; diff --git a/node_modules/ejs/package.json b/node_modules/ejs/package.json index afc766f..a229989 100644 --- a/node_modules/ejs/package.json +++ b/node_modules/ejs/package.json @@ -6,7 +6,7 @@ "engine", "ejs" ], - "version": "3.1.8", + "version": "3.1.10", "author": "Matthew Eernisse (http://fleegix.org)", "license": "Apache-2.0", "bin": { @@ -28,15 +28,15 @@ "browserify": "^16.5.1", "eslint": "^6.8.0", "git-directory-deploy": "^1.5.1", - "jsdoc": "^3.6.7", + "jsdoc": "^4.0.2", "lru-cache": "^4.0.1", - "mocha": "^7.1.1", + "mocha": "^10.2.0", "uglify-js": "^3.3.16" }, "engines": { "node": ">=0.10.0" }, "scripts": { - "test": "mocha" + "test": "npx jake test" } } diff --git a/node_modules/entities/lib/decode.d.ts b/node_modules/entities/lib/decode.d.ts index 4d3df42..ccfd9fb 100644 --- a/node_modules/entities/lib/decode.d.ts +++ b/node_modules/entities/lib/decode.d.ts @@ -1,5 +1,211 @@ -export declare const decodeXML: (str: string) => string; -export declare const decodeHTMLStrict: (str: string) => string; -export declare type MapType = Record; -export declare const decodeHTML: (str: string) => string; +import htmlDecodeTree from "./generated/decode-data-html.js"; +import xmlDecodeTree from "./generated/decode-data-xml.js"; +import decodeCodePoint from "./decode_codepoint.js"; +export { htmlDecodeTree, xmlDecodeTree, decodeCodePoint }; +export { replaceCodePoint, fromCodePoint } from "./decode_codepoint.js"; +export declare enum BinTrieFlags { + VALUE_LENGTH = 49152, + BRANCH_LENGTH = 16256, + JUMP_TABLE = 127 +} +export declare enum DecodingMode { + /** Entities in text nodes that can end with any character. */ + Legacy = 0, + /** Only allow entities terminated with a semicolon. */ + Strict = 1, + /** Entities in attributes have limitations on ending characters. */ + Attribute = 2 +} +/** + * Producers for character reference errors as defined in the HTML spec. + */ +export interface EntityErrorProducer { + missingSemicolonAfterCharacterReference(): void; + absenceOfDigitsInNumericCharacterReference(consumedCharacters: number): void; + validateNumericCharacterReference(code: number): void; +} +/** + * Token decoder with support of writing partial entities. + */ +export declare class EntityDecoder { + /** The tree used to decode entities. */ + private readonly decodeTree; + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + private readonly emitCodePoint; + /** An object that is used to produce errors. */ + private readonly errors?; + constructor( + /** The tree used to decode entities. */ + decodeTree: Uint16Array, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint: (cp: number, consumed: number) => void, + /** An object that is used to produce errors. */ + errors?: EntityErrorProducer | undefined); + /** The current state of the decoder. */ + private state; + /** Characters that were consumed while parsing an entity. */ + private consumed; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + private result; + /** The current index in the decode tree. */ + private treeIndex; + /** The number of characters that were consumed in excess. */ + private excess; + /** The mode in which the decoder is operating. */ + private decodeMode; + /** Resets the instance to make it reusable. */ + startEntity(decodeMode: DecodingMode): void; + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + write(str: string, offset: number): number; + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericStart; + private addToNumericResult; + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericHex; + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericDecimal; + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + private emitNumericEntity; + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNamedEntity; + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + private emitNotTerminatedNamedEntity; + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + private emitNamedEntityData; + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + end(): number; +} +/** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ +export declare function determineBranch(decodeTree: Uint16Array, current: number, nodeIdx: number, char: number): number; +/** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ +export declare function decodeHTML(str: string, mode?: DecodingMode): string; +/** + * Decodes an HTML string in an attribute. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeHTMLAttribute(str: string): string; +/** + * Decodes an HTML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeHTMLStrict(str: string): string; +/** + * Decodes an XML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeXML(str: string): string; //# sourceMappingURL=decode.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/decode.d.ts.map b/node_modules/entities/lib/decode.d.ts.map index ebcf133..4c0b4b4 100644 --- a/node_modules/entities/lib/decode.d.ts.map +++ b/node_modules/entities/lib/decode.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"decode.d.ts","sourceRoot":"","sources":["../src/decode.ts"],"names":[],"mappings":"AAOA,eAAO,MAAM,SAAS,QAOL,MAAM,WAP0B,CAAC;AAClD,eAAO,MAAM,gBAAgB,QAMZ,MAAM,WANoC,CAAC;AAE5D,oBAAY,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAS7C,eAAO,MAAM,UAAU,QAyBN,MAAM,WACnB,CAAC"} \ No newline at end of file +{"version":3,"file":"decode.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAC3D,OAAO,eAGN,MAAM,uBAAuB,CAAC;AAG/B,OAA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G,IAAI;IAS3C;;;;;;;;;;OAUG;IACH,KAAK,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM;IA8B1C;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,kBAAkB;IAe1B;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAkBvB;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB;IAkB3B;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,iBAAiB;IA6BzB;;;;;;;;OAQG;IACH,OAAO,CAAC,gBAAgB;IAsDxB;;;;OAIG;IACH,OAAO,CAAC,4BAA4B;IAYpC;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB;IAqB3B;;;;;;OAMG;IACH,GAAG,IAAI,MAAM;CA6BhB;AAoDD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC3B,UAAU,EAAE,WAAW,EACvB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,GACb,MAAM,CAsCR;AAKD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,eAAsB,GAAG,MAAM,CAE1E;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE7C"} \ No newline at end of file diff --git a/node_modules/entities/lib/decode.js b/node_modules/entities/lib/decode.js index 5f9c1f2..aa4a42c 100644 --- a/node_modules/entities/lib/decode.js +++ b/node_modules/entities/lib/decode.js @@ -1,53 +1,536 @@ "use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeHTML = exports.decodeHTMLStrict = exports.decodeXML = void 0; -var entities_json_1 = __importDefault(require("./maps/entities.json")); -var legacy_json_1 = __importDefault(require("./maps/legacy.json")); -var xml_json_1 = __importDefault(require("./maps/xml.json")); -var decode_codepoint_1 = __importDefault(require("./decode_codepoint")); -var strictEntityRe = /&(?:[a-zA-Z0-9]+|#[xX][\da-fA-F]+|#\d+);/g; -exports.decodeXML = getStrictDecoder(xml_json_1.default); -exports.decodeHTMLStrict = getStrictDecoder(entities_json_1.default); -function getStrictDecoder(map) { - var replace = getReplacer(map); - return function (str) { return String(str).replace(strictEntityRe, replace); }; -} -var sorter = function (a, b) { return (a < b ? 1 : -1); }; -exports.decodeHTML = (function () { - var legacy = Object.keys(legacy_json_1.default).sort(sorter); - var keys = Object.keys(entities_json_1.default).sort(sorter); - for (var i = 0, j = 0; i < keys.length; i++) { - if (legacy[j] === keys[i]) { - keys[i] += ";?"; - j++; +exports.decodeXML = exports.decodeHTMLStrict = exports.decodeHTMLAttribute = exports.decodeHTML = exports.determineBranch = exports.EntityDecoder = exports.DecodingMode = exports.BinTrieFlags = exports.fromCodePoint = exports.replaceCodePoint = exports.decodeCodePoint = exports.xmlDecodeTree = exports.htmlDecodeTree = void 0; +var decode_data_html_js_1 = __importDefault(require("./generated/decode-data-html.js")); +exports.htmlDecodeTree = decode_data_html_js_1.default; +var decode_data_xml_js_1 = __importDefault(require("./generated/decode-data-xml.js")); +exports.xmlDecodeTree = decode_data_xml_js_1.default; +var decode_codepoint_js_1 = __importStar(require("./decode_codepoint.js")); +exports.decodeCodePoint = decode_codepoint_js_1.default; +var decode_codepoint_js_2 = require("./decode_codepoint.js"); +Object.defineProperty(exports, "replaceCodePoint", { enumerable: true, get: function () { return decode_codepoint_js_2.replaceCodePoint; } }); +Object.defineProperty(exports, "fromCodePoint", { enumerable: true, get: function () { return decode_codepoint_js_2.fromCodePoint; } }); +var CharCodes; +(function (CharCodes) { + CharCodes[CharCodes["NUM"] = 35] = "NUM"; + CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; + CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; + CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; + CharCodes[CharCodes["NINE"] = 57] = "NINE"; + CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; + CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; + CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; + CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; + CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; + CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; + CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; +})(CharCodes || (CharCodes = {})); +/** Bit that needs to be set to convert an upper case ASCII character to lower case */ +var TO_LOWER_BIT = 32; +var BinTrieFlags; +(function (BinTrieFlags) { + BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; + BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; + BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; +})(BinTrieFlags = exports.BinTrieFlags || (exports.BinTrieFlags = {})); +function isNumber(code) { + return code >= CharCodes.ZERO && code <= CharCodes.NINE; +} +function isHexadecimalCharacter(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F)); +} +function isAsciiAlphaNumeric(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || + isNumber(code)); +} +/** + * Checks if the given character is a valid end character for an entity in an attribute. + * + * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. + * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state + */ +function isEntityInAttributeInvalidEnd(code) { + return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); +} +var EntityDecoderState; +(function (EntityDecoderState) { + EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; + EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; + EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; + EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; + EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; +})(EntityDecoderState || (EntityDecoderState = {})); +var DecodingMode; +(function (DecodingMode) { + /** Entities in text nodes that can end with any character. */ + DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; + /** Only allow entities terminated with a semicolon. */ + DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; + /** Entities in attributes have limitations on ending characters. */ + DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; +})(DecodingMode = exports.DecodingMode || (exports.DecodingMode = {})); +/** + * Token decoder with support of writing partial entities. + */ +var EntityDecoder = /** @class */ (function () { + function EntityDecoder( + /** The tree used to decode entities. */ + decodeTree, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint, + /** An object that is used to produce errors. */ + errors) { + this.decodeTree = decodeTree; + this.emitCodePoint = emitCodePoint; + this.errors = errors; + /** The current state of the decoder. */ + this.state = EntityDecoderState.EntityStart; + /** Characters that were consumed while parsing an entity. */ + this.consumed = 1; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + this.result = 0; + /** The current index in the decode tree. */ + this.treeIndex = 0; + /** The number of characters that were consumed in excess. */ + this.excess = 1; + /** The mode in which the decoder is operating. */ + this.decodeMode = DecodingMode.Strict; + } + /** Resets the instance to make it reusable. */ + EntityDecoder.prototype.startEntity = function (decodeMode) { + this.decodeMode = decodeMode; + this.state = EntityDecoderState.EntityStart; + this.result = 0; + this.treeIndex = 0; + this.excess = 1; + this.consumed = 1; + }; + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.write = function (str, offset) { + switch (this.state) { + case EntityDecoderState.EntityStart: { + if (str.charCodeAt(offset) === CharCodes.NUM) { + this.state = EntityDecoderState.NumericStart; + this.consumed += 1; + return this.stateNumericStart(str, offset + 1); + } + this.state = EntityDecoderState.NamedEntity; + return this.stateNamedEntity(str, offset); + } + case EntityDecoderState.NumericStart: { + return this.stateNumericStart(str, offset); + } + case EntityDecoderState.NumericDecimal: { + return this.stateNumericDecimal(str, offset); + } + case EntityDecoderState.NumericHex: { + return this.stateNumericHex(str, offset); + } + case EntityDecoderState.NamedEntity: { + return this.stateNamedEntity(str, offset); + } } - else { - keys[i] += ";"; + }; + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericStart = function (str, offset) { + if (offset >= str.length) { + return -1; } - } - var re = new RegExp("&(?:" + keys.join("|") + "|#[xX][\\da-fA-F]+;?|#\\d+;?)", "g"); - var replace = getReplacer(entities_json_1.default); - function replacer(str) { - if (str.substr(-1) !== ";") - str += ";"; - return replace(str); - } - // TODO consider creating a merged map - return function (str) { return String(str).replace(re, replacer); }; -})(); -function getReplacer(map) { - return function replace(str) { - if (str.charAt(1) === "#") { - var secondChar = str.charAt(2); - if (secondChar === "X" || secondChar === "x") { - return decode_codepoint_1.default(parseInt(str.substr(3), 16)); + if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { + this.state = EntityDecoderState.NumericHex; + this.consumed += 1; + return this.stateNumericHex(str, offset + 1); + } + this.state = EntityDecoderState.NumericDecimal; + return this.stateNumericDecimal(str, offset); + }; + EntityDecoder.prototype.addToNumericResult = function (str, start, end, base) { + if (start !== end) { + var digitCount = end - start; + this.result = + this.result * Math.pow(base, digitCount) + + parseInt(str.substr(start, digitCount), base); + this.consumed += digitCount; + } + }; + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericHex = function (str, offset) { + var startIdx = offset; + while (offset < str.length) { + var char = str.charCodeAt(offset); + if (isNumber(char) || isHexadecimalCharacter(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 16); + return this.emitNumericEntity(char, 3); } - return decode_codepoint_1.default(parseInt(str.substr(2), 10)); } - // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing - return map[str.slice(1, -1)] || str; + this.addToNumericResult(str, startIdx, offset, 16); + return -1; }; + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNumericDecimal = function (str, offset) { + var startIdx = offset; + while (offset < str.length) { + var char = str.charCodeAt(offset); + if (isNumber(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 10); + return this.emitNumericEntity(char, 2); + } + } + this.addToNumericResult(str, startIdx, offset, 10); + return -1; + }; + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + EntityDecoder.prototype.emitNumericEntity = function (lastCp, expectedLength) { + var _a; + // Ensure we consumed at least one digit. + if (this.consumed <= expectedLength) { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + // Figure out if this is a legit end of the entity + if (lastCp === CharCodes.SEMI) { + this.consumed += 1; + } + else if (this.decodeMode === DecodingMode.Strict) { + return 0; + } + this.emitCodePoint((0, decode_codepoint_js_1.replaceCodePoint)(this.result), this.consumed); + if (this.errors) { + if (lastCp !== CharCodes.SEMI) { + this.errors.missingSemicolonAfterCharacterReference(); + } + this.errors.validateNumericCharacterReference(this.result); + } + return this.consumed; + }; + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + EntityDecoder.prototype.stateNamedEntity = function (str, offset) { + var decodeTree = this.decodeTree; + var current = decodeTree[this.treeIndex]; + // The mask is the number of bytes of the value, including the current byte. + var valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + for (; offset < str.length; offset++, this.excess++) { + var char = str.charCodeAt(offset); + this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); + if (this.treeIndex < 0) { + return this.result === 0 || + // If we are parsing an attribute + (this.decodeMode === DecodingMode.Attribute && + // We shouldn't have consumed any characters after the entity, + (valueLength === 0 || + // And there should be no invalid characters. + isEntityInAttributeInvalidEnd(char))) + ? 0 + : this.emitNotTerminatedNamedEntity(); + } + current = decodeTree[this.treeIndex]; + valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + // If the branch is a value, store it and continue + if (valueLength !== 0) { + // If the entity is terminated by a semicolon, we are done. + if (char === CharCodes.SEMI) { + return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); + } + // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. + if (this.decodeMode !== DecodingMode.Strict) { + this.result = this.treeIndex; + this.consumed += this.excess; + this.excess = 0; + } + } + } + return -1; + }; + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.emitNotTerminatedNamedEntity = function () { + var _a; + var _b = this, result = _b.result, decodeTree = _b.decodeTree; + var valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; + this.emitNamedEntityData(result, valueLength, this.consumed); + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); + return this.consumed; + }; + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.emitNamedEntityData = function (result, valueLength, consumed) { + var decodeTree = this.decodeTree; + this.emitCodePoint(valueLength === 1 + ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH + : decodeTree[result + 1], consumed); + if (valueLength === 3) { + // For multi-byte values, we need to emit the second byte. + this.emitCodePoint(decodeTree[result + 2], consumed); + } + return consumed; + }; + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + EntityDecoder.prototype.end = function () { + var _a; + switch (this.state) { + case EntityDecoderState.NamedEntity: { + // Emit a named entity if we have one. + return this.result !== 0 && + (this.decodeMode !== DecodingMode.Attribute || + this.result === this.treeIndex) + ? this.emitNotTerminatedNamedEntity() + : 0; + } + // Otherwise, emit a numeric entity if we have one. + case EntityDecoderState.NumericDecimal: { + return this.emitNumericEntity(0, 2); + } + case EntityDecoderState.NumericHex: { + return this.emitNumericEntity(0, 3); + } + case EntityDecoderState.NumericStart: { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + case EntityDecoderState.EntityStart: { + // Return 0 if we have no entity. + return 0; + } + } + }; + return EntityDecoder; +}()); +exports.EntityDecoder = EntityDecoder; +/** + * Creates a function that decodes entities in a string. + * + * @param decodeTree The decode tree. + * @returns A function that decodes entities in a string. + */ +function getDecoder(decodeTree) { + var ret = ""; + var decoder = new EntityDecoder(decodeTree, function (str) { return (ret += (0, decode_codepoint_js_1.fromCodePoint)(str)); }); + return function decodeWithTrie(str, decodeMode) { + var lastIndex = 0; + var offset = 0; + while ((offset = str.indexOf("&", offset)) >= 0) { + ret += str.slice(lastIndex, offset); + decoder.startEntity(decodeMode); + var len = decoder.write(str, + // Skip the "&" + offset + 1); + if (len < 0) { + lastIndex = offset + decoder.end(); + break; + } + lastIndex = offset + len; + // If `len` is 0, skip the current `&` and continue. + offset = len === 0 ? lastIndex + 1 : lastIndex; + } + var result = ret + str.slice(lastIndex); + // Make sure we don't keep a reference to the final string. + ret = ""; + return result; + }; +} +/** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ +function determineBranch(decodeTree, current, nodeIdx, char) { + var branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; + var jumpOffset = current & BinTrieFlags.JUMP_TABLE; + // Case 1: Single branch encoded in jump offset + if (branchCount === 0) { + return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; + } + // Case 2: Multiple branches encoded in jump table + if (jumpOffset) { + var value = char - jumpOffset; + return value < 0 || value >= branchCount + ? -1 + : decodeTree[nodeIdx + value] - 1; + } + // Case 3: Multiple branches encoded in dictionary + // Binary search for the character. + var lo = nodeIdx; + var hi = lo + branchCount - 1; + while (lo <= hi) { + var mid = (lo + hi) >>> 1; + var midVal = decodeTree[mid]; + if (midVal < char) { + lo = mid + 1; + } + else if (midVal > char) { + hi = mid - 1; + } + else { + return decodeTree[mid + branchCount]; + } + } + return -1; +} +exports.determineBranch = determineBranch; +var htmlDecoder = getDecoder(decode_data_html_js_1.default); +var xmlDecoder = getDecoder(decode_data_xml_js_1.default); +/** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ +function decodeHTML(str, mode) { + if (mode === void 0) { mode = DecodingMode.Legacy; } + return htmlDecoder(str, mode); +} +exports.decodeHTML = decodeHTML; +/** + * Decodes an HTML string in an attribute. + * + * @param str The string to decode. + * @returns The decoded string. + */ +function decodeHTMLAttribute(str) { + return htmlDecoder(str, DecodingMode.Attribute); +} +exports.decodeHTMLAttribute = decodeHTMLAttribute; +/** + * Decodes an HTML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +function decodeHTMLStrict(str) { + return htmlDecoder(str, DecodingMode.Strict); +} +exports.decodeHTMLStrict = decodeHTMLStrict; +/** + * Decodes an XML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +function decodeXML(str) { + return xmlDecoder(str, DecodingMode.Strict); } +exports.decodeXML = decodeXML; +//# sourceMappingURL=decode.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/decode.js.map b/node_modules/entities/lib/decode.js.map new file mode 100644 index 0000000..afcad7e --- /dev/null +++ b/node_modules/entities/lib/decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,wFAA6D;AAQpD,yBARF,6BAAc,CAQE;AAPvB,sFAA2D;AAOlC,wBAPlB,4BAAa,CAOkB;AANtC,2EAG+B;AAGS,0BANjC,6BAAe,CAMiC;AACvD,6DAAwE;AAA/D,uHAAA,gBAAgB,OAAA;AAAE,oHAAA,aAAa,OAAA;AAExC,IAAW,SAaV;AAbD,WAAW,SAAS;IAChB,wCAAQ,CAAA;IACR,0CAAS,CAAA;IACT,8CAAW,CAAA;IACX,0CAAS,CAAA;IACT,0CAAS,CAAA;IACT,gDAAY,CAAA;IACZ,iDAAa,CAAA;IACb,iDAAa,CAAA;IACb,iDAAa,CAAA;IACb,gDAAY,CAAA;IACZ,gDAAY,CAAA;IACZ,gDAAY,CAAA;AAChB,CAAC,EAbU,SAAS,KAAT,SAAS,QAanB;AAED,sFAAsF;AACtF,IAAM,YAAY,GAAG,EAAQ,CAAC;AAE9B,IAAY,YAIX;AAJD,WAAY,YAAY;IACpB,mEAAoC,CAAA;IACpC,qEAAqC,CAAA;IACrC,6DAAkC,CAAA;AACtC,CAAC,EAJW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAIvB;AAED,SAAS,QAAQ,CAAC,IAAY;IAC1B,OAAO,IAAI,IAAI,SAAS,CAAC,IAAI,IAAI,IAAI,IAAI,SAAS,CAAC,IAAI,CAAC;AAC5D,CAAC;AAED,SAAS,sBAAsB,CAAC,IAAY;IACxC,OAAO,CACH,CAAC,IAA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CAAC;AACjD,CAAC;AAFD,4CAEC;AAED;;;;;GAKG;AACH,SAAgB,SAAS,CAAC,GAAW;IACjC,OAAO,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;AAChD,CAAC;AAFD,8BAEC"} \ No newline at end of file diff --git a/node_modules/entities/lib/decode_codepoint.d.ts b/node_modules/entities/lib/decode_codepoint.d.ts index 6b72eaa..84ae206 100644 --- a/node_modules/entities/lib/decode_codepoint.d.ts +++ b/node_modules/entities/lib/decode_codepoint.d.ts @@ -1,2 +1,19 @@ +/** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ +export declare const fromCodePoint: (...codePoints: number[]) => string; +/** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ +export declare function replaceCodePoint(codePoint: number): number; +/** + * Replace the code point if relevant, then convert it to a string. + * + * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. + * @param codePoint The code point to decode. + * @returns The decoded code point. + */ export default function decodeCodePoint(codePoint: number): string; //# sourceMappingURL=decode_codepoint.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/decode_codepoint.d.ts.map b/node_modules/entities/lib/decode_codepoint.d.ts.map index b765ae0..38a8dea 100644 --- a/node_modules/entities/lib/decode_codepoint.d.ts.map +++ b/node_modules/entities/lib/decode_codepoint.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"decode_codepoint.d.ts","sourceRoot":"","sources":["../src/decode_codepoint.ts"],"names":[],"mappings":"AAsBA,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAUjE"} \ No newline at end of file +{"version":3,"file":"decode_codepoint.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode_codepoint.ts"],"names":[],"mappings":"AAkCA;;GAEG;AACH,eAAO,MAAM,aAAa,qCAgBrB,CAAC;AAEN;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,UAMjD;AAED;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAEjE"} \ No newline at end of file diff --git a/node_modules/entities/lib/decode_codepoint.js b/node_modules/entities/lib/decode_codepoint.js index 63efe19..1205346 100644 --- a/node_modules/entities/lib/decode_codepoint.js +++ b/node_modules/entities/lib/decode_codepoint.js @@ -1,30 +1,76 @@ "use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; +// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 +var _a; Object.defineProperty(exports, "__esModule", { value: true }); -var decode_json_1 = __importDefault(require("./maps/decode.json")); -// Adapted from https://github.com/mathiasbynens/he/blob/master/src/he.js#L94-L119 -var fromCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -String.fromCodePoint || - function (codePoint) { - var output = ""; - if (codePoint > 0xffff) { - codePoint -= 0x10000; - output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800); - codePoint = 0xdc00 | (codePoint & 0x3ff); - } - output += String.fromCharCode(codePoint); - return output; - }; -function decodeCodePoint(codePoint) { - if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) { - return "\uFFFD"; +exports.replaceCodePoint = exports.fromCodePoint = void 0; +var decodeMap = new Map([ + [0, 65533], + // C1 Unicode control character reference replacements + [128, 8364], + [130, 8218], + [131, 402], + [132, 8222], + [133, 8230], + [134, 8224], + [135, 8225], + [136, 710], + [137, 8240], + [138, 352], + [139, 8249], + [140, 338], + [142, 381], + [145, 8216], + [146, 8217], + [147, 8220], + [148, 8221], + [149, 8226], + [150, 8211], + [151, 8212], + [152, 732], + [153, 8482], + [154, 353], + [155, 8250], + [156, 339], + [158, 382], + [159, 376], +]); +/** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ +exports.fromCodePoint = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins +(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { + var output = ""; + if (codePoint > 0xffff) { + codePoint -= 0x10000; + output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); } - if (codePoint in decode_json_1.default) { - codePoint = decode_json_1.default[codePoint]; + output += String.fromCharCode(codePoint); + return output; +}; +/** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ +function replaceCodePoint(codePoint) { + var _a; + if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) { + return 0xfffd; } - return fromCodePoint(codePoint); + return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; +} +exports.replaceCodePoint = replaceCodePoint; +/** + * Replace the code point if relevant, then convert it to a string. + * + * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. + * @param codePoint The code point to decode. + * @returns The decoded code point. + */ +function decodeCodePoint(codePoint) { + return (0, exports.fromCodePoint)(replaceCodePoint(codePoint)); } exports.default = decodeCodePoint; +//# sourceMappingURL=decode_codepoint.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/decode_codepoint.js.map b/node_modules/entities/lib/decode_codepoint.js.map new file mode 100644 index 0000000..2747865 --- /dev/null +++ b/node_modules/entities/lib/decode_codepoint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_codepoint.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode_codepoint.ts"],"names":[],"mappings":";AAAA,qHAAqH;;;;AAErH,IAAM,SAAS,GAAG,IAAI,GAAG,CAAC;IACtB,CAAC,CAAC,EAAE,KAAK,CAAC;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KAAK,EAAE,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CACxC,CAAC;QACF,SAAS,GAAG,MAAM,GAAG,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC;KAC5C;IAED,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IACzC,OAAO,MAAM,CAAC;AAClB,CAAC,CAAC;AAEN;;;;GAIG;AACH,SAAgB,gBAAgB,CAAC,SAAiB;;IAC9C,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,IAAI,SAAS,GAAG,QAAQ,EAAE;QACtE,OAAO,MAAM,CAAC;KACjB;IAED,OAAO,MAAA,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,mCAAI,SAAS,CAAC;AACjD,CAAC;AAND,4CAMC;AAED;;;;;;GAMG;AACH,SAAwB,eAAe,CAAC,SAAiB;IACrD,OAAO,IAAA,qBAAa,EAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACtD,CAAC;AAFD,kCAEC"} \ No newline at end of file diff --git a/node_modules/entities/lib/encode.d.ts b/node_modules/entities/lib/encode.d.ts index 8e346d8..f09c4ee 100644 --- a/node_modules/entities/lib/encode.d.ts +++ b/node_modules/entities/lib/encode.d.ts @@ -1,47 +1,22 @@ /** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using XML entities. + * Encodes all characters in the input using HTML entities. This includes + * characters that are valid ASCII characters in HTML documents, such as `#`. * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ -export declare const encodeXML: (data: string) => string; -/** - * Encodes all entities and non-ASCII characters in the input. - * - * This includes characters that are valid ASCII characters in HTML documents. - * For example `#` will be encoded as `#`. To get a more compact output, - * consider using the `encodeNonAsciiHTML` function. + * To get a more compact output, consider using the `encodeNonAsciiHTML` + * function, which will only encode characters that are not valid in HTML + * documents, as well as non-ASCII characters. * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. */ -export declare const encodeHTML: (data: string) => string; +export declare function encodeHTML(data: string): string; /** * Encodes all non-ASCII characters, as well as characters not valid in HTML - * documents using HTML entities. - * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ -export declare const encodeNonAsciiHTML: (data: string) => string; -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using numeric hexadecimal reference (eg. `ü`). - * - * Have a look at `escapeUTF8` if you want a more concise output at the expense - * of reduced transportability. - * - * @param data String to escape. - */ -export declare function escape(data: string): string; -/** - * Encodes all characters not valid in XML documents using numeric hexadecimal - * reference (eg. `ü`). - * - * Note that the output will be character-set dependent. + * documents using HTML entities. This function will not encode characters that + * are valid in HTML documents, such as `#`. * - * @param data String to escape. + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. */ -export declare function escapeUTF8(data: string): string; +export declare function encodeNonAsciiHTML(data: string): string; //# sourceMappingURL=encode.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/encode.d.ts.map b/node_modules/entities/lib/encode.d.ts.map index 0b075fd..e24c05b 100644 --- a/node_modules/entities/lib/encode.d.ts.map +++ b/node_modules/entities/lib/encode.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"encode.d.ts","sourceRoot":"","sources":["../src/encode.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AACH,eAAO,MAAM,SAAS,SAwIJ,MAAM,WAxI4B,CAAC;AAOrD;;;;;;;;;GASG;AACH,eAAO,MAAM,UAAU,SAkFL,MAAM,WAlFuC,CAAC;AAChE;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,SA+Gb,MAAM,WA/GsC,CAAC;AAqF/D;;;;;;;;GAQG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE3C;AAED;;;;;;;GAOG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C"} \ No newline at end of file +{"version":3,"file":"encode.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["encode.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AACD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvD"} \ No newline at end of file diff --git a/node_modules/entities/lib/encode.js b/node_modules/entities/lib/encode.js index d11b238..4786a03 100644 --- a/node_modules/entities/lib/encode.js +++ b/node_modules/entities/lib/encode.js @@ -3,134 +3,75 @@ var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); -exports.escapeUTF8 = exports.escape = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.encodeXML = void 0; -var xml_json_1 = __importDefault(require("./maps/xml.json")); -var inverseXML = getInverseObj(xml_json_1.default); -var xmlReplacer = getInverseReplacer(inverseXML); +exports.encodeNonAsciiHTML = exports.encodeHTML = void 0; +var encode_html_js_1 = __importDefault(require("./generated/encode-html.js")); +var escape_js_1 = require("./escape.js"); +var htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; /** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using XML entities. + * Encodes all characters in the input using HTML entities. This includes + * characters that are valid ASCII characters in HTML documents, such as `#`. * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. - */ -exports.encodeXML = getASCIIEncoder(inverseXML); -var entities_json_1 = __importDefault(require("./maps/entities.json")); -var inverseHTML = getInverseObj(entities_json_1.default); -var htmlReplacer = getInverseReplacer(inverseHTML); -/** - * Encodes all entities and non-ASCII characters in the input. - * - * This includes characters that are valid ASCII characters in HTML documents. - * For example `#` will be encoded as `#`. To get a more compact output, - * consider using the `encodeNonAsciiHTML` function. + * To get a more compact output, consider using the `encodeNonAsciiHTML` + * function, which will only encode characters that are not valid in HTML + * documents, as well as non-ASCII characters. * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. */ -exports.encodeHTML = getInverse(inverseHTML, htmlReplacer); +function encodeHTML(data) { + return encodeHTMLTrieRe(htmlReplacer, data); +} +exports.encodeHTML = encodeHTML; /** * Encodes all non-ASCII characters, as well as characters not valid in HTML - * documents using HTML entities. + * documents using HTML entities. This function will not encode characters that + * are valid in HTML documents, such as `#`. * - * If a character has no equivalent entity, a - * numeric hexadecimal reference (eg. `ü`) will be used. + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. */ -exports.encodeNonAsciiHTML = getASCIIEncoder(inverseHTML); -function getInverseObj(obj) { - return Object.keys(obj) - .sort() - .reduce(function (inverse, name) { - inverse[obj[name]] = "&" + name + ";"; - return inverse; - }, {}); +function encodeNonAsciiHTML(data) { + return encodeHTMLTrieRe(escape_js_1.xmlReplacer, data); } -function getInverseReplacer(inverse) { - var single = []; - var multiple = []; - for (var _i = 0, _a = Object.keys(inverse); _i < _a.length; _i++) { - var k = _a[_i]; - if (k.length === 1) { - // Add value to single array - single.push("\\" + k); +exports.encodeNonAsciiHTML = encodeNonAsciiHTML; +function encodeHTMLTrieRe(regExp, str) { + var ret = ""; + var lastIdx = 0; + var match; + while ((match = regExp.exec(str)) !== null) { + var i = match.index; + ret += str.substring(lastIdx, i); + var char = str.charCodeAt(i); + var next = encode_html_js_1.default.get(char); + if (typeof next === "object") { + // We are in a branch. Try to match the next char. + if (i + 1 < str.length) { + var nextChar = str.charCodeAt(i + 1); + var value = typeof next.n === "number" + ? next.n === nextChar + ? next.o + : undefined + : next.n.get(nextChar); + if (value !== undefined) { + ret += value; + lastIdx = regExp.lastIndex += 1; + continue; + } + } + next = next.v; } - else { - // Add value to multiple array - multiple.push(k); + // We might have a tree node without a value; skip and use a numeric entity. + if (next !== undefined) { + ret += next; + lastIdx = i + 1; } - } - // Add ranges to single characters. - single.sort(); - for (var start = 0; start < single.length - 1; start++) { - // Find the end of a run of characters - var end = start; - while (end < single.length - 1 && - single[end].charCodeAt(1) + 1 === single[end + 1].charCodeAt(1)) { - end += 1; + else { + var cp = (0, escape_js_1.getCodePoint)(str, i); + ret += "&#x".concat(cp.toString(16), ";"); + // Increase by 1 if we have a surrogate pair + lastIdx = regExp.lastIndex += Number(cp !== char); } - var count = 1 + end - start; - // We want to replace at least three characters - if (count < 3) - continue; - single.splice(start, count, single[start] + "-" + single[end]); } - multiple.unshift("[" + single.join("") + "]"); - return new RegExp(multiple.join("|"), "g"); -} -// /[^\0-\x7F]/gu -var reNonASCII = /(?:[\x80-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/g; -var getCodePoint = -// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -String.prototype.codePointAt != null - ? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - function (str) { return str.codePointAt(0); } - : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - function (c) { - return (c.charCodeAt(0) - 0xd800) * 0x400 + - c.charCodeAt(1) - - 0xdc00 + - 0x10000; - }; -function singleCharReplacer(c) { - return "&#x" + (c.length > 1 ? getCodePoint(c) : c.charCodeAt(0)) - .toString(16) - .toUpperCase() + ";"; -} -function getInverse(inverse, re) { - return function (data) { - return data - .replace(re, function (name) { return inverse[name]; }) - .replace(reNonASCII, singleCharReplacer); - }; -} -var reEscapeChars = new RegExp(xmlReplacer.source + "|" + reNonASCII.source, "g"); -/** - * Encodes all non-ASCII characters, as well as characters not valid in XML - * documents using numeric hexadecimal reference (eg. `ü`). - * - * Have a look at `escapeUTF8` if you want a more concise output at the expense - * of reduced transportability. - * - * @param data String to escape. - */ -function escape(data) { - return data.replace(reEscapeChars, singleCharReplacer); -} -exports.escape = escape; -/** - * Encodes all characters not valid in XML documents using numeric hexadecimal - * reference (eg. `ü`). - * - * Note that the output will be character-set dependent. - * - * @param data String to escape. - */ -function escapeUTF8(data) { - return data.replace(xmlReplacer, singleCharReplacer); -} -exports.escapeUTF8 = escapeUTF8; -function getASCIIEncoder(obj) { - return function (data) { - return data.replace(reEscapeChars, function (c) { return obj[c] || singleCharReplacer(c); }); - }; + return ret + str.substr(lastIdx); } +//# sourceMappingURL=encode.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/encode.js.map b/node_modules/entities/lib/encode.js.map new file mode 100644 index 0000000..9d47162 --- /dev/null +++ b/node_modules/entities/lib/encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["encode.ts"],"names":[],"mappings":";;;;;;AAAA,8EAAkD;AAClD,yCAAwD;AAExD,IAAM,YAAY,GAAG,qCAAqC,CAAC;AAE3D;;;;;;;;;;GAUG;AACH,SAAgB,UAAU,CAAC,IAAY;IACnC,OAAO,gBAAgB,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC;AAFD,gCAEC;AACD;;;;;;;GAOG;AACH,SAAgB,kBAAkB,CAAC,IAAY;IAC3C,OAAO,gBAAgB,CAAC,uBAAW,EAAE,IAAI,CAAC,CAAC;AAC/C,CAAC;AAFD,gDAEC;AAED,SAAS,gBAAgB,CAAC,MAAc,EAAE,GAAW;IACjD,IAAI,GAAG,GAAG,EAAE,CAAC;IACb,IAAI,OAAO,GAAG,CAAC,CAAC;IAChB,IAAI,KAAK,CAAC;IAEV,OAAO,CAAC,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE;QACxC,IAAM,CAAC,GAAG,K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KAAK,IAAI,CAAC,CAAC;SACrD;KACJ;IAED,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/escape.d.ts b/node_modules/entities/lib/escape.d.ts new file mode 100644 index 0000000..c07ecdc --- /dev/null +++ b/node_modules/entities/lib/escape.d.ts @@ -0,0 +1,43 @@ +export declare const xmlReplacer: RegExp; +export declare const getCodePoint: (str: string, index: number) => number; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using XML entities. + * + * If a character has no equivalent entity, a + * numeric hexadecimal reference (eg. `ü`) will be used. + */ +export declare function encodeXML(str: string): string; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using numeric hexadecimal reference (eg. `ü`). + * + * Have a look at `escapeUTF8` if you want a more concise output at the expense + * of reduced transportability. + * + * @param data String to escape. + */ +export declare const escape: typeof encodeXML; +/** + * Encodes all characters not valid in XML documents using XML entities. + * + * Note that the output will be character-set dependent. + * + * @param data String to escape. + */ +export declare const escapeUTF8: (data: string) => string; +/** + * Encodes all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export declare const escapeAttribute: (data: string) => string; +/** + * Encodes all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export declare const escapeText: (data: string) => string; +//# sourceMappingURL=escape.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/escape.d.ts.map b/node_modules/entities/lib/escape.d.ts.map new file mode 100644 index 0000000..fa19825 --- /dev/null +++ b/node_modules/entities/lib/escape.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["escape.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,QAAyB,CAAC;AAWlD,eAAO,MAAM,YAAY,QAGT,MAAM,SAAS,MAAM,KAAG,MAQD,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CA0B7C;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,kBAAY,CAAC;AAqChC;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,SA7Bb,MAAM,KAAK,MA6BuC,CAAC;AAE7D;;;;;GAKG;AACH,eAAO,MAAM,eAAe,SArClB,MAAM,KAAK,MA4CpB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,UAAU,SApDb,MAAM,KAAK,MA4DpB,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/escape.js b/node_modules/entities/lib/escape.js new file mode 100644 index 0000000..9f36272 --- /dev/null +++ b/node_modules/entities/lib/escape.js @@ -0,0 +1,122 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.getCodePoint = exports.xmlReplacer = void 0; +exports.xmlReplacer = /["&'<>$\x80-\uFFFF]/g; +var xmlCodeMap = new Map([ + [34, """], + [38, "&"], + [39, "'"], + [60, "<"], + [62, ">"], +]); +// For compatibility with node < 4, we wrap `codePointAt` +exports.getCodePoint = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition +String.prototype.codePointAt != null + ? function (str, index) { return str.codePointAt(index); } + : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + function (c, index) { + return (c.charCodeAt(index) & 0xfc00) === 0xd800 + ? (c.charCodeAt(index) - 0xd800) * 0x400 + + c.charCodeAt(index + 1) - + 0xdc00 + + 0x10000 + : c.charCodeAt(index); + }; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using XML entities. + * + * If a character has no equivalent entity, a + * numeric hexadecimal reference (eg. `ü`) will be used. + */ +function encodeXML(str) { + var ret = ""; + var lastIdx = 0; + var match; + while ((match = exports.xmlReplacer.exec(str)) !== null) { + var i = match.index; + var char = str.charCodeAt(i); + var next = xmlCodeMap.get(char); + if (next !== undefined) { + ret += str.substring(lastIdx, i) + next; + lastIdx = i + 1; + } + else { + ret += "".concat(str.substring(lastIdx, i), "&#x").concat((0, exports.getCodePoint)(str, i).toString(16), ";"); + // Increase by 1 if we have a surrogate pair + lastIdx = exports.xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800); + } + } + return ret + str.substr(lastIdx); +} +exports.encodeXML = encodeXML; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using numeric hexadecimal reference (eg. `ü`). + * + * Have a look at `escapeUTF8` if you want a more concise output at the expense + * of reduced transportability. + * + * @param data String to escape. + */ +exports.escape = encodeXML; +/** + * Creates a function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + * + * @param regex Regular expression to match characters to escape. + * @param map Map of characters to escape to their entities. + * + * @returns Function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + */ +function getEscaper(regex, map) { + return function escape(data) { + var match; + var lastIdx = 0; + var result = ""; + while ((match = regex.exec(data))) { + if (lastIdx !== match.index) { + result += data.substring(lastIdx, match.index); + } + // We know that this character will be in the map. + result += map.get(match[0].charCodeAt(0)); + // Every match will be of length 1 + lastIdx = match.index + 1; + } + return result + data.substring(lastIdx); + }; +} +/** + * Encodes all characters not valid in XML documents using XML entities. + * + * Note that the output will be character-set dependent. + * + * @param data String to escape. + */ +exports.escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); +/** + * Encodes all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +exports.escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([ + [34, """], + [38, "&"], + [160, " "], +])); +/** + * Encodes all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +exports.escapeText = getEscaper(/[&<>\u00A0]/g, new Map([ + [38, "&"], + [60, "<"], + [62, ">"], + [160, " "], +])); +//# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/escape.js.map b/node_modules/entities/lib/escape.js.map new file mode 100644 index 0000000..f96d022 --- /dev/null +++ b/node_modules/entities/lib/escape.js.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["escape.ts"],"names":[],"mappings":";;;AAAa,QAAA,WAAW,GAAG,sBAAsB,CAAC;AAElD,IAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACvB,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,EAAE,EAAE,MAAM,CAAC;CACf,CAAC,CAAC;AAEH,yDAAyD;AAC5C,QAAA,YAAY;AACrB,uEAAuE;AACvE,MAAM,CAAC,SAAS,CAAC,WAAW,IAAI,IAAI;IAChC,CAAC,CAAC,UAAC,GAAW,EAAE,KAAa,IAAa,OAAA,GAAG,CAAC,WAAW,CAAC,KAAK,CAAE,EAAvB,CAAuB;IACjE,CAAC,CAAC,uEAAuE;QACvE,UAAC,CAAS,EAAE,KAAa;YACrB,OAAA,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,MAAM;gBACrC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,KAAK;oBACtC,CAAC,CAAC,UAAU,CAAC,KAAK,GAAG,CAAC,CAAC;oBACvB,MAAM;oBACN,OAAO;gBACT,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC;QALzB,CAKyB,CAAC;AAExC;;;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OAAO,CAAC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,EAAE;YAC/B,IAAI,OAAO,KAAK,KAAK,CAAC,KAAK,EAAE;gBACzB,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;aAClD;YAED,kDAAkD;YAClD,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAE,CAAC;YAE3C,kCAAkC;YAClC,OAAO,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC;SAC7B;QAED,OAAO,MAAM,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAC5C,CAAC,CAAC;AACN,CAAC;AAED;;;;;;GAMG;AACU,QAAA,UAAU,GAAG,UAAU,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;AAE7D;;;;;GAKG;AACU,QAAA,eAAe,GAAG,UAAU,CACrC,aAAa,EACb,IAAI,GAAG,CAAC;IACJ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,GAAG,EAAE,QAAQ,CAAC;CAClB,CAAC,CACL,CAAC;AAEF;;;;;GAKG;AACU,QAAA,UAAU,GAAG,UAAU,CAChC,cAAc,EACd,IAAI,GAAG,CAAC;IACJ,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,GAAG,EAAE,QAAQ,CAAC;CAClB,CAAC,CACL,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode.d.ts b/node_modules/entities/lib/esm/decode.d.ts new file mode 100644 index 0000000..ccfd9fb --- /dev/null +++ b/node_modules/entities/lib/esm/decode.d.ts @@ -0,0 +1,211 @@ +import htmlDecodeTree from "./generated/decode-data-html.js"; +import xmlDecodeTree from "./generated/decode-data-xml.js"; +import decodeCodePoint from "./decode_codepoint.js"; +export { htmlDecodeTree, xmlDecodeTree, decodeCodePoint }; +export { replaceCodePoint, fromCodePoint } from "./decode_codepoint.js"; +export declare enum BinTrieFlags { + VALUE_LENGTH = 49152, + BRANCH_LENGTH = 16256, + JUMP_TABLE = 127 +} +export declare enum DecodingMode { + /** Entities in text nodes that can end with any character. */ + Legacy = 0, + /** Only allow entities terminated with a semicolon. */ + Strict = 1, + /** Entities in attributes have limitations on ending characters. */ + Attribute = 2 +} +/** + * Producers for character reference errors as defined in the HTML spec. + */ +export interface EntityErrorProducer { + missingSemicolonAfterCharacterReference(): void; + absenceOfDigitsInNumericCharacterReference(consumedCharacters: number): void; + validateNumericCharacterReference(code: number): void; +} +/** + * Token decoder with support of writing partial entities. + */ +export declare class EntityDecoder { + /** The tree used to decode entities. */ + private readonly decodeTree; + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + private readonly emitCodePoint; + /** An object that is used to produce errors. */ + private readonly errors?; + constructor( + /** The tree used to decode entities. */ + decodeTree: Uint16Array, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint: (cp: number, consumed: number) => void, + /** An object that is used to produce errors. */ + errors?: EntityErrorProducer | undefined); + /** The current state of the decoder. */ + private state; + /** Characters that were consumed while parsing an entity. */ + private consumed; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + private result; + /** The current index in the decode tree. */ + private treeIndex; + /** The number of characters that were consumed in excess. */ + private excess; + /** The mode in which the decoder is operating. */ + private decodeMode; + /** Resets the instance to make it reusable. */ + startEntity(decodeMode: DecodingMode): void; + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + write(str: string, offset: number): number; + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericStart; + private addToNumericResult; + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericHex; + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNumericDecimal; + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + private emitNumericEntity; + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + private stateNamedEntity; + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + private emitNotTerminatedNamedEntity; + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + private emitNamedEntityData; + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + end(): number; +} +/** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ +export declare function determineBranch(decodeTree: Uint16Array, current: number, nodeIdx: number, char: number): number; +/** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ +export declare function decodeHTML(str: string, mode?: DecodingMode): string; +/** + * Decodes an HTML string in an attribute. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeHTMLAttribute(str: string): string; +/** + * Decodes an HTML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeHTMLStrict(str: string): string; +/** + * Decodes an XML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export declare function decodeXML(str: string): string; +//# sourceMappingURL=decode.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode.d.ts.map b/node_modules/entities/lib/esm/decode.d.ts.map new file mode 100644 index 0000000..4c0b4b4 --- /dev/null +++ b/node_modules/entities/lib/esm/decode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAC3D,OAAO,eAGN,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,eAAe,EAAE,CAAC;AAC1D,OAAO,EAAE,gBAAgB,E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EAAE,MAAM,GAAG,MAAM;IA8B1C;;;;;;;;OAQG;IACH,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,kBAAkB;IAe1B;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IAkBvB;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB;IAkB3B;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,iBAAiB;IA6BzB;;;;;;;;OAQG;IACH,OAAO,CAAC,gBAAgB;IAsDxB;;;;OAIG;IACH,OAAO,CAAC,4BAA4B;IAYpC;;;;;;;;OAQG;IACH,OAAO,CAAC,mBAAmB;IAqB3B;;;;;;OAMG;IACH,GAAG,IAAI,MAAM;CA6BhB;AAoDD;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAC3B,UAAU,EAAE,WAAW,EACvB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,GACb,MAAM,CAsCR;AAKD;;;;;;GAMG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,eAAsB,GAAG,MAAM,CAE1E;AAED;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEvD;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAEpD;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE7C"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode.js b/node_modules/entities/lib/esm/decode.js new file mode 100644 index 0000000..de225ec --- /dev/null +++ b/node_modules/entities/lib/esm/decode.js @@ -0,0 +1,496 @@ +import htmlDecodeTree from "./generated/decode-data-html.js"; +import xmlDecodeTree from "./generated/decode-data-xml.js"; +import decodeCodePoint, { replaceCodePoint, fromCodePoint, } from "./decode_codepoint.js"; +// Re-export for use by eg. htmlparser2 +export { htmlDecodeTree, xmlDecodeTree, decodeCodePoint }; +export { replaceCodePoint, fromCodePoint } from "./decode_codepoint.js"; +var CharCodes; +(function (CharCodes) { + CharCodes[CharCodes["NUM"] = 35] = "NUM"; + CharCodes[CharCodes["SEMI"] = 59] = "SEMI"; + CharCodes[CharCodes["EQUALS"] = 61] = "EQUALS"; + CharCodes[CharCodes["ZERO"] = 48] = "ZERO"; + CharCodes[CharCodes["NINE"] = 57] = "NINE"; + CharCodes[CharCodes["LOWER_A"] = 97] = "LOWER_A"; + CharCodes[CharCodes["LOWER_F"] = 102] = "LOWER_F"; + CharCodes[CharCodes["LOWER_X"] = 120] = "LOWER_X"; + CharCodes[CharCodes["LOWER_Z"] = 122] = "LOWER_Z"; + CharCodes[CharCodes["UPPER_A"] = 65] = "UPPER_A"; + CharCodes[CharCodes["UPPER_F"] = 70] = "UPPER_F"; + CharCodes[CharCodes["UPPER_Z"] = 90] = "UPPER_Z"; +})(CharCodes || (CharCodes = {})); +/** Bit that needs to be set to convert an upper case ASCII character to lower case */ +const TO_LOWER_BIT = 0b100000; +export var BinTrieFlags; +(function (BinTrieFlags) { + BinTrieFlags[BinTrieFlags["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH"; + BinTrieFlags[BinTrieFlags["BRANCH_LENGTH"] = 16256] = "BRANCH_LENGTH"; + BinTrieFlags[BinTrieFlags["JUMP_TABLE"] = 127] = "JUMP_TABLE"; +})(BinTrieFlags || (BinTrieFlags = {})); +function isNumber(code) { + return code >= CharCodes.ZERO && code <= CharCodes.NINE; +} +function isHexadecimalCharacter(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_F) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_F)); +} +function isAsciiAlphaNumeric(code) { + return ((code >= CharCodes.UPPER_A && code <= CharCodes.UPPER_Z) || + (code >= CharCodes.LOWER_A && code <= CharCodes.LOWER_Z) || + isNumber(code)); +} +/** + * Checks if the given character is a valid end character for an entity in an attribute. + * + * Attribute values that aren't terminated properly aren't parsed, and shouldn't lead to a parser error. + * See the example in https://html.spec.whatwg.org/multipage/parsing.html#named-character-reference-state + */ +function isEntityInAttributeInvalidEnd(code) { + return code === CharCodes.EQUALS || isAsciiAlphaNumeric(code); +} +var EntityDecoderState; +(function (EntityDecoderState) { + EntityDecoderState[EntityDecoderState["EntityStart"] = 0] = "EntityStart"; + EntityDecoderState[EntityDecoderState["NumericStart"] = 1] = "NumericStart"; + EntityDecoderState[EntityDecoderState["NumericDecimal"] = 2] = "NumericDecimal"; + EntityDecoderState[EntityDecoderState["NumericHex"] = 3] = "NumericHex"; + EntityDecoderState[EntityDecoderState["NamedEntity"] = 4] = "NamedEntity"; +})(EntityDecoderState || (EntityDecoderState = {})); +export var DecodingMode; +(function (DecodingMode) { + /** Entities in text nodes that can end with any character. */ + DecodingMode[DecodingMode["Legacy"] = 0] = "Legacy"; + /** Only allow entities terminated with a semicolon. */ + DecodingMode[DecodingMode["Strict"] = 1] = "Strict"; + /** Entities in attributes have limitations on ending characters. */ + DecodingMode[DecodingMode["Attribute"] = 2] = "Attribute"; +})(DecodingMode || (DecodingMode = {})); +/** + * Token decoder with support of writing partial entities. + */ +export class EntityDecoder { + constructor( + /** The tree used to decode entities. */ + decodeTree, + /** + * The function that is called when a codepoint is decoded. + * + * For multi-byte named entities, this will be called multiple times, + * with the second codepoint, and the same `consumed` value. + * + * @param codepoint The decoded codepoint. + * @param consumed The number of bytes consumed by the decoder. + */ + emitCodePoint, + /** An object that is used to produce errors. */ + errors) { + this.decodeTree = decodeTree; + this.emitCodePoint = emitCodePoint; + this.errors = errors; + /** The current state of the decoder. */ + this.state = EntityDecoderState.EntityStart; + /** Characters that were consumed while parsing an entity. */ + this.consumed = 1; + /** + * The result of the entity. + * + * Either the result index of a numeric entity, or the codepoint of a + * numeric entity. + */ + this.result = 0; + /** The current index in the decode tree. */ + this.treeIndex = 0; + /** The number of characters that were consumed in excess. */ + this.excess = 1; + /** The mode in which the decoder is operating. */ + this.decodeMode = DecodingMode.Strict; + } + /** Resets the instance to make it reusable. */ + startEntity(decodeMode) { + this.decodeMode = decodeMode; + this.state = EntityDecoderState.EntityStart; + this.result = 0; + this.treeIndex = 0; + this.excess = 1; + this.consumed = 1; + } + /** + * Write an entity to the decoder. This can be called multiple times with partial entities. + * If the entity is incomplete, the decoder will return -1. + * + * Mirrors the implementation of `getDecoder`, but with the ability to stop decoding if the + * entity is incomplete, and resume when the next string is written. + * + * @param string The string containing the entity (or a continuation of the entity). + * @param offset The offset at which the entity begins. Should be 0 if this is not the first call. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + write(str, offset) { + switch (this.state) { + case EntityDecoderState.EntityStart: { + if (str.charCodeAt(offset) === CharCodes.NUM) { + this.state = EntityDecoderState.NumericStart; + this.consumed += 1; + return this.stateNumericStart(str, offset + 1); + } + this.state = EntityDecoderState.NamedEntity; + return this.stateNamedEntity(str, offset); + } + case EntityDecoderState.NumericStart: { + return this.stateNumericStart(str, offset); + } + case EntityDecoderState.NumericDecimal: { + return this.stateNumericDecimal(str, offset); + } + case EntityDecoderState.NumericHex: { + return this.stateNumericHex(str, offset); + } + case EntityDecoderState.NamedEntity: { + return this.stateNamedEntity(str, offset); + } + } + } + /** + * Switches between the numeric decimal and hexadecimal states. + * + * Equivalent to the `Numeric character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericStart(str, offset) { + if (offset >= str.length) { + return -1; + } + if ((str.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) { + this.state = EntityDecoderState.NumericHex; + this.consumed += 1; + return this.stateNumericHex(str, offset + 1); + } + this.state = EntityDecoderState.NumericDecimal; + return this.stateNumericDecimal(str, offset); + } + addToNumericResult(str, start, end, base) { + if (start !== end) { + const digitCount = end - start; + this.result = + this.result * Math.pow(base, digitCount) + + parseInt(str.substr(start, digitCount), base); + this.consumed += digitCount; + } + } + /** + * Parses a hexadecimal numeric entity. + * + * Equivalent to the `Hexademical character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericHex(str, offset) { + const startIdx = offset; + while (offset < str.length) { + const char = str.charCodeAt(offset); + if (isNumber(char) || isHexadecimalCharacter(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 16); + return this.emitNumericEntity(char, 3); + } + } + this.addToNumericResult(str, startIdx, offset, 16); + return -1; + } + /** + * Parses a decimal numeric entity. + * + * Equivalent to the `Decimal character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNumericDecimal(str, offset) { + const startIdx = offset; + while (offset < str.length) { + const char = str.charCodeAt(offset); + if (isNumber(char)) { + offset += 1; + } + else { + this.addToNumericResult(str, startIdx, offset, 10); + return this.emitNumericEntity(char, 2); + } + } + this.addToNumericResult(str, startIdx, offset, 10); + return -1; + } + /** + * Validate and emit a numeric entity. + * + * Implements the logic from the `Hexademical character reference start + * state` and `Numeric character reference end state` in the HTML spec. + * + * @param lastCp The last code point of the entity. Used to see if the + * entity was terminated with a semicolon. + * @param expectedLength The minimum number of characters that should be + * consumed. Used to validate that at least one digit + * was consumed. + * @returns The number of characters that were consumed. + */ + emitNumericEntity(lastCp, expectedLength) { + var _a; + // Ensure we consumed at least one digit. + if (this.consumed <= expectedLength) { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + // Figure out if this is a legit end of the entity + if (lastCp === CharCodes.SEMI) { + this.consumed += 1; + } + else if (this.decodeMode === DecodingMode.Strict) { + return 0; + } + this.emitCodePoint(replaceCodePoint(this.result), this.consumed); + if (this.errors) { + if (lastCp !== CharCodes.SEMI) { + this.errors.missingSemicolonAfterCharacterReference(); + } + this.errors.validateNumericCharacterReference(this.result); + } + return this.consumed; + } + /** + * Parses a named entity. + * + * Equivalent to the `Named character reference state` in the HTML spec. + * + * @param str The string containing the entity (or a continuation of the entity). + * @param offset The current offset. + * @returns The number of characters that were consumed, or -1 if the entity is incomplete. + */ + stateNamedEntity(str, offset) { + const { decodeTree } = this; + let current = decodeTree[this.treeIndex]; + // The mask is the number of bytes of the value, including the current byte. + let valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + for (; offset < str.length; offset++, this.excess++) { + const char = str.charCodeAt(offset); + this.treeIndex = determineBranch(decodeTree, current, this.treeIndex + Math.max(1, valueLength), char); + if (this.treeIndex < 0) { + return this.result === 0 || + // If we are parsing an attribute + (this.decodeMode === DecodingMode.Attribute && + // We shouldn't have consumed any characters after the entity, + (valueLength === 0 || + // And there should be no invalid characters. + isEntityInAttributeInvalidEnd(char))) + ? 0 + : this.emitNotTerminatedNamedEntity(); + } + current = decodeTree[this.treeIndex]; + valueLength = (current & BinTrieFlags.VALUE_LENGTH) >> 14; + // If the branch is a value, store it and continue + if (valueLength !== 0) { + // If the entity is terminated by a semicolon, we are done. + if (char === CharCodes.SEMI) { + return this.emitNamedEntityData(this.treeIndex, valueLength, this.consumed + this.excess); + } + // If we encounter a non-terminated (legacy) entity while parsing strictly, then ignore it. + if (this.decodeMode !== DecodingMode.Strict) { + this.result = this.treeIndex; + this.consumed += this.excess; + this.excess = 0; + } + } + } + return -1; + } + /** + * Emit a named entity that was not terminated with a semicolon. + * + * @returns The number of characters consumed. + */ + emitNotTerminatedNamedEntity() { + var _a; + const { result, decodeTree } = this; + const valueLength = (decodeTree[result] & BinTrieFlags.VALUE_LENGTH) >> 14; + this.emitNamedEntityData(result, valueLength, this.consumed); + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.missingSemicolonAfterCharacterReference(); + return this.consumed; + } + /** + * Emit a named entity. + * + * @param result The index of the entity in the decode tree. + * @param valueLength The number of bytes in the entity. + * @param consumed The number of characters consumed. + * + * @returns The number of characters consumed. + */ + emitNamedEntityData(result, valueLength, consumed) { + const { decodeTree } = this; + this.emitCodePoint(valueLength === 1 + ? decodeTree[result] & ~BinTrieFlags.VALUE_LENGTH + : decodeTree[result + 1], consumed); + if (valueLength === 3) { + // For multi-byte values, we need to emit the second byte. + this.emitCodePoint(decodeTree[result + 2], consumed); + } + return consumed; + } + /** + * Signal to the parser that the end of the input was reached. + * + * Remaining data will be emitted and relevant errors will be produced. + * + * @returns The number of characters consumed. + */ + end() { + var _a; + switch (this.state) { + case EntityDecoderState.NamedEntity: { + // Emit a named entity if we have one. + return this.result !== 0 && + (this.decodeMode !== DecodingMode.Attribute || + this.result === this.treeIndex) + ? this.emitNotTerminatedNamedEntity() + : 0; + } + // Otherwise, emit a numeric entity if we have one. + case EntityDecoderState.NumericDecimal: { + return this.emitNumericEntity(0, 2); + } + case EntityDecoderState.NumericHex: { + return this.emitNumericEntity(0, 3); + } + case EntityDecoderState.NumericStart: { + (_a = this.errors) === null || _a === void 0 ? void 0 : _a.absenceOfDigitsInNumericCharacterReference(this.consumed); + return 0; + } + case EntityDecoderState.EntityStart: { + // Return 0 if we have no entity. + return 0; + } + } + } +} +/** + * Creates a function that decodes entities in a string. + * + * @param decodeTree The decode tree. + * @returns A function that decodes entities in a string. + */ +function getDecoder(decodeTree) { + let ret = ""; + const decoder = new EntityDecoder(decodeTree, (str) => (ret += fromCodePoint(str))); + return function decodeWithTrie(str, decodeMode) { + let lastIndex = 0; + let offset = 0; + while ((offset = str.indexOf("&", offset)) >= 0) { + ret += str.slice(lastIndex, offset); + decoder.startEntity(decodeMode); + const len = decoder.write(str, + // Skip the "&" + offset + 1); + if (len < 0) { + lastIndex = offset + decoder.end(); + break; + } + lastIndex = offset + len; + // If `len` is 0, skip the current `&` and continue. + offset = len === 0 ? lastIndex + 1 : lastIndex; + } + const result = ret + str.slice(lastIndex); + // Make sure we don't keep a reference to the final string. + ret = ""; + return result; + }; +} +/** + * Determines the branch of the current node that is taken given the current + * character. This function is used to traverse the trie. + * + * @param decodeTree The trie. + * @param current The current node. + * @param nodeIdx The index right after the current node and its value. + * @param char The current character. + * @returns The index of the next node, or -1 if no branch is taken. + */ +export function determineBranch(decodeTree, current, nodeIdx, char) { + const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7; + const jumpOffset = current & BinTrieFlags.JUMP_TABLE; + // Case 1: Single branch encoded in jump offset + if (branchCount === 0) { + return jumpOffset !== 0 && char === jumpOffset ? nodeIdx : -1; + } + // Case 2: Multiple branches encoded in jump table + if (jumpOffset) { + const value = char - jumpOffset; + return value < 0 || value >= branchCount + ? -1 + : decodeTree[nodeIdx + value] - 1; + } + // Case 3: Multiple branches encoded in dictionary + // Binary search for the character. + let lo = nodeIdx; + let hi = lo + branchCount - 1; + while (lo <= hi) { + const mid = (lo + hi) >>> 1; + const midVal = decodeTree[mid]; + if (midVal < char) { + lo = mid + 1; + } + else if (midVal > char) { + hi = mid - 1; + } + else { + return decodeTree[mid + branchCount]; + } + } + return -1; +} +const htmlDecoder = getDecoder(htmlDecodeTree); +const xmlDecoder = getDecoder(xmlDecodeTree); +/** + * Decodes an HTML string. + * + * @param str The string to decode. + * @param mode The decoding mode. + * @returns The decoded string. + */ +export function decodeHTML(str, mode = DecodingMode.Legacy) { + return htmlDecoder(str, mode); +} +/** + * Decodes an HTML string in an attribute. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export function decodeHTMLAttribute(str) { + return htmlDecoder(str, DecodingMode.Attribute); +} +/** + * Decodes an HTML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export function decodeHTMLStrict(str) { + return htmlDecoder(str, DecodingMode.Strict); +} +/** + * Decodes an XML string, requiring all entities to be terminated by a semicolon. + * + * @param str The string to decode. + * @returns The decoded string. + */ +export function decodeXML(str) { + return xmlDecoder(str, DecodingMode.Strict); +} +//# sourceMappingURL=decode.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode.js.map b/node_modules/entities/lib/esm/decode.js.map new file mode 100644 index 0000000..2db1510 --- /dev/null +++ b/node_modules/entities/lib/esm/decode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode.ts"],"names":[],"mappings":"AAAA,OAAO,cAAc,MAAM,iCAAiC,CAAC;AAC7D,OAAO,aAAa,MAAM,gCAAgC,CAAC;AAC3D,OAAO,eAAe,EAAE,EACpB,gBAAgB,EAChB,aAAa,GAChB,MAAM,uBAAuB,CAAC;AAE/B,uCAAuC;AACvC,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,eAAe,EAAE,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AAExE,IAAW,SAaV;AAbD,WAAW,SAAS;IAChB,wCAAQ,CAAA;IACR,0CAAS,CAAA;IACT,8CAAW,CAAA;IACX,0CAAS,CAAA;IACT,0CAAS,CAAA;IACT,gDAAY,CAAA;IACZ,iDAAa,CAAA;IACb,iDAAa,CAAA;IACb,iDAAa,CAAA;IACb,gDAAY,CAAA;IACZ,gDAAY,CAAA;IACZ,gDAAY,CAAA;AAChB,CAAC,EAbU,SAAS,KAAT,SAAS,QAanB;AAED,sFAAsF;AACtF,MAAM,YAAY,GAAG,QAAQ,CAAC;AAE9B,MAAM,CAAN,IAAY,YAIX;AAJD,WAAY,YAAY;IACpB,mEAAoC,CAAA;IACpC,qEAAqC,CAAA;IACrC,6DAAkC,CAAA;AACtC,CAAC,EAJW,YAAY,KAAZ,YAAY,QAIvB;AAED,SAAS,QAAQ,CAAC,IAAY;IAC1B,OAAO,IAAI,IAAI,SAAS,CAAC,IAAI,IAAI,IAAI,IAAI,SAAS,CAAC,IAAI,CAAC;AAC5D,CAAC;AAED,SAAS,sBAAsB,CAAC,IAAY;IACxC,OAAO,CACH,CAAC,IAAI,IAAI,SAAS,CAAC,OAAO,IAAI,IAAI,IAAI,SAAS,C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AE,GAAG,EAAE,GAAG,WAAW,GAAG,CAAC,CAAC;IAE9B,OAAO,EAAE,IAAI,EAAE,EAAE;QACb,MAAM,GAAG,GAAG,CAAC,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,CAAC;QAC5B,MAAM,MAAM,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC;QAE/B,IAAI,MAAM,GAAG,IAAI,EAAE;YACf,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;SAChB;aAAM,IAAI,MAAM,GAAG,IAAI,EAAE;YACtB,EAAE,GAAG,GAAG,GAAG,CAAC,CAAC;SAChB;aAAM;YACH,OAAO,UAAU,CAAC,GAAG,GAAG,WAAW,CAAC,CAAC;SACxC;KACJ;IAED,OAAO,CAAC,CAAC,CAAC;AACd,CAAC;AAED,MAAM,WAAW,GAAG,UAAU,CAAC,cAAc,CAAC,CAAC;AAC/C,MAAM,UAAU,GAAG,UAAU,CAAC,aAAa,CAAC,CAAC;AAE7C;;;;;;GAMG;AACH,MAAM,UAAU,UAAU,CAAC,GAAW,EAAE,IAAI,GAAG,YAAY,CAAC,MAAM;IAC9D,OAAO,WAAW,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;AAClC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,GAAW;IAC3C,OAAO,WAAW,CAAC,GAAG,EAAE,YAAY,CAAC,SAAS,CAAC,CAAC;AACpD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW;IACxC,OAAO,WAAW,CAAC,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;AACjD,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,SAAS,CAAC,GAAW;IACjC,OAAO,UAAU,CAAC,GAAG,EAAE,YAAY,CAAC,MAAM,CAAC,CAAC;AAChD,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode_codepoint.d.ts b/node_modules/entities/lib/esm/decode_codepoint.d.ts new file mode 100644 index 0000000..84ae206 --- /dev/null +++ b/node_modules/entities/lib/esm/decode_codepoint.d.ts @@ -0,0 +1,19 @@ +/** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ +export declare const fromCodePoint: (...codePoints: number[]) => string; +/** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ +export declare function replaceCodePoint(codePoint: number): number; +/** + * Replace the code point if relevant, then convert it to a string. + * + * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. + * @param codePoint The code point to decode. + * @returns The decoded code point. + */ +export default function decodeCodePoint(codePoint: number): string; +//# sourceMappingURL=decode_codepoint.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode_codepoint.d.ts.map b/node_modules/entities/lib/esm/decode_codepoint.d.ts.map new file mode 100644 index 0000000..38a8dea --- /dev/null +++ b/node_modules/entities/lib/esm/decode_codepoint.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_codepoint.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["decode_codepoint.ts"],"names":[],"mappings":"AAkCA;;GAEG;AACH,eAAO,MAAM,aAAa,qCAgBrB,CAAC;AAEN;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,MAAM,UAMjD;AAED;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAEjE"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode_codepoint.js b/node_modules/entities/lib/esm/decode_codepoint.js new file mode 100644 index 0000000..4d8281e --- /dev/null +++ b/node_modules/entities/lib/esm/decode_codepoint.js @@ -0,0 +1,71 @@ +// Adapted from https://github.com/mathiasbynens/he/blob/36afe179392226cf1b6ccdb16ebbb7a5a844d93a/src/he.js#L106-L134 +var _a; +const decodeMap = new Map([ + [0, 65533], + // C1 Unicode control character reference replacements + [128, 8364], + [130, 8218], + [131, 402], + [132, 8222], + [133, 8230], + [134, 8224], + [135, 8225], + [136, 710], + [137, 8240], + [138, 352], + [139, 8249], + [140, 338], + [142, 381], + [145, 8216], + [146, 8217], + [147, 8220], + [148, 8221], + [149, 8226], + [150, 8211], + [151, 8212], + [152, 732], + [153, 8482], + [154, 353], + [155, 8250], + [156, 339], + [158, 382], + [159, 376], +]); +/** + * Polyfill for `String.fromCodePoint`. It is used to create a string from a Unicode code point. + */ +export const fromCodePoint = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition, node/no-unsupported-features/es-builtins +(_a = String.fromCodePoint) !== null && _a !== void 0 ? _a : function (codePoint) { + let output = ""; + if (codePoint > 0xffff) { + codePoint -= 0x10000; + output += String.fromCharCode(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + output += String.fromCharCode(codePoint); + return output; +}; +/** + * Replace the given code point with a replacement character if it is a + * surrogate or is outside the valid range. Otherwise return the code + * point unchanged. + */ +export function replaceCodePoint(codePoint) { + var _a; + if ((codePoint >= 0xd800 && codePoint <= 0xdfff) || codePoint > 0x10ffff) { + return 0xfffd; + } + return (_a = decodeMap.get(codePoint)) !== null && _a !== void 0 ? _a : codePoint; +} +/** + * Replace the code point if relevant, then convert it to a string. + * + * @deprecated Use `fromCodePoint(replaceCodePoint(codePoint))` instead. + * @param codePoint The code point to decode. + * @returns The decoded code point. + */ +export default function decodeCodePoint(codePoint) { + return fromCodePoint(replaceCodePoint(codePoint)); +} +//# sourceMappingURL=decode_codepoint.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/decode_codepoint.js.map b/node_modules/entities/lib/esm/decode_codepoint.js.map new file mode 100644 index 0000000..53a32b6 --- /dev/null +++ b/node_modules/entities/lib/esm/decode_codepoint.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode_codepoint.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701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AiB;IACvB,IAAI,MAAM,GAAG,EAAE,CAAC;IAEhB,IAAI,SAAS,GAAG,MAAM,EAAE;QACpB,SAAS,IAAI,OAAO,CAAC;QACrB,MAAM,IAAI,MAAM,CAAC,YAAY,CACzB,CAAC,CAAC,SAAS,KAAK,EAAE,CAAC,GAAG,KAAK,CAAC,GAAG,MAAM,CACxC,CAAC;QACF,SAAS,GAAG,MAAM,GAAG,CAAC,SAAS,GAAG,KAAK,CAAC,CAAC;KAC5C;IAED,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IACzC,OAAO,MAAM,CAAC;AAClB,CAAC,CAAC;AAEN;;;;GAIG;AACH,MAAM,UAAU,gBAAgB,CAAC,SAAiB;;IAC9C,IAAI,CAAC,SAAS,IAAI,MAAM,IAAI,SAAS,IAAI,MAAM,CAAC,IAAI,SAAS,GAAG,QAAQ,EAAE;QACtE,OAAO,MAAM,CAAC;KACjB;IAED,OAAO,MAAA,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,mCAAI,SAAS,CAAC;AACjD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,OAAO,UAAU,eAAe,CAAC,SAAiB;IACrD,OAAO,aAAa,CAAC,gBAAgB,CAAC,SAAS,CAAC,CAAC,CAAC;AACtD,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/encode.d.ts b/node_modules/entities/lib/esm/encode.d.ts new file mode 100644 index 0000000..f09c4ee --- /dev/null +++ b/node_modules/entities/lib/esm/encode.d.ts @@ -0,0 +1,22 @@ +/** + * Encodes all characters in the input using HTML entities. This includes + * characters that are valid ASCII characters in HTML documents, such as `#`. + * + * To get a more compact output, consider using the `encodeNonAsciiHTML` + * function, which will only encode characters that are not valid in HTML + * documents, as well as non-ASCII characters. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ +export declare function encodeHTML(data: string): string; +/** + * Encodes all non-ASCII characters, as well as characters not valid in HTML + * documents using HTML entities. This function will not encode characters that + * are valid in HTML documents, such as `#`. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ +export declare function encodeNonAsciiHTML(data: string): string; +//# sourceMappingURL=encode.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/encode.d.ts.map b/node_modules/entities/lib/esm/encode.d.ts.map new file mode 100644 index 0000000..e24c05b --- /dev/null +++ b/node_modules/entities/lib/esm/encode.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["encode.ts"],"names":[],"mappings":"AAKA;;;;;;;;;;GAUG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAE/C;AACD;;;;;;;GAOG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAEvD"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/encode.js b/node_modules/entities/lib/esm/encode.js new file mode 100644 index 0000000..9c2364f --- /dev/null +++ b/node_modules/entities/lib/esm/encode.js @@ -0,0 +1,69 @@ +import htmlTrie from "./generated/encode-html.js"; +import { xmlReplacer, getCodePoint } from "./escape.js"; +const htmlReplacer = /[\t\n!-,./:-@[-`\f{-}$\x80-\uFFFF]/g; +/** + * Encodes all characters in the input using HTML entities. This includes + * characters that are valid ASCII characters in HTML documents, such as `#`. + * + * To get a more compact output, consider using the `encodeNonAsciiHTML` + * function, which will only encode characters that are not valid in HTML + * documents, as well as non-ASCII characters. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ +export function encodeHTML(data) { + return encodeHTMLTrieRe(htmlReplacer, data); +} +/** + * Encodes all non-ASCII characters, as well as characters not valid in HTML + * documents using HTML entities. This function will not encode characters that + * are valid in HTML documents, such as `#`. + * + * If a character has no equivalent entity, a numeric hexadecimal reference + * (eg. `ü`) will be used. + */ +export function encodeNonAsciiHTML(data) { + return encodeHTMLTrieRe(xmlReplacer, data); +} +function encodeHTMLTrieRe(regExp, str) { + let ret = ""; + let lastIdx = 0; + let match; + while ((match = regExp.exec(str)) !== null) { + const i = match.index; + ret += str.substring(lastIdx, i); + const char = str.charCodeAt(i); + let next = htmlTrie.get(char); + if (typeof next === "object") { + // We are in a branch. Try to match the next char. + if (i + 1 < str.length) { + const nextChar = str.charCodeAt(i + 1); + const value = typeof next.n === "number" + ? next.n === nextChar + ? next.o + : undefined + : next.n.get(nextChar); + if (value !== undefined) { + ret += value; + lastIdx = regExp.lastIndex += 1; + continue; + } + } + next = next.v; + } + // We might have a tree node without a value; skip and use a numeric entity. + if (next !== undefined) { + ret += next; + lastIdx = i + 1; + } + else { + const cp = getCodePoint(str, i); + ret += `&#x${cp.toString(16)};`; + // Increase by 1 if we have a surrogate pair + lastIdx = regExp.lastIndex += Number(cp !== char); + } + } + return ret + str.substr(lastIdx); +} +//# sourceMappingURL=encode.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/encode.js.map b/node_modules/entities/lib/esm/encode.js.map new file mode 100644 index 0000000..14ac068 --- /dev/null +++ b/node_modules/entities/lib/esm/encode.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["encode.ts"],"names":[],"mappings":"AAAA,OAAO,QAAQ,MAAM,4BAA4B,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAExD,MAAM,YAAY,GAAG,qCAAqC,CAAC;AAE3D;;;;;;;;;;GAUG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACnC,OAAO,gBAAgB,CAAC,YAAY,EAAE,IAAI,CAAC,CAAC;AAChD,CAAC;AACD;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAAC,IAAY;IAC3C,OAAO,gBAAgB,CAAC,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G,IAAI,IAAI,CAAC;YACZ,OAAO,GAAG,CAAC,GAAG,CAAC,CAAC;SACnB;aAAM;YACH,MAAM,EAAE,GAAG,YAAY,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;YAChC,GAAG,IAAI,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC;YAChC,4CAA4C;YAC5C,OAAO,GAAG,MAAM,CAAC,SAAS,IAAI,MAAM,CAAC,EAAE,KAAK,IAAI,CAAC,CAAC;SACrD;KACJ;IAED,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/escape.d.ts b/node_modules/entities/lib/esm/escape.d.ts new file mode 100644 index 0000000..c07ecdc --- /dev/null +++ b/node_modules/entities/lib/esm/escape.d.ts @@ -0,0 +1,43 @@ +export declare const xmlReplacer: RegExp; +export declare const getCodePoint: (str: string, index: number) => number; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using XML entities. + * + * If a character has no equivalent entity, a + * numeric hexadecimal reference (eg. `ü`) will be used. + */ +export declare function encodeXML(str: string): string; +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using numeric hexadecimal reference (eg. `ü`). + * + * Have a look at `escapeUTF8` if you want a more concise output at the expense + * of reduced transportability. + * + * @param data String to escape. + */ +export declare const escape: typeof encodeXML; +/** + * Encodes all characters not valid in XML documents using XML entities. + * + * Note that the output will be character-set dependent. + * + * @param data String to escape. + */ +export declare const escapeUTF8: (data: string) => string; +/** + * Encodes all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export declare const escapeAttribute: (data: string) => string; +/** + * Encodes all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export declare const escapeText: (data: string) => string; +//# sourceMappingURL=escape.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/escape.d.ts.map b/node_modules/entities/lib/esm/escape.d.ts.map new file mode 100644 index 0000000..fa19825 --- /dev/null +++ b/node_modules/entities/lib/esm/escape.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["escape.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,WAAW,QAAyB,CAAC;AAWlD,eAAO,MAAM,YAAY,QAGT,MAAM,SAAS,MAAM,KAAG,MAQD,CAAC;AAExC;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CA0B7C;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,kBAAY,CAAC;AAqChC;;;;;;GAMG;AACH,eAAO,MAAM,UAAU,SA7Bb,MAAM,KAAK,MA6BuC,CAAC;AAE7D;;;;;GAKG;AACH,eAAO,MAAM,eAAe,SArClB,MAAM,KAAK,MA4CpB,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,UAAU,SApDb,MAAM,KAAK,MA4DpB,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/escape.js b/node_modules/entities/lib/esm/escape.js new file mode 100644 index 0000000..c64da6e --- /dev/null +++ b/node_modules/entities/lib/esm/escape.js @@ -0,0 +1,116 @@ +export const xmlReplacer = /["&'<>$\x80-\uFFFF]/g; +const xmlCodeMap = new Map([ + [34, """], + [38, "&"], + [39, "'"], + [60, "<"], + [62, ">"], +]); +// For compatibility with node < 4, we wrap `codePointAt` +export const getCodePoint = +// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition +String.prototype.codePointAt != null + ? (str, index) => str.codePointAt(index) + : // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + (c, index) => (c.charCodeAt(index) & 0xfc00) === 0xd800 + ? (c.charCodeAt(index) - 0xd800) * 0x400 + + c.charCodeAt(index + 1) - + 0xdc00 + + 0x10000 + : c.charCodeAt(index); +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using XML entities. + * + * If a character has no equivalent entity, a + * numeric hexadecimal reference (eg. `ü`) will be used. + */ +export function encodeXML(str) { + let ret = ""; + let lastIdx = 0; + let match; + while ((match = xmlReplacer.exec(str)) !== null) { + const i = match.index; + const char = str.charCodeAt(i); + const next = xmlCodeMap.get(char); + if (next !== undefined) { + ret += str.substring(lastIdx, i) + next; + lastIdx = i + 1; + } + else { + ret += `${str.substring(lastIdx, i)}&#x${getCodePoint(str, i).toString(16)};`; + // Increase by 1 if we have a surrogate pair + lastIdx = xmlReplacer.lastIndex += Number((char & 0xfc00) === 0xd800); + } + } + return ret + str.substr(lastIdx); +} +/** + * Encodes all non-ASCII characters, as well as characters not valid in XML + * documents using numeric hexadecimal reference (eg. `ü`). + * + * Have a look at `escapeUTF8` if you want a more concise output at the expense + * of reduced transportability. + * + * @param data String to escape. + */ +export const escape = encodeXML; +/** + * Creates a function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + * + * @param regex Regular expression to match characters to escape. + * @param map Map of characters to escape to their entities. + * + * @returns Function that escapes all characters matched by the given regular + * expression using the given map of characters to escape to their entities. + */ +function getEscaper(regex, map) { + return function escape(data) { + let match; + let lastIdx = 0; + let result = ""; + while ((match = regex.exec(data))) { + if (lastIdx !== match.index) { + result += data.substring(lastIdx, match.index); + } + // We know that this character will be in the map. + result += map.get(match[0].charCodeAt(0)); + // Every match will be of length 1 + lastIdx = match.index + 1; + } + return result + data.substring(lastIdx); + }; +} +/** + * Encodes all characters not valid in XML documents using XML entities. + * + * Note that the output will be character-set dependent. + * + * @param data String to escape. + */ +export const escapeUTF8 = getEscaper(/[&<>'"]/g, xmlCodeMap); +/** + * Encodes all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export const escapeAttribute = getEscaper(/["&\u00A0]/g, new Map([ + [34, """], + [38, "&"], + [160, " "], +])); +/** + * Encodes all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + * + * @param data String to escape. + */ +export const escapeText = getEscaper(/[&<>\u00A0]/g, new Map([ + [38, "&"], + [60, "<"], + [62, ">"], + [160, " "], +])); +//# sourceMappingURL=escape.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/escape.js.map b/node_modules/entities/lib/esm/escape.js.map new file mode 100644 index 0000000..164301c --- /dev/null +++ b/node_modules/entities/lib/esm/escape.js.map @@ -0,0 +1 @@ +{"version":3,"file":"escape.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["escape.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,WAAW,GAAG,sBAAsB,CAAC;AAElD,MAAM,UAAU,GAAG,IAAI,GAAG,CAAC;IACvB,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,OAAO,CAAC;IACb,CAAC,EAAE,EAAE,QAAQ,CAAC;IACd,CAAC,EAAE,EAAE,MAAM,CAAC;IACZ,CAAC,EAAE,EAAE,MAAM,CAAC;CACf,CAAC,CAAC;AAEH,yDAAyD;AACzD,MAAM,CAAC,MAAM,YAAY;AACrB,uEAAuE;AACvE,MAAM,CAAC,SAAS,CAAC,WAAW,IAAI,IAAI;IAChC,CAAC,CAAC,CAAC,GAAW,EAAE,KAAa,EAAU,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,KAAK,CAAE;IACjE,CAAC,CAAC,uEAAuE;QACvE,CAAC,CAAS,EAAE,KAAa,EAAU,EAAE,CACjC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,MAAM;YACrC,CAAC,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,GAAG,KAAK;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end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-html.d.ts b/node_modules/entities/lib/esm/generated/decode-data-html.d.ts new file mode 100644 index 0000000..9cfc4f4 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-html.d.ts @@ -0,0 +1,3 @@ +declare const _default: Uint16Array; +export default _default; +//# sourceMappingURL=decode-data-html.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-html.d.ts.map b/node_modules/entities/lib/esm/generated/decode-data-html.d.ts.map new file mode 100644 index 0000000..6d4d64b --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-html.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-html.ts"],"names":[],"mappings":";AAEA,wBAKE"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-html.js b/node_modules/entities/lib/esm/generated/decode-data-html.js new file mode 100644 index 0000000..0791b55 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-html.js @@ -0,0 +1,7 @@ +// Generated using scripts/write-decode-map.ts +export default new Uint16Array( +// prettier-ignore +"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c" + .split("") + .map((c) => c.charCodeAt(0))); +//# sourceMappingURL=decode-data-html.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-html.js.map b/node_modules/entities/lib/esm/generated/decode-data-html.js.map new file mode 100644 index 0000000..c4b1e6b --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-html.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-html.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-html.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C,eAAe,IAAI,WAAW;AAC1B,kBAAkB;AAClB,268CAA268C;KACt68C,KAAK,CAAC,EAAE,CAAC;KACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts b/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts new file mode 100644 index 0000000..4a3f533 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts @@ -0,0 +1,3 @@ +declare const _default: Uint16Array; +export default _default; +//# sourceMappingURL=decode-data-xml.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts.map b/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts.map new file mode 100644 index 0000000..be2a9a2 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-xml.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-xml.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-xml.ts"],"names":[],"mappings":";AAEA,wBAKE"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-xml.js b/node_modules/entities/lib/esm/generated/decode-data-xml.js new file mode 100644 index 0000000..b01dec7 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-xml.js @@ -0,0 +1,7 @@ +// Generated using scripts/write-decode-map.ts +export default new Uint16Array( +// prettier-ignore +"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022" + .split("") + .map((c) => c.charCodeAt(0))); +//# sourceMappingURL=decode-data-xml.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/decode-data-xml.js.map b/node_modules/entities/lib/esm/generated/decode-data-xml.js.map new file mode 100644 index 0000000..86f7150 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/decode-data-xml.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-xml.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-xml.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAE9C,eAAe,IAAI,WAAW;AAC1B,kBAAkB;AAClB,uFAAuF;KAClF,KAAK,CAAC,EAAE,CAAC;KACT,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/encode-html.d.ts b/node_modules/entities/lib/esm/generated/encode-html.d.ts new file mode 100644 index 0000000..0704827 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/encode-html.d.ts @@ -0,0 +1,8 @@ +type EncodeTrieNode = string | { + v?: string; + n: number | Map; + o?: string; +}; +declare const _default: Map; +export default _default; +//# sourceMappingURL=encode-html.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/encode-html.d.ts.map b/node_modules/entities/lib/esm/generated/encode-html.d.ts.map new file mode 100644 index 0000000..e665a6e --- /dev/null +++ b/node_modules/entities/lib/esm/generated/encode-html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-html.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/encode-html.ts"],"names":[],"mappings":"AAEA,KAAK,cAAc,GACb,MAAM,GACN;IAAE,CAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAAC,CAAC,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;;AAY1E,wBAAo+tB"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/encode-html.js b/node_modules/entities/lib/esm/generated/encode-html.js new file mode 100644 index 0000000..9f1858b --- /dev/null +++ b/node_modules/entities/lib/esm/generated/encode-html.js @@ -0,0 +1,10 @@ +// Generated using scripts/write-encode-map.ts +function restoreDiff(arr) { + for (let i = 1; i < arr.length; i++) { + arr[i][0] += arr[i - 1][0] + 1; + } + return arr; +} +// prettier-ignore +export default new Map(/* #__PURE__ */ restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { v: "<", n: 8402, o: "<⃒" }], [0, { v: "=", n: 8421, o: "=⃥" }], [0, { v: ">", n: 8402, o: ">⃒" }], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { n: 106, o: "fj" }], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { v: " ", n: 8202, o: "  " }], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { v: "↝", n: 824, o: "↝̸" }], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { v: "∂", n: 824, o: "∂̸" }], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { v: "∠", n: 8402, o: "∠⃒" }], [0, "∡"], [0, "∢"], [0, "∣"], [0, "∤"], [0, "∥"], [0, "∦"], [0, "∧"], [0, "∨"], [0, { v: "∩", n: 65024, o: "∩︀" }], [0, { v: "∪", n: 65024, o: "∪︀" }], [0, "∫"], [0, "∬"], [0, "∭"], [0, "∮"], [0, "∯"], [0, "∰"], [0, "∱"], [0, "∲"], [0, "∳"], [0, "∴"], [0, "∵"], [0, "∶"], [0, "∷"], [0, "∸"], [1, "∺"], [0, "∻"], [0, { v: "∼", n: 8402, o: "∼⃒" }], [0, { v: "∽", n: 817, o: "∽̱" }], [0, { v: "∾", n: 819, o: "∾̳" }], [0, "∿"], [0, "≀"], [0, "≁"], [0, { v: "≂", n: 824, o: "≂̸" }], [0, "≃"], [0, "≄"], [0, "≅"], [0, "≆"], [0, "≇"], [0, "≈"], [0, "≉"], [0, "≊"], [0, { v: "≋", n: 824, o: "≋̸" }], [0, "≌"], [0, { v: "≍", n: 8402, o: "≍⃒" }], [0, { v: "≎", n: 824, o: "≎̸" }], [0, { v: "≏", n: 824, o: "≏̸" }], [0, { v: "≐", n: 824, o: "≐̸" }], [0, "≑"], [0, "≒"], [0, "≓"], [0, "≔"], [0, "≕"], [0, "≖"], [0, "≗"], [1, "≙"], [0, "≚"], [1, "≜"], [2, "≟"], [0, "≠"], [0, { v: "≡", n: 8421, o: "≡⃥" }], [0, "≢"], [1, { v: "≤", n: 8402, o: "≤⃒" }], [0, { v: "≥", n: 8402, o: "≥⃒" }], [0, { v: "≦", n: 824, o: "≦̸" }], [0, { v: "≧", n: 824, o: "≧̸" }], [0, { v: "≨", n: 65024, o: "≨︀" }], [0, { v: "≩", n: 65024, o: "≩︀" }], [0, { v: "≪", n: new Map(/* #__PURE__ */ restoreDiff([[824, "≪̸"], [7577, "≪⃒"]])) }], [0, { v: "≫", n: new Map(/* #__PURE__ */ restoreDiff([[824, "≫̸"], [7577, "≫⃒"]])) }], [0, "≬"], [0, "≭"], [0, "≮"], [0, "≯"], [0, "≰"], [0, "≱"], [0, "≲"], [0, "≳"], [0, "≴"], [0, "≵"], [0, "≶"], [0, "≷"], [0, "≸"], [0, "≹"], [0, "≺"], [0, "≻"], [0, "≼"], [0, "≽"], [0, "≾"], [0, { v: "≿", n: 824, o: "≿̸" }], [0, "⊀"], [0, "⊁"], [0, { v: "⊂", n: 8402, o: "⊂⃒" }], [0, { v: "⊃", n: 8402, o: "⊃⃒" }], [0, "⊄"], [0, "⊅"], [0, "⊆"], [0, "⊇"], [0, "⊈"], [0, "⊉"], [0, { v: "⊊", n: 65024, o: "⊊︀" }], [0, { v: "⊋", n: 65024, o: "⊋︀" }], [1, "⊍"], [0, "⊎"], [0, { v: "⊏", n: 824, o: "⊏̸" }], [0, { v: "⊐", n: 824, o: "⊐̸" }], [0, "⊑"], [0, "⊒"], [0, { v: "⊓", n: 65024, o: "⊓︀" }], [0, { v: "⊔", n: 65024, o: "⊔︀" }], [0, "⊕"], [0, "⊖"], [0, "⊗"], [0, "⊘"], [0, "⊙"], [0, "⊚"], [0, "⊛"], [1, "⊝"], [0, "⊞"], [0, "⊟"], [0, "⊠"], [0, "⊡"], [0, "⊢"], [0, "⊣"], [0, "⊤"], [0, "⊥"], [1, "⊧"], [0, "⊨"], [0, "⊩"], [0, "⊪"], [0, "⊫"], [0, "⊬"], [0, "⊭"], [0, "⊮"], [0, "⊯"], [0, "⊰"], [1, "⊲"], [0, "⊳"], [0, { v: "⊴", n: 8402, o: "⊴⃒" }], [0, { v: "⊵", n: 8402, o: "⊵⃒" }], [0, "⊶"], [0, "⊷"], [0, "⊸"], [0, "⊹"], [0, "⊺"], [0, "⊻"], [1, "⊽"], [0, "⊾"], [0, "⊿"], [0, "⋀"], [0, "⋁"], [0, "⋂"], [0, "⋃"], [0, "⋄"], [0, "⋅"], [0, "⋆"], [0, "⋇"], [0, "⋈"], [0, "⋉"], [0, "⋊"], [0, "⋋"], [0, "⋌"], [0, "⋍"], [0, "⋎"], [0, "⋏"], [0, "⋐"], [0, "⋑"], [0, "⋒"], [0, "⋓"], [0, "⋔"], [0, "⋕"], [0, "⋖"], [0, "⋗"], [0, { v: "⋘", n: 824, o: "⋘̸" }], [0, { v: "⋙", n: 824, o: "⋙̸" }], [0, { v: "⋚", n: 65024, o: "⋚︀" }], [0, { v: "⋛", n: 65024, o: "⋛︀" }], [2, "⋞"], [0, "⋟"], [0, "⋠"], [0, "⋡"], [0, "⋢"], [0, "⋣"], [2, "⋦"], [0, "⋧"], [0, "⋨"], [0, "⋩"], [0, "⋪"], [0, "⋫"], [0, "⋬"], [0, "⋭"], [0, "⋮"], [0, "⋯"], [0, "⋰"], [0, "⋱"], [0, "⋲"], [0, "⋳"], [0, "⋴"], [0, { v: "⋵", n: 824, o: "⋵̸" }], [0, "⋶"], [0, "⋷"], [1, { v: "⋹", n: 824, o: "⋹̸" }], [0, "⋺"], [0, "⋻"], [0, "⋼"], [0, "⋽"], [0, "⋾"], [6, "⌅"], [0, "⌆"], [1, "⌈"], [0, "⌉"], [0, "⌊"], [0, "⌋"], [0, "⌌"], [0, "⌍"], [0, "⌎"], [0, "⌏"], [0, "⌐"], [1, "⌒"], [0, "⌓"], [1, "⌕"], [0, "⌖"], [5, "⌜"], [0, "⌝"], [0, "⌞"], [0, "⌟"], [2, "⌢"], [0, "⌣"], [9, "⌭"], [0, "⌮"], [7, "⌶"], [6, "⌽"], [1, "⌿"], [60, "⍼"], [51, "⎰"], [0, "⎱"], [2, "⎴"], [0, "⎵"], [0, "⎶"], [37, "⏜"], [0, "⏝"], [0, "⏞"], [0, "⏟"], [2, "⏢"], [4, "⏧"], [59, "␣"], [164, "Ⓢ"], [55, "─"], [1, "│"], [9, "┌"], [3, "┐"], [3, "└"], [3, "┘"], [3, "├"], [7, "┤"], [7, "┬"], [7, "┴"], [7, "┼"], [19, "═"], [0, "║"], [0, "╒"], [0, "╓"], [0, "╔"], [0, "╕"], [0, "╖"], [0, "╗"], [0, "╘"], [0, "╙"], [0, "╚"], [0, "╛"], [0, "╜"], [0, "╝"], [0, "╞"], [0, "╟"], [0, "╠"], [0, "╡"], [0, "╢"], [0, "╣"], [0, "╤"], [0, "╥"], [0, "╦"], [0, "╧"], [0, "╨"], [0, "╩"], [0, "╪"], [0, "╫"], [0, "╬"], [19, "▀"], [3, "▄"], [3, "█"], [8, "░"], [0, "▒"], [0, "▓"], [13, "□"], [8, "▪"], [0, "▫"], [1, "▭"], [0, "▮"], [2, "▱"], [1, "△"], [0, "▴"], [0, "▵"], [2, "▸"], [0, "▹"], [3, "▽"], [0, "▾"], [0, "▿"], [2, "◂"], [0, "◃"], [6, "◊"], [0, "○"], [32, "◬"], [2, "◯"], [8, "◸"], [0, "◹"], [0, "◺"], [0, "◻"], [0, "◼"], [8, "★"], [0, "☆"], [7, "☎"], [49, "♀"], [1, "♂"], [29, "♠"], [2, "♣"], [1, "♥"], [0, "♦"], [3, "♪"], [2, "♭"], [0, "♮"], [0, "♯"], [163, "✓"], [3, "✗"], [8, "✠"], [21, "✶"], [33, "❘"], [25, "❲"], [0, "❳"], [84, "⟈"], [0, "⟉"], [28, "⟦"], [0, "⟧"], [0, "⟨"], [0, "⟩"], [0, "⟪"], [0, "⟫"], [0, "⟬"], [0, "⟭"], [7, "⟵"], [0, "⟶"], [0, "⟷"], [0, "⟸"], [0, "⟹"], [0, "⟺"], [1, "⟼"], [2, "⟿"], [258, "⤂"], [0, "⤃"], [0, "⤄"], [0, "⤅"], [6, "⤌"], [0, "⤍"], [0, "⤎"], [0, "⤏"], [0, "⤐"], [0, "⤑"], [0, "⤒"], [0, "⤓"], [2, "⤖"], [2, "⤙"], [0, "⤚"], [0, "⤛"], [0, "⤜"], [0, "⤝"], [0, "⤞"], [0, "⤟"], [0, "⤠"], [2, "⤣"], [0, "⤤"], [0, "⤥"], [0, "⤦"], [0, "⤧"], [0, "⤨"], [0, "⤩"], [0, "⤪"], [8, { v: "⤳", n: 824, o: "⤳̸" }], [1, "⤵"], [0, "⤶"], [0, "⤷"], [0, "⤸"], [0, "⤹"], [2, "⤼"], [0, "⤽"], [7, "⥅"], [2, "⥈"], [0, "⥉"], [0, "⥊"], [0, "⥋"], [2, "⥎"], [0, "⥏"], [0, "⥐"], [0, "⥑"], [0, "⥒"], [0, "⥓"], [0, "⥔"], [0, "⥕"], [0, "⥖"], [0, "⥗"], [0, "⥘"], [0, "⥙"], [0, "⥚"], [0, "⥛"], [0, "⥜"], [0, "⥝"], [0, "⥞"], [0, "⥟"], [0, "⥠"], [0, "⥡"], [0, "⥢"], [0, "⥣"], [0, "⥤"], [0, "⥥"], [0, "⥦"], [0, "⥧"], [0, "⥨"], [0, "⥩"], [0, "⥪"], [0, "⥫"], [0, "⥬"], [0, "⥭"], [0, "⥮"], [0, "⥯"], [0, "⥰"], [0, "⥱"], [0, "⥲"], [0, "⥳"], [0, "⥴"], [0, "⥵"], [0, "⥶"], [1, "⥸"], [0, "⥹"], [1, "⥻"], [0, "⥼"], [0, "⥽"], [0, "⥾"], [0, "⥿"], [5, "⦅"], [0, "⦆"], [4, "⦋"], [0, "⦌"], [0, "⦍"], [0, "⦎"], [0, "⦏"], [0, "⦐"], [0, "⦑"], [0, "⦒"], [0, "⦓"], [0, "⦔"], [0, "⦕"], [0, "⦖"], [3, "⦚"], [1, "⦜"], [0, "⦝"], [6, "⦤"], [0, "⦥"], [0, "⦦"], [0, "⦧"], [0, "⦨"], [0, "⦩"], [0, "⦪"], [0, "⦫"], [0, "⦬"], [0, "⦭"], [0, "⦮"], [0, "⦯"], [0, "⦰"], [0, "⦱"], [0, "⦲"], [0, "⦳"], [0, "⦴"], [0, "⦵"], [0, "⦶"], [0, "⦷"], [1, "⦹"], [1, "⦻"], [0, "⦼"], [1, "⦾"], [0, "⦿"], [0, "⧀"], [0, "⧁"], [0, "⧂"], [0, "⧃"], [0, "⧄"], [0, "⧅"], [3, "⧉"], [3, "⧍"], [0, "⧎"], [0, { v: "⧏", n: 824, o: "⧏̸" }], [0, { v: "⧐", n: 824, o: "⧐̸" }], [11, "⧜"], [0, "⧝"], [0, "⧞"], [4, "⧣"], [0, "⧤"], [0, "⧥"], [5, "⧫"], [8, "⧴"], [1, "⧶"], [9, "⨀"], [0, "⨁"], [0, "⨂"], [1, "⨄"], [1, "⨆"], [5, "⨌"], [0, "⨍"], [2, "⨐"], [0, "⨑"], [0, "⨒"], [0, "⨓"], [0, "⨔"], [0, "⨕"], [0, "⨖"], [0, "⨗"], [10, "⨢"], [0, "⨣"], [0, "⨤"], [0, "⨥"], [0, "⨦"], [0, "⨧"], [1, "⨩"], [0, "⨪"], [2, "⨭"], [0, "⨮"], [0, "⨯"], [0, "⨰"], [0, "⨱"], [1, "⨳"], [0, "⨴"], [0, "⨵"], [0, "⨶"], [0, "⨷"], [0, "⨸"], [0, "⨹"], [0, "⨺"], [0, "⨻"], [0, "⨼"], [2, "⨿"], [0, "⩀"], [1, "⩂"], [0, "⩃"], [0, "⩄"], [0, "⩅"], [0, "⩆"], [0, "⩇"], [0, "⩈"], [0, "⩉"], [0, "⩊"], [0, "⩋"], [0, "⩌"], [0, "⩍"], [2, "⩐"], [2, "⩓"], [0, "⩔"], [0, "⩕"], [0, "⩖"], [0, "⩗"], [0, "⩘"], [1, "⩚"], [0, "⩛"], [0, "⩜"], [0, "⩝"], [1, "⩟"], [6, "⩦"], [3, "⩪"], [2, { v: "⩭", n: 824, o: "⩭̸" }], [0, "⩮"], [0, "⩯"], [0, { v: "⩰", n: 824, o: "⩰̸" }], [0, "⩱"], [0, "⩲"], [0, "⩳"], [0, "⩴"], [0, "⩵"], [1, "⩷"], [0, "⩸"], [0, "⩹"], [0, "⩺"], [0, "⩻"], [0, "⩼"], [0, { v: "⩽", n: 824, o: "⩽̸" }], [0, { v: "⩾", n: 824, o: "⩾̸" }], [0, "⩿"], [0, "⪀"], [0, "⪁"], [0, "⪂"], [0, "⪃"], [0, "⪄"], [0, "⪅"], [0, "⪆"], [0, "⪇"], [0, "⪈"], [0, "⪉"], [0, "⪊"], [0, "⪋"], [0, "⪌"], [0, "⪍"], [0, "⪎"], [0, "⪏"], [0, "⪐"], [0, "⪑"], [0, "⪒"], [0, "⪓"], [0, "⪔"], [0, "⪕"], [0, "⪖"], [0, "⪗"], [0, "⪘"], [0, "⪙"], [0, "⪚"], [2, "⪝"], [0, "⪞"], [0, "⪟"], [0, "⪠"], [0, { v: "⪡", n: 824, o: "⪡̸" }], [0, { v: "⪢", n: 824, o: "⪢̸" }], [1, "⪤"], [0, "⪥"], [0, "⪦"], [0, "⪧"], [0, "⪨"], [0, "⪩"], [0, "⪪"], [0, "⪫"], [0, { v: "⪬", n: 65024, o: "⪬︀" }], [0, { v: "⪭", n: 65024, o: "⪭︀" }], [0, "⪮"], [0, { v: "⪯", n: 824, o: "⪯̸" }], [0, { v: "⪰", n: 824, o: "⪰̸" }], [2, "⪳"], [0, "⪴"], [0, "⪵"], [0, "⪶"], [0, "⪷"], [0, "⪸"], [0, "⪹"], [0, "⪺"], [0, "⪻"], [0, "⪼"], [0, "⪽"], [0, "⪾"], [0, "⪿"], [0, "⫀"], [0, "⫁"], [0, "⫂"], [0, "⫃"], [0, "⫄"], [0, { v: "⫅", n: 824, o: "⫅̸" }], [0, { v: "⫆", n: 824, o: "⫆̸" }], [0, "⫇"], [0, "⫈"], [2, { v: "⫋", n: 65024, o: "⫋︀" }], [0, { v: "⫌", n: 65024, o: "⫌︀" }], [2, "⫏"], [0, "⫐"], [0, "⫑"], [0, "⫒"], [0, "⫓"], [0, "⫔"], [0, "⫕"], [0, "⫖"], [0, "⫗"], [0, "⫘"], [0, "⫙"], [0, "⫚"], [0, "⫛"], [8, "⫤"], [1, "⫦"], [0, "⫧"], [0, "⫨"], [0, "⫩"], [1, "⫫"], [0, "⫬"], [0, "⫭"], [0, "⫮"], [0, "⫯"], [0, "⫰"], [0, "⫱"], [0, "⫲"], [0, "⫳"], [9, { v: "⫽", n: 8421, o: "⫽⃥" }], [44343, { n: new Map(/* #__PURE__ */ restoreDiff([[56476, "𝒜"], [1, "𝒞"], [0, "𝒟"], [2, "𝒢"], [2, "𝒥"], [0, "𝒦"], [2, "𝒩"], [0, "𝒪"], [0, "𝒫"], [0, "𝒬"], [1, "𝒮"], [0, "𝒯"], [0, "𝒰"], [0, "𝒱"], [0, "𝒲"], [0, "𝒳"], [0, "𝒴"], [0, "𝒵"], [0, "𝒶"], [0, "𝒷"], [0, "𝒸"], [0, "𝒹"], [1, "𝒻"], [1, "𝒽"], [0, "𝒾"], [0, "𝒿"], [0, "𝓀"], [0, "𝓁"], [0, "𝓂"], [0, "𝓃"], [1, "𝓅"], [0, "𝓆"], [0, "𝓇"], [0, "𝓈"], [0, "𝓉"], [0, "𝓊"], [0, "𝓋"], [0, "𝓌"], [0, "𝓍"], [0, "𝓎"], [0, "𝓏"], [52, "𝔄"], [0, "𝔅"], [1, "𝔇"], [0, "𝔈"], [0, "𝔉"], [0, "𝔊"], [2, "𝔍"], [0, "𝔎"], [0, "𝔏"], [0, "𝔐"], [0, "𝔑"], [0, "𝔒"], [0, "𝔓"], [0, "𝔔"], [1, "𝔖"], [0, "𝔗"], [0, "𝔘"], [0, "𝔙"], [0, "𝔚"], [0, "𝔛"], [0, "𝔜"], [1, "𝔞"], [0, "𝔟"], [0, "𝔠"], [0, "𝔡"], [0, "𝔢"], [0, "𝔣"], [0, "𝔤"], [0, "𝔥"], [0, "𝔦"], [0, "𝔧"], [0, "𝔨"], [0, "𝔩"], [0, "𝔪"], [0, "𝔫"], [0, "𝔬"], [0, "𝔭"], [0, "𝔮"], [0, "𝔯"], [0, "𝔰"], [0, "𝔱"], [0, "𝔲"], [0, "𝔳"], [0, "𝔴"], [0, "𝔵"], [0, "𝔶"], [0, "𝔷"], [0, "𝔸"], [0, "𝔹"], [1, "𝔻"], [0, "𝔼"], [0, "𝔽"], [0, "𝔾"], [1, "𝕀"], [0, "𝕁"], [0, "𝕂"], [0, "𝕃"], [0, "𝕄"], [1, "𝕆"], [3, "𝕊"], [0, "𝕋"], [0, "𝕌"], [0, "𝕍"], [0, "𝕎"], [0, "𝕏"], [0, "𝕐"], [1, "𝕒"], [0, "𝕓"], [0, "𝕔"], [0, "𝕕"], [0, "𝕖"], [0, "𝕗"], [0, "𝕘"], [0, "𝕙"], [0, "𝕚"], [0, "𝕛"], [0, "𝕜"], [0, "𝕝"], [0, "𝕞"], [0, "𝕟"], [0, "𝕠"], [0, "𝕡"], [0, "𝕢"], [0, "𝕣"], [0, "𝕤"], [0, "𝕥"], [0, "𝕦"], [0, "𝕧"], [0, "𝕨"], [0, "𝕩"], [0, "𝕪"], [0, "𝕫"]])) }], [8906, "ff"], [0, "fi"], [0, "fl"], [0, "ffi"], [0, "ffl"]])); +//# sourceMappingURL=encode-html.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/generated/encode-html.js.map b/node_modules/entities/lib/esm/generated/encode-html.js.map new file mode 100644 index 0000000..8906ff8 --- /dev/null +++ b/node_modules/entities/lib/esm/generated/encode-html.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-html.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/encode-html.ts"],"names":[],"mappings":"AAAA,8CAA8C;AAM9C,SAAS,WAAW,CAChB,GAAM;IAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACjC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;KAClC;IACD,OAAO,GAAG,CAAC;AACf,CAAC;AAED,kBAAkB;AAClB,eAAe,IAAI,GAAG,CAAwB,eAAe,CAAA,WAAW,CAAC,CAAC,CAAC,CAAC,EAAC,OAAO,CAAC,EAAC,CAAC,CAAC,EAAC,WAAW,CAAC,EAAC,CAAC,EAAE,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,OAAO,CAAC,EAAC,CAAC,CAAC,EAAC,UAAU,CAAC,EAAC,CAAC,CAAC,EAAC,UAAU,CAAC,EAAC,CAAC,CAAC,EAAC,OAAO,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,OAAO,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,SAAS,CAAC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,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,EAAC,CAAC,CAAC,EAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,EAAC,CAAC,EAAC,CAAC,IAAI,EAAC,SAAS,CAAC,EAAC,CAAC,CAAC,EAAC,SAAS,CAAC,EAAC,CAAC,CAAC,EAAC,SAAS,CAAC,EAAC,CAAC,CAAC,EAAC,UAAU,CAAC,EAAC,CAAC,CAAC,EAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/index.d.ts b/node_modules/entities/lib/esm/index.d.ts new file mode 100644 index 0000000..dd4eb11 --- /dev/null +++ b/node_modules/entities/lib/esm/index.d.ts @@ -0,0 +1,96 @@ +import { DecodingMode } from "./decode.js"; +/** The level of entities to support. */ +export declare enum EntityLevel { + /** Support only XML entities. */ + XML = 0, + /** Support HTML entities, which are a superset of XML entities. */ + HTML = 1 +} +export declare enum EncodingMode { + /** + * The output is UTF-8 encoded. Only characters that need escaping within + * XML will be escaped. + */ + UTF8 = 0, + /** + * The output consists only of ASCII characters. Characters that need + * escaping within HTML, and characters that aren't ASCII characters will + * be escaped. + */ + ASCII = 1, + /** + * Encode all characters that have an equivalent entity, as well as all + * characters that are not ASCII characters. + */ + Extensive = 2, + /** + * Encode all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + Attribute = 3, + /** + * Encode all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + Text = 4 +} +export interface DecodingOptions { + /** + * The level of entities to support. + * @default {@link EntityLevel.XML} + */ + level?: EntityLevel; + /** + * Decoding mode. If `Legacy`, will support legacy entities not terminated + * with a semicolon (`;`). + * + * Always `Strict` for XML. For HTML, set this to `true` if you are parsing + * an attribute value. + * + * The deprecated `decodeStrict` function defaults this to `Strict`. + * + * @default {@link DecodingMode.Legacy} + */ + mode?: DecodingMode | undefined; +} +/** + * Decodes a string with entities. + * + * @param data String to decode. + * @param options Decoding options. + */ +export declare function decode(data: string, options?: DecodingOptions | EntityLevel): string; +/** + * Decodes a string with entities. Does not allow missing trailing semicolons for entities. + * + * @param data String to decode. + * @param options Decoding options. + * @deprecated Use `decode` with the `mode` set to `Strict`. + */ +export declare function decodeStrict(data: string, options?: DecodingOptions | EntityLevel): string; +/** + * Options for `encode`. + */ +export interface EncodingOptions { + /** + * The level of entities to support. + * @default {@link EntityLevel.XML} + */ + level?: EntityLevel; + /** + * Output format. + * @default {@link EncodingMode.Extensive} + */ + mode?: EncodingMode; +} +/** + * Encodes a string with entities. + * + * @param data String to encode. + * @param options Encoding options. + */ +export declare function encode(data: string, options?: EncodingOptions | EntityLevel): string; +export { encodeXML, escape, escapeUTF8, escapeAttribute, escapeText, } from "./escape.js"; +export { encodeHTML, encodeNonAsciiHTML, encodeHTML as encodeHTML4, encodeHTML as encodeHTML5, } from "./encode.js"; +export { EntityDecoder, DecodingMode, decodeXML, decodeHTML, decodeHTMLStrict, decodeHTMLAttribute, decodeHTML as decodeHTML4, decodeHTML as decodeHTML5, decodeHTMLStrict as decodeHTML4Strict, decodeHTMLStrict as decodeHTML5Strict, decodeXML as decodeXMLStrict, } from "./decode.js"; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/index.d.ts.map b/node_modules/entities/lib/esm/index.d.ts.map new file mode 100644 index 0000000..cfeef9f --- /dev/null +++ b/node_modules/entities/lib/esm/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,YAAY,EAAE,MAAM,aAAa,CAAC;AASlE,wCAAwC;AACxC,oBAAY,WAAW;IACnB,iCAAiC;IACjC,GAAG,IAAI;IACP,mEAAmE;IACnE,IAAI,IAAI;CACX;AAED,oBAAY,YAAY;IACpB;;;OAGG;IACH,IAAI,IAAA;IACJ;;;;OAIG;IACH,KAAK,IAAA;IACL;;;OAGG;IACH,SAAS,IAAA;IACT;;;OAGG;IACH,SAAS,IAAA;IACT;;;OAGG;IACH,IAAI,IAAA;CACP;AAED,MAAM,WAAW,eAAe;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB;;;;;;;;;;OAUG;IACH,IAAI,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;CACnC;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CASR;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CACxB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CAKR;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB;;;OAGG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;CACvB;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CAkBR;AAED,OAAO,EACH,SAAS,EACT,MAAM,EACN,UAAU,EACV,eAAe,EACf,UAAU,GACb,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,UAAU,EACV,kBAAkB,EAElB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,GAC5B,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,aAAa,EACb,YAAY,EACZ,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,mBAAmB,EAEnB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,gBAAgB,IAAI,iBAAiB,EACrC,gBAAgB,IAAI,iBAAiB,EACrC,SAAS,IAAI,eAAe,GAC/B,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/index.js b/node_modules/entities/lib/esm/index.js new file mode 100644 index 0000000..acc6dbe --- /dev/null +++ b/node_modules/entities/lib/esm/index.js @@ -0,0 +1,99 @@ +import { decodeXML, decodeHTML, DecodingMode } from "./decode.js"; +import { encodeHTML, encodeNonAsciiHTML } from "./encode.js"; +import { encodeXML, escapeUTF8, escapeAttribute, escapeText, } from "./escape.js"; +/** The level of entities to support. */ +export var EntityLevel; +(function (EntityLevel) { + /** Support only XML entities. */ + EntityLevel[EntityLevel["XML"] = 0] = "XML"; + /** Support HTML entities, which are a superset of XML entities. */ + EntityLevel[EntityLevel["HTML"] = 1] = "HTML"; +})(EntityLevel || (EntityLevel = {})); +export var EncodingMode; +(function (EncodingMode) { + /** + * The output is UTF-8 encoded. Only characters that need escaping within + * XML will be escaped. + */ + EncodingMode[EncodingMode["UTF8"] = 0] = "UTF8"; + /** + * The output consists only of ASCII characters. Characters that need + * escaping within HTML, and characters that aren't ASCII characters will + * be escaped. + */ + EncodingMode[EncodingMode["ASCII"] = 1] = "ASCII"; + /** + * Encode all characters that have an equivalent entity, as well as all + * characters that are not ASCII characters. + */ + EncodingMode[EncodingMode["Extensive"] = 2] = "Extensive"; + /** + * Encode all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[EncodingMode["Attribute"] = 3] = "Attribute"; + /** + * Encode all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[EncodingMode["Text"] = 4] = "Text"; +})(EncodingMode || (EncodingMode = {})); +/** + * Decodes a string with entities. + * + * @param data String to decode. + * @param options Decoding options. + */ +export function decode(data, options = EntityLevel.XML) { + const level = typeof options === "number" ? options : options.level; + if (level === EntityLevel.HTML) { + const mode = typeof options === "object" ? options.mode : undefined; + return decodeHTML(data, mode); + } + return decodeXML(data); +} +/** + * Decodes a string with entities. Does not allow missing trailing semicolons for entities. + * + * @param data String to decode. + * @param options Decoding options. + * @deprecated Use `decode` with the `mode` set to `Strict`. + */ +export function decodeStrict(data, options = EntityLevel.XML) { + var _a; + const opts = typeof options === "number" ? { level: options } : options; + (_a = opts.mode) !== null && _a !== void 0 ? _a : (opts.mode = DecodingMode.Strict); + return decode(data, opts); +} +/** + * Encodes a string with entities. + * + * @param data String to encode. + * @param options Encoding options. + */ +export function encode(data, options = EntityLevel.XML) { + const opts = typeof options === "number" ? { level: options } : options; + // Mode `UTF8` just escapes XML entities + if (opts.mode === EncodingMode.UTF8) + return escapeUTF8(data); + if (opts.mode === EncodingMode.Attribute) + return escapeAttribute(data); + if (opts.mode === EncodingMode.Text) + return escapeText(data); + if (opts.level === EntityLevel.HTML) { + if (opts.mode === EncodingMode.ASCII) { + return encodeNonAsciiHTML(data); + } + return encodeHTML(data); + } + // ASCII and Extensive are equivalent + return encodeXML(data); +} +export { encodeXML, escape, escapeUTF8, escapeAttribute, escapeText, } from "./escape.js"; +export { encodeHTML, encodeNonAsciiHTML, +// Legacy aliases (deprecated) +encodeHTML as encodeHTML4, encodeHTML as encodeHTML5, } from "./encode.js"; +export { EntityDecoder, DecodingMode, decodeXML, decodeHTML, decodeHTMLStrict, decodeHTMLAttribute, +// Legacy aliases (deprecated) +decodeHTML as decodeHTML4, decodeHTML as decodeHTML5, decodeHTMLStrict as decodeHTML4Strict, decodeHTMLStrict as decodeHTML5Strict, decodeXML as decodeXMLStrict, } from "./decode.js"; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/esm/index.js.map b/node_modules/entities/lib/esm/index.js.map new file mode 100644 index 0000000..5f634fc --- /dev/null +++ b/node_modules/entities/lib/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,EAAE,UAAU,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAC7D,OAAO,EACH,SAAS,EACT,UAAU,EACV,eAAe,EACf,UAAU,GACb,MAAM,aAAa,CAAC;AAErB,wCAAwC;AACxC,MAAM,CAAN,IAAY,WAKX;AALD,WAAY,WAAW;IACnB,iCAAiC;IACjC,2CAAO,CAAA;IACP,mEAAmE;IACnE,6CAAQ,CAAA;AACZ,CAAC,EALW,WAAW,KAAX,WAAW,QAKtB;AAED,MAAM,CAAN,IAAY,YA2BX;AA3BD,WAAY,YAAY;IACpB;;;OAGG;IACH,+CAAI,CAAA;IACJ;;;;OAIG;IACH,iDAAK,CAAA;IACL;;;OAGG;IACH,yDAAS,CAAA;IACT;;;OAGG;IACH,yDAAS,CAAA;IACT;;;OAGG;IACH,+CAAI,CAAA;AACR,CAAC,EA3BW,YAAY,KAAZ,YAAY,QA2BvB;AAsBD;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAClB,IAAY,EACZ,UAAyC,WAAW,CAAC,GAAG;IAExD,MAAM,KAAK,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;IAEpE,IAAI,KAAK,KAAK,WAAW,CAAC,IAAI,EAAE;QAC5B,MAAM,IAAI,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;QACpE,O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,SAAS,CAAC,IAAI,CAAC,CAAC;AAC3B,CAAC;AAED,OAAO,EACH,SAAS,EACT,MAAM,EACN,UAAU,EACV,eAAe,EACf,UAAU,GACb,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,UAAU,EACV,kBAAkB;AAClB,8BAA8B;AAC9B,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,GAC5B,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,aAAa,EACb,YAAY,EACZ,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,mBAAmB;AACnB,8BAA8B;AAC9B,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,gBAAgB,IAAI,iBAAiB,EACrC,gBAAgB,IAAI,iBAAiB,EACrC,SAAS,IAAI,eAAe,GAC/B,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/esm/package.json b/node_modules/entities/lib/esm/package.json new file mode 100644 index 0000000..089153b --- /dev/null +++ b/node_modules/entities/lib/esm/package.json @@ -0,0 +1 @@ +{"type":"module"} diff --git a/node_modules/entities/lib/generated/decode-data-html.d.ts b/node_modules/entities/lib/generated/decode-data-html.d.ts new file mode 100644 index 0000000..9cfc4f4 --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-html.d.ts @@ -0,0 +1,3 @@ +declare const _default: Uint16Array; +export default _default; +//# sourceMappingURL=decode-data-html.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-html.d.ts.map b/node_modules/entities/lib/generated/decode-data-html.d.ts.map new file mode 100644 index 0000000..6d4d64b --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-html.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-html.ts"],"names":[],"mappings":";AAEA,wBAKE"} \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-html.js b/node_modules/entities/lib/generated/decode-data-html.js new file mode 100644 index 0000000..295cd9b --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-html.js @@ -0,0 +1,9 @@ +"use strict"; +// Generated using scripts/write-decode-map.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = new Uint16Array( +// prettier-ignore +"\u1d41<\xd5\u0131\u028a\u049d\u057b\u05d0\u0675\u06de\u07a2\u07d6\u080f\u0a4a\u0a91\u0da1\u0e6d\u0f09\u0f26\u10ca\u1228\u12e1\u1415\u149d\u14c3\u14df\u1525\0\0\0\0\0\0\u156b\u16cd\u198d\u1c12\u1ddd\u1f7e\u2060\u21b0\u228d\u23c0\u23fb\u2442\u2824\u2912\u2d08\u2e48\u2fce\u3016\u32ba\u3639\u37ac\u38fe\u3a28\u3a71\u3ae0\u3b2e\u0800EMabcfglmnoprstu\\bfms\x7f\x84\x8b\x90\x95\x98\xa6\xb3\xb9\xc8\xcflig\u803b\xc6\u40c6P\u803b&\u4026cute\u803b\xc1\u40c1reve;\u4102\u0100iyx}rc\u803b\xc2\u40c2;\u4410r;\uc000\ud835\udd04rave\u803b\xc0\u40c0pha;\u4391acr;\u4100d;\u6a53\u0100gp\x9d\xa1on;\u4104f;\uc000\ud835\udd38plyFunction;\u6061ing\u803b\xc5\u40c5\u0100cs\xbe\xc3r;\uc000\ud835\udc9cign;\u6254ilde\u803b\xc3\u40c3ml\u803b\xc4\u40c4\u0400aceforsu\xe5\xfb\xfe\u0117\u011c\u0122\u0127\u012a\u0100cr\xea\xf2kslash;\u6216\u0176\xf6\xf8;\u6ae7ed;\u6306y;\u4411\u0180crt\u0105\u010b\u0114ause;\u6235noullis;\u612ca;\u4392r;\uc000\ud835\udd05pf;\uc000\ud835\udd39eve;\u42d8c\xf2\u0113mpeq;\u624e\u0700HOacdefhilorsu\u014d\u0151\u0156\u0180\u019e\u01a2\u01b5\u01b7\u01ba\u01dc\u0215\u0273\u0278\u027ecy;\u4427PY\u803b\xa9\u40a9\u0180cpy\u015d\u0162\u017aute;\u4106\u0100;i\u0167\u0168\u62d2talDifferentialD;\u6145leys;\u612d\u0200aeio\u0189\u018e\u0194\u0198ron;\u410cdil\u803b\xc7\u40c7rc;\u4108nint;\u6230ot;\u410a\u0100dn\u01a7\u01adilla;\u40b8terDot;\u40b7\xf2\u017fi;\u43a7rcle\u0200DMPT\u01c7\u01cb\u01d1\u01d6ot;\u6299inus;\u6296lus;\u6295imes;\u6297o\u0100cs\u01e2\u01f8kwiseContourIntegral;\u6232eCurly\u0100DQ\u0203\u020foubleQuote;\u601duote;\u6019\u0200lnpu\u021e\u0228\u0247\u0255on\u0100;e\u0225\u0226\u6237;\u6a74\u0180git\u022f\u0236\u023aruent;\u6261nt;\u622fourIntegral;\u622e\u0100fr\u024c\u024e;\u6102oduct;\u6210nterClockwiseContourIntegral;\u6233oss;\u6a2fcr;\uc000\ud835\udc9ep\u0100;C\u0284\u0285\u62d3ap;\u624d\u0580DJSZacefios\u02a0\u02ac\u02b0\u02b4\u02b8\u02cb\u02d7\u02e1\u02e6\u0333\u048d\u0100;o\u0179\u02a5trahd;\u6911cy;\u4402cy;\u4405cy;\u440f\u0180grs\u02bf\u02c4\u02c7ger;\u6021r;\u61a1hv;\u6ae4\u0100ay\u02d0\u02d5ron;\u410e;\u4414l\u0100;t\u02dd\u02de\u6207a;\u4394r;\uc000\ud835\udd07\u0100af\u02eb\u0327\u0100cm\u02f0\u0322ritical\u0200ADGT\u0300\u0306\u0316\u031ccute;\u40b4o\u0174\u030b\u030d;\u42d9bleAcute;\u42ddrave;\u4060ilde;\u42dcond;\u62c4ferentialD;\u6146\u0470\u033d\0\0\0\u0342\u0354\0\u0405f;\uc000\ud835\udd3b\u0180;DE\u0348\u0349\u034d\u40a8ot;\u60dcqual;\u6250ble\u0300CDLRUV\u0363\u0372\u0382\u03cf\u03e2\u03f8ontourIntegra\xec\u0239o\u0274\u0379\0\0\u037b\xbb\u0349nArrow;\u61d3\u0100eo\u0387\u03a4ft\u0180ART\u0390\u0396\u03a1rrow;\u61d0ightArrow;\u61d4e\xe5\u02cang\u0100LR\u03ab\u03c4eft\u0100AR\u03b3\u03b9rrow;\u67f8ightArrow;\u67faightArrow;\u67f9ight\u0100AT\u03d8\u03derrow;\u61d2ee;\u62a8p\u0241\u03e9\0\0\u03efrrow;\u61d1ownArrow;\u61d5erticalBar;\u6225n\u0300ABLRTa\u0412\u042a\u0430\u045e\u047f\u037crrow\u0180;BU\u041d\u041e\u0422\u6193ar;\u6913pArrow;\u61f5reve;\u4311eft\u02d2\u043a\0\u0446\0\u0450ightVector;\u6950eeVector;\u695eector\u0100;B\u0459\u045a\u61bdar;\u6956ight\u01d4\u0467\0\u0471eeVector;\u695fector\u0100;B\u047a\u047b\u61c1ar;\u6957ee\u0100;A\u0486\u0487\u62a4rrow;\u61a7\u0100ct\u0492\u0497r;\uc000\ud835\udc9frok;\u4110\u0800NTacdfglmopqstux\u04bd\u04c0\u04c4\u04cb\u04de\u04e2\u04e7\u04ee\u04f5\u0521\u052f\u0536\u0552\u055d\u0560\u0565G;\u414aH\u803b\xd0\u40d0cute\u803b\xc9\u40c9\u0180aiy\u04d2\u04d7\u04dcron;\u411arc\u803b\xca\u40ca;\u442dot;\u4116r;\uc000\ud835\udd08rave\u803b\xc8\u40c8ement;\u6208\u0100ap\u04fa\u04fecr;\u4112ty\u0253\u0506\0\0\u0512mallSquare;\u65fberySmallSquare;\u65ab\u0100gp\u0526\u052aon;\u4118f;\uc000\ud835\udd3csilon;\u4395u\u0100ai\u053c\u0549l\u0100;T\u0542\u0543\u6a75ilde;\u6242librium;\u61cc\u0100ci\u0557\u055ar;\u6130m;\u6a73a;\u4397ml\u803b\xcb\u40cb\u0100ip\u056a\u056fsts;\u6203onentialE;\u6147\u0280cfios\u0585\u0588\u058d\u05b2\u05ccy;\u4424r;\uc000\ud835\udd09lled\u0253\u0597\0\0\u05a3mallSquare;\u65fcerySmallSquare;\u65aa\u0370\u05ba\0\u05bf\0\0\u05c4f;\uc000\ud835\udd3dAll;\u6200riertrf;\u6131c\xf2\u05cb\u0600JTabcdfgorst\u05e8\u05ec\u05ef\u05fa\u0600\u0612\u0616\u061b\u061d\u0623\u066c\u0672cy;\u4403\u803b>\u403emma\u0100;d\u05f7\u05f8\u4393;\u43dcreve;\u411e\u0180eiy\u0607\u060c\u0610dil;\u4122rc;\u411c;\u4413ot;\u4120r;\uc000\ud835\udd0a;\u62d9pf;\uc000\ud835\udd3eeater\u0300EFGLST\u0635\u0644\u064e\u0656\u065b\u0666qual\u0100;L\u063e\u063f\u6265ess;\u62dbullEqual;\u6267reater;\u6aa2ess;\u6277lantEqual;\u6a7eilde;\u6273cr;\uc000\ud835\udca2;\u626b\u0400Aacfiosu\u0685\u068b\u0696\u069b\u069e\u06aa\u06be\u06caRDcy;\u442a\u0100ct\u0690\u0694ek;\u42c7;\u405eirc;\u4124r;\u610clbertSpace;\u610b\u01f0\u06af\0\u06b2f;\u610dizontalLine;\u6500\u0100ct\u06c3\u06c5\xf2\u06a9rok;\u4126mp\u0144\u06d0\u06d8ownHum\xf0\u012fqual;\u624f\u0700EJOacdfgmnostu\u06fa\u06fe\u0703\u0707\u070e\u071a\u071e\u0721\u0728\u0744\u0778\u078b\u078f\u0795cy;\u4415lig;\u4132cy;\u4401cute\u803b\xcd\u40cd\u0100iy\u0713\u0718rc\u803b\xce\u40ce;\u4418ot;\u4130r;\u6111rave\u803b\xcc\u40cc\u0180;ap\u0720\u072f\u073f\u0100cg\u0734\u0737r;\u412ainaryI;\u6148lie\xf3\u03dd\u01f4\u0749\0\u0762\u0100;e\u074d\u074e\u622c\u0100gr\u0753\u0758ral;\u622bsection;\u62c2isible\u0100CT\u076c\u0772omma;\u6063imes;\u6062\u0180gpt\u077f\u0783\u0788on;\u412ef;\uc000\ud835\udd40a;\u4399cr;\u6110ilde;\u4128\u01eb\u079a\0\u079ecy;\u4406l\u803b\xcf\u40cf\u0280cfosu\u07ac\u07b7\u07bc\u07c2\u07d0\u0100iy\u07b1\u07b5rc;\u4134;\u4419r;\uc000\ud835\udd0dpf;\uc000\ud835\udd41\u01e3\u07c7\0\u07ccr;\uc000\ud835\udca5rcy;\u4408kcy;\u4404\u0380HJacfos\u07e4\u07e8\u07ec\u07f1\u07fd\u0802\u0808cy;\u4425cy;\u440cppa;\u439a\u0100ey\u07f6\u07fbdil;\u4136;\u441ar;\uc000\ud835\udd0epf;\uc000\ud835\udd42cr;\uc000\ud835\udca6\u0580JTaceflmost\u0825\u0829\u082c\u0850\u0863\u09b3\u09b8\u09c7\u09cd\u0a37\u0a47cy;\u4409\u803b<\u403c\u0280cmnpr\u0837\u083c\u0841\u0844\u084dute;\u4139bda;\u439bg;\u67ealacetrf;\u6112r;\u619e\u0180aey\u0857\u085c\u0861ron;\u413ddil;\u413b;\u441b\u0100fs\u0868\u0970t\u0500ACDFRTUVar\u087e\u08a9\u08b1\u08e0\u08e6\u08fc\u092f\u095b\u0390\u096a\u0100nr\u0883\u088fgleBracket;\u67e8row\u0180;BR\u0899\u089a\u089e\u6190ar;\u61e4ightArrow;\u61c6eiling;\u6308o\u01f5\u08b7\0\u08c3bleBracket;\u67e6n\u01d4\u08c8\0\u08d2eeVector;\u6961ector\u0100;B\u08db\u08dc\u61c3ar;\u6959loor;\u630aight\u0100AV\u08ef\u08f5rrow;\u6194ector;\u694e\u0100er\u0901\u0917e\u0180;AV\u0909\u090a\u0910\u62a3rrow;\u61a4ector;\u695aiangle\u0180;BE\u0924\u0925\u0929\u62b2ar;\u69cfqual;\u62b4p\u0180DTV\u0937\u0942\u094cownVector;\u6951eeVector;\u6960ector\u0100;B\u0956\u0957\u61bfar;\u6958ector\u0100;B\u0965\u0966\u61bcar;\u6952ight\xe1\u039cs\u0300EFGLST\u097e\u098b\u0995\u099d\u09a2\u09adqualGreater;\u62daullEqual;\u6266reater;\u6276ess;\u6aa1lantEqual;\u6a7dilde;\u6272r;\uc000\ud835\udd0f\u0100;e\u09bd\u09be\u62d8ftarrow;\u61daidot;\u413f\u0180npw\u09d4\u0a16\u0a1bg\u0200LRlr\u09de\u09f7\u0a02\u0a10eft\u0100AR\u09e6\u09ecrrow;\u67f5ightArrow;\u67f7ightArrow;\u67f6eft\u0100ar\u03b3\u0a0aight\xe1\u03bfight\xe1\u03caf;\uc000\ud835\udd43er\u0100LR\u0a22\u0a2ceftArrow;\u6199ightArrow;\u6198\u0180cht\u0a3e\u0a40\u0a42\xf2\u084c;\u61b0rok;\u4141;\u626a\u0400acefiosu\u0a5a\u0a5d\u0a60\u0a77\u0a7c\u0a85\u0a8b\u0a8ep;\u6905y;\u441c\u0100dl\u0a65\u0a6fiumSpace;\u605flintrf;\u6133r;\uc000\ud835\udd10nusPlus;\u6213pf;\uc000\ud835\udd44c\xf2\u0a76;\u439c\u0480Jacefostu\u0aa3\u0aa7\u0aad\u0ac0\u0b14\u0b19\u0d91\u0d97\u0d9ecy;\u440acute;\u4143\u0180aey\u0ab4\u0ab9\u0aberon;\u4147dil;\u4145;\u441d\u0180gsw\u0ac7\u0af0\u0b0eative\u0180MTV\u0ad3\u0adf\u0ae8ediumSpace;\u600bhi\u0100cn\u0ae6\u0ad8\xeb\u0ad9eryThi\xee\u0ad9ted\u0100GL\u0af8\u0b06reaterGreate\xf2\u0673essLes\xf3\u0a48Line;\u400ar;\uc000\ud835\udd11\u0200Bnpt\u0b22\u0b28\u0b37\u0b3areak;\u6060BreakingSpace;\u40a0f;\u6115\u0680;CDEGHLNPRSTV\u0b55\u0b56\u0b6a\u0b7c\u0ba1\u0beb\u0c04\u0c5e\u0c84\u0ca6\u0cd8\u0d61\u0d85\u6aec\u0100ou\u0b5b\u0b64ngruent;\u6262pCap;\u626doubleVerticalBar;\u6226\u0180lqx\u0b83\u0b8a\u0b9bement;\u6209ual\u0100;T\u0b92\u0b93\u6260ilde;\uc000\u2242\u0338ists;\u6204reater\u0380;EFGLST\u0bb6\u0bb7\u0bbd\u0bc9\u0bd3\u0bd8\u0be5\u626fqual;\u6271ullEqual;\uc000\u2267\u0338reater;\uc000\u226b\u0338ess;\u6279lantEqual;\uc000\u2a7e\u0338ilde;\u6275ump\u0144\u0bf2\u0bfdownHump;\uc000\u224e\u0338qual;\uc000\u224f\u0338e\u0100fs\u0c0a\u0c27tTriangle\u0180;BE\u0c1a\u0c1b\u0c21\u62eaar;\uc000\u29cf\u0338qual;\u62ecs\u0300;EGLST\u0c35\u0c36\u0c3c\u0c44\u0c4b\u0c58\u626equal;\u6270reater;\u6278ess;\uc000\u226a\u0338lantEqual;\uc000\u2a7d\u0338ilde;\u6274ested\u0100GL\u0c68\u0c79reaterGreater;\uc000\u2aa2\u0338essLess;\uc000\u2aa1\u0338recedes\u0180;ES\u0c92\u0c93\u0c9b\u6280qual;\uc000\u2aaf\u0338lantEqual;\u62e0\u0100ei\u0cab\u0cb9verseElement;\u620cghtTriangle\u0180;BE\u0ccb\u0ccc\u0cd2\u62ebar;\uc000\u29d0\u0338qual;\u62ed\u0100qu\u0cdd\u0d0cuareSu\u0100bp\u0ce8\u0cf9set\u0100;E\u0cf0\u0cf3\uc000\u228f\u0338qual;\u62e2erset\u0100;E\u0d03\u0d06\uc000\u2290\u0338qual;\u62e3\u0180bcp\u0d13\u0d24\u0d4eset\u0100;E\u0d1b\u0d1e\uc000\u2282\u20d2qual;\u6288ceeds\u0200;EST\u0d32\u0d33\u0d3b\u0d46\u6281qual;\uc000\u2ab0\u0338lantEqual;\u62e1ilde;\uc000\u227f\u0338erset\u0100;E\u0d58\u0d5b\uc000\u2283\u20d2qual;\u6289ilde\u0200;EFT\u0d6e\u0d6f\u0d75\u0d7f\u6241qual;\u6244ullEqual;\u6247ilde;\u6249erticalBar;\u6224cr;\uc000\ud835\udca9ilde\u803b\xd1\u40d1;\u439d\u0700Eacdfgmoprstuv\u0dbd\u0dc2\u0dc9\u0dd5\u0ddb\u0de0\u0de7\u0dfc\u0e02\u0e20\u0e22\u0e32\u0e3f\u0e44lig;\u4152cute\u803b\xd3\u40d3\u0100iy\u0dce\u0dd3rc\u803b\xd4\u40d4;\u441eblac;\u4150r;\uc000\ud835\udd12rave\u803b\xd2\u40d2\u0180aei\u0dee\u0df2\u0df6cr;\u414cga;\u43a9cron;\u439fpf;\uc000\ud835\udd46enCurly\u0100DQ\u0e0e\u0e1aoubleQuote;\u601cuote;\u6018;\u6a54\u0100cl\u0e27\u0e2cr;\uc000\ud835\udcaaash\u803b\xd8\u40d8i\u016c\u0e37\u0e3cde\u803b\xd5\u40d5es;\u6a37ml\u803b\xd6\u40d6er\u0100BP\u0e4b\u0e60\u0100ar\u0e50\u0e53r;\u603eac\u0100ek\u0e5a\u0e5c;\u63deet;\u63b4arenthesis;\u63dc\u0480acfhilors\u0e7f\u0e87\u0e8a\u0e8f\u0e92\u0e94\u0e9d\u0eb0\u0efcrtialD;\u6202y;\u441fr;\uc000\ud835\udd13i;\u43a6;\u43a0usMinus;\u40b1\u0100ip\u0ea2\u0eadncareplan\xe5\u069df;\u6119\u0200;eio\u0eb9\u0eba\u0ee0\u0ee4\u6abbcedes\u0200;EST\u0ec8\u0ec9\u0ecf\u0eda\u627aqual;\u6aaflantEqual;\u627cilde;\u627eme;\u6033\u0100dp\u0ee9\u0eeeuct;\u620fortion\u0100;a\u0225\u0ef9l;\u621d\u0100ci\u0f01\u0f06r;\uc000\ud835\udcab;\u43a8\u0200Ufos\u0f11\u0f16\u0f1b\u0f1fOT\u803b\"\u4022r;\uc000\ud835\udd14pf;\u611acr;\uc000\ud835\udcac\u0600BEacefhiorsu\u0f3e\u0f43\u0f47\u0f60\u0f73\u0fa7\u0faa\u0fad\u1096\u10a9\u10b4\u10bearr;\u6910G\u803b\xae\u40ae\u0180cnr\u0f4e\u0f53\u0f56ute;\u4154g;\u67ebr\u0100;t\u0f5c\u0f5d\u61a0l;\u6916\u0180aey\u0f67\u0f6c\u0f71ron;\u4158dil;\u4156;\u4420\u0100;v\u0f78\u0f79\u611cerse\u0100EU\u0f82\u0f99\u0100lq\u0f87\u0f8eement;\u620builibrium;\u61cbpEquilibrium;\u696fr\xbb\u0f79o;\u43a1ght\u0400ACDFTUVa\u0fc1\u0feb\u0ff3\u1022\u1028\u105b\u1087\u03d8\u0100nr\u0fc6\u0fd2gleBracket;\u67e9row\u0180;BL\u0fdc\u0fdd\u0fe1\u6192ar;\u61e5eftArrow;\u61c4eiling;\u6309o\u01f5\u0ff9\0\u1005bleBracket;\u67e7n\u01d4\u100a\0\u1014eeVector;\u695dector\u0100;B\u101d\u101e\u61c2ar;\u6955loor;\u630b\u0100er\u102d\u1043e\u0180;AV\u1035\u1036\u103c\u62a2rrow;\u61a6ector;\u695biangle\u0180;BE\u1050\u1051\u1055\u62b3ar;\u69d0qual;\u62b5p\u0180DTV\u1063\u106e\u1078ownVector;\u694feeVector;\u695cector\u0100;B\u1082\u1083\u61bear;\u6954ector\u0100;B\u1091\u1092\u61c0ar;\u6953\u0100pu\u109b\u109ef;\u611dndImplies;\u6970ightarrow;\u61db\u0100ch\u10b9\u10bcr;\u611b;\u61b1leDelayed;\u69f4\u0680HOacfhimoqstu\u10e4\u10f1\u10f7\u10fd\u1119\u111e\u1151\u1156\u1161\u1167\u11b5\u11bb\u11bf\u0100Cc\u10e9\u10eeHcy;\u4429y;\u4428FTcy;\u442ccute;\u415a\u0280;aeiy\u1108\u1109\u110e\u1113\u1117\u6abcron;\u4160dil;\u415erc;\u415c;\u4421r;\uc000\ud835\udd16ort\u0200DLRU\u112a\u1134\u113e\u1149ownArrow\xbb\u041eeftArrow\xbb\u089aightArrow\xbb\u0fddpArrow;\u6191gma;\u43a3allCircle;\u6218pf;\uc000\ud835\udd4a\u0272\u116d\0\0\u1170t;\u621aare\u0200;ISU\u117b\u117c\u1189\u11af\u65a1ntersection;\u6293u\u0100bp\u118f\u119eset\u0100;E\u1197\u1198\u628fqual;\u6291erset\u0100;E\u11a8\u11a9\u6290qual;\u6292nion;\u6294cr;\uc000\ud835\udcaear;\u62c6\u0200bcmp\u11c8\u11db\u1209\u120b\u0100;s\u11cd\u11ce\u62d0et\u0100;E\u11cd\u11d5qual;\u6286\u0100ch\u11e0\u1205eeds\u0200;EST\u11ed\u11ee\u11f4\u11ff\u627bqual;\u6ab0lantEqual;\u627dilde;\u627fTh\xe1\u0f8c;\u6211\u0180;es\u1212\u1213\u1223\u62d1rset\u0100;E\u121c\u121d\u6283qual;\u6287et\xbb\u1213\u0580HRSacfhiors\u123e\u1244\u1249\u1255\u125e\u1271\u1276\u129f\u12c2\u12c8\u12d1ORN\u803b\xde\u40deADE;\u6122\u0100Hc\u124e\u1252cy;\u440by;\u4426\u0100bu\u125a\u125c;\u4009;\u43a4\u0180aey\u1265\u126a\u126fron;\u4164dil;\u4162;\u4422r;\uc000\ud835\udd17\u0100ei\u127b\u1289\u01f2\u1280\0\u1287efore;\u6234a;\u4398\u0100cn\u128e\u1298kSpace;\uc000\u205f\u200aSpace;\u6009lde\u0200;EFT\u12ab\u12ac\u12b2\u12bc\u623cqual;\u6243ullEqual;\u6245ilde;\u6248pf;\uc000\ud835\udd4bipleDot;\u60db\u0100ct\u12d6\u12dbr;\uc000\ud835\udcafrok;\u4166\u0ae1\u12f7\u130e\u131a\u1326\0\u132c\u1331\0\0\0\0\0\u1338\u133d\u1377\u1385\0\u13ff\u1404\u140a\u1410\u0100cr\u12fb\u1301ute\u803b\xda\u40dar\u0100;o\u1307\u1308\u619fcir;\u6949r\u01e3\u1313\0\u1316y;\u440eve;\u416c\u0100iy\u131e\u1323rc\u803b\xdb\u40db;\u4423blac;\u4170r;\uc000\ud835\udd18rave\u803b\xd9\u40d9acr;\u416a\u0100di\u1341\u1369er\u0100BP\u1348\u135d\u0100ar\u134d\u1350r;\u405fac\u0100ek\u1357\u1359;\u63dfet;\u63b5arenthesis;\u63ddon\u0100;P\u1370\u1371\u62c3lus;\u628e\u0100gp\u137b\u137fon;\u4172f;\uc000\ud835\udd4c\u0400ADETadps\u1395\u13ae\u13b8\u13c4\u03e8\u13d2\u13d7\u13f3rrow\u0180;BD\u1150\u13a0\u13a4ar;\u6912ownArrow;\u61c5ownArrow;\u6195quilibrium;\u696eee\u0100;A\u13cb\u13cc\u62a5rrow;\u61a5own\xe1\u03f3er\u0100LR\u13de\u13e8eftArrow;\u6196ightArrow;\u6197i\u0100;l\u13f9\u13fa\u43d2on;\u43a5ing;\u416ecr;\uc000\ud835\udcb0ilde;\u4168ml\u803b\xdc\u40dc\u0480Dbcdefosv\u1427\u142c\u1430\u1433\u143e\u1485\u148a\u1490\u1496ash;\u62abar;\u6aeby;\u4412ash\u0100;l\u143b\u143c\u62a9;\u6ae6\u0100er\u1443\u1445;\u62c1\u0180bty\u144c\u1450\u147aar;\u6016\u0100;i\u144f\u1455cal\u0200BLST\u1461\u1465\u146a\u1474ar;\u6223ine;\u407ceparator;\u6758ilde;\u6240ThinSpace;\u600ar;\uc000\ud835\udd19pf;\uc000\ud835\udd4dcr;\uc000\ud835\udcb1dash;\u62aa\u0280cefos\u14a7\u14ac\u14b1\u14b6\u14bcirc;\u4174dge;\u62c0r;\uc000\ud835\udd1apf;\uc000\ud835\udd4ecr;\uc000\ud835\udcb2\u0200fios\u14cb\u14d0\u14d2\u14d8r;\uc000\ud835\udd1b;\u439epf;\uc000\ud835\udd4fcr;\uc000\ud835\udcb3\u0480AIUacfosu\u14f1\u14f5\u14f9\u14fd\u1504\u150f\u1514\u151a\u1520cy;\u442fcy;\u4407cy;\u442ecute\u803b\xdd\u40dd\u0100iy\u1509\u150drc;\u4176;\u442br;\uc000\ud835\udd1cpf;\uc000\ud835\udd50cr;\uc000\ud835\udcb4ml;\u4178\u0400Hacdefos\u1535\u1539\u153f\u154b\u154f\u155d\u1560\u1564cy;\u4416cute;\u4179\u0100ay\u1544\u1549ron;\u417d;\u4417ot;\u417b\u01f2\u1554\0\u155boWidt\xe8\u0ad9a;\u4396r;\u6128pf;\u6124cr;\uc000\ud835\udcb5\u0be1\u1583\u158a\u1590\0\u15b0\u15b6\u15bf\0\0\0\0\u15c6\u15db\u15eb\u165f\u166d\0\u1695\u169b\u16b2\u16b9\0\u16becute\u803b\xe1\u40e1reve;\u4103\u0300;Ediuy\u159c\u159d\u15a1\u15a3\u15a8\u15ad\u623e;\uc000\u223e\u0333;\u623frc\u803b\xe2\u40e2te\u80bb\xb4\u0306;\u4430lig\u803b\xe6\u40e6\u0100;r\xb2\u15ba;\uc000\ud835\udd1erave\u803b\xe0\u40e0\u0100ep\u15ca\u15d6\u0100fp\u15cf\u15d4sym;\u6135\xe8\u15d3ha;\u43b1\u0100ap\u15dfc\u0100cl\u15e4\u15e7r;\u4101g;\u6a3f\u0264\u15f0\0\0\u160a\u0280;adsv\u15fa\u15fb\u15ff\u1601\u1607\u6227nd;\u6a55;\u6a5clope;\u6a58;\u6a5a\u0380;elmrsz\u1618\u1619\u161b\u161e\u163f\u164f\u1659\u6220;\u69a4e\xbb\u1619sd\u0100;a\u1625\u1626\u6221\u0461\u1630\u1632\u1634\u1636\u1638\u163a\u163c\u163e;\u69a8;\u69a9;\u69aa;\u69ab;\u69ac;\u69ad;\u69ae;\u69aft\u0100;v\u1645\u1646\u621fb\u0100;d\u164c\u164d\u62be;\u699d\u0100pt\u1654\u1657h;\u6222\xbb\xb9arr;\u637c\u0100gp\u1663\u1667on;\u4105f;\uc000\ud835\udd52\u0380;Eaeiop\u12c1\u167b\u167d\u1682\u1684\u1687\u168a;\u6a70cir;\u6a6f;\u624ad;\u624bs;\u4027rox\u0100;e\u12c1\u1692\xf1\u1683ing\u803b\xe5\u40e5\u0180cty\u16a1\u16a6\u16a8r;\uc000\ud835\udcb6;\u402amp\u0100;e\u12c1\u16af\xf1\u0288ilde\u803b\xe3\u40e3ml\u803b\xe4\u40e4\u0100ci\u16c2\u16c8onin\xf4\u0272nt;\u6a11\u0800Nabcdefiklnoprsu\u16ed\u16f1\u1730\u173c\u1743\u1748\u1778\u177d\u17e0\u17e6\u1839\u1850\u170d\u193d\u1948\u1970ot;\u6aed\u0100cr\u16f6\u171ek\u0200ceps\u1700\u1705\u170d\u1713ong;\u624cpsilon;\u43f6rime;\u6035im\u0100;e\u171a\u171b\u623dq;\u62cd\u0176\u1722\u1726ee;\u62bded\u0100;g\u172c\u172d\u6305e\xbb\u172drk\u0100;t\u135c\u1737brk;\u63b6\u0100oy\u1701\u1741;\u4431quo;\u601e\u0280cmprt\u1753\u175b\u1761\u1764\u1768aus\u0100;e\u010a\u0109ptyv;\u69b0s\xe9\u170cno\xf5\u0113\u0180ahw\u176f\u1771\u1773;\u43b2;\u6136een;\u626cr;\uc000\ud835\udd1fg\u0380costuvw\u178d\u179d\u17b3\u17c1\u17d5\u17db\u17de\u0180aiu\u1794\u1796\u179a\xf0\u0760rc;\u65efp\xbb\u1371\u0180dpt\u17a4\u17a8\u17adot;\u6a00lus;\u6a01imes;\u6a02\u0271\u17b9\0\0\u17becup;\u6a06ar;\u6605riangle\u0100du\u17cd\u17d2own;\u65bdp;\u65b3plus;\u6a04e\xe5\u1444\xe5\u14adarow;\u690d\u0180ako\u17ed\u1826\u1835\u0100cn\u17f2\u1823k\u0180lst\u17fa\u05ab\u1802ozenge;\u69ebriangle\u0200;dlr\u1812\u1813\u1818\u181d\u65b4own;\u65beeft;\u65c2ight;\u65b8k;\u6423\u01b1\u182b\0\u1833\u01b2\u182f\0\u1831;\u6592;\u65914;\u6593ck;\u6588\u0100eo\u183e\u184d\u0100;q\u1843\u1846\uc000=\u20e5uiv;\uc000\u2261\u20e5t;\u6310\u0200ptwx\u1859\u185e\u1867\u186cf;\uc000\ud835\udd53\u0100;t\u13cb\u1863om\xbb\u13cctie;\u62c8\u0600DHUVbdhmptuv\u1885\u1896\u18aa\u18bb\u18d7\u18db\u18ec\u18ff\u1905\u190a\u1910\u1921\u0200LRlr\u188e\u1890\u1892\u1894;\u6557;\u6554;\u6556;\u6553\u0280;DUdu\u18a1\u18a2\u18a4\u18a6\u18a8\u6550;\u6566;\u6569;\u6564;\u6567\u0200LRlr\u18b3\u18b5\u18b7\u18b9;\u655d;\u655a;\u655c;\u6559\u0380;HLRhlr\u18ca\u18cb\u18cd\u18cf\u18d1\u18d3\u18d5\u6551;\u656c;\u6563;\u6560;\u656b;\u6562;\u655fox;\u69c9\u0200LRlr\u18e4\u18e6\u18e8\u18ea;\u6555;\u6552;\u6510;\u650c\u0280;DUdu\u06bd\u18f7\u18f9\u18fb\u18fd;\u6565;\u6568;\u652c;\u6534inus;\u629flus;\u629eimes;\u62a0\u0200LRlr\u1919\u191b\u191d\u191f;\u655b;\u6558;\u6518;\u6514\u0380;HLRhlr\u1930\u1931\u1933\u1935\u1937\u1939\u193b\u6502;\u656a;\u6561;\u655e;\u653c;\u6524;\u651c\u0100ev\u0123\u1942bar\u803b\xa6\u40a6\u0200ceio\u1951\u1956\u195a\u1960r;\uc000\ud835\udcb7mi;\u604fm\u0100;e\u171a\u171cl\u0180;bh\u1968\u1969\u196b\u405c;\u69c5sub;\u67c8\u016c\u1974\u197el\u0100;e\u1979\u197a\u6022t\xbb\u197ap\u0180;Ee\u012f\u1985\u1987;\u6aae\u0100;q\u06dc\u06db\u0ce1\u19a7\0\u19e8\u1a11\u1a15\u1a32\0\u1a37\u1a50\0\0\u1ab4\0\0\u1ac1\0\0\u1b21\u1b2e\u1b4d\u1b52\0\u1bfd\0\u1c0c\u0180cpr\u19ad\u19b2\u19ddute;\u4107\u0300;abcds\u19bf\u19c0\u19c4\u19ca\u19d5\u19d9\u6229nd;\u6a44rcup;\u6a49\u0100au\u19cf\u19d2p;\u6a4bp;\u6a47ot;\u6a40;\uc000\u2229\ufe00\u0100eo\u19e2\u19e5t;\u6041\xee\u0693\u0200aeiu\u19f0\u19fb\u1a01\u1a05\u01f0\u19f5\0\u19f8s;\u6a4don;\u410ddil\u803b\xe7\u40e7rc;\u4109ps\u0100;s\u1a0c\u1a0d\u6a4cm;\u6a50ot;\u410b\u0180dmn\u1a1b\u1a20\u1a26il\u80bb\xb8\u01adptyv;\u69b2t\u8100\xa2;e\u1a2d\u1a2e\u40a2r\xe4\u01b2r;\uc000\ud835\udd20\u0180cei\u1a3d\u1a40\u1a4dy;\u4447ck\u0100;m\u1a47\u1a48\u6713ark\xbb\u1a48;\u43c7r\u0380;Ecefms\u1a5f\u1a60\u1a62\u1a6b\u1aa4\u1aaa\u1aae\u65cb;\u69c3\u0180;el\u1a69\u1a6a\u1a6d\u42c6q;\u6257e\u0261\u1a74\0\0\u1a88rrow\u0100lr\u1a7c\u1a81eft;\u61baight;\u61bb\u0280RSacd\u1a92\u1a94\u1a96\u1a9a\u1a9f\xbb\u0f47;\u64c8st;\u629birc;\u629aash;\u629dnint;\u6a10id;\u6aefcir;\u69c2ubs\u0100;u\u1abb\u1abc\u6663it\xbb\u1abc\u02ec\u1ac7\u1ad4\u1afa\0\u1b0aon\u0100;e\u1acd\u1ace\u403a\u0100;q\xc7\xc6\u026d\u1ad9\0\0\u1ae2a\u0100;t\u1ade\u1adf\u402c;\u4040\u0180;fl\u1ae8\u1ae9\u1aeb\u6201\xee\u1160e\u0100mx\u1af1\u1af6ent\xbb\u1ae9e\xf3\u024d\u01e7\u1afe\0\u1b07\u0100;d\u12bb\u1b02ot;\u6a6dn\xf4\u0246\u0180fry\u1b10\u1b14\u1b17;\uc000\ud835\udd54o\xe4\u0254\u8100\xa9;s\u0155\u1b1dr;\u6117\u0100ao\u1b25\u1b29rr;\u61b5ss;\u6717\u0100cu\u1b32\u1b37r;\uc000\ud835\udcb8\u0100bp\u1b3c\u1b44\u0100;e\u1b41\u1b42\u6acf;\u6ad1\u0100;e\u1b49\u1b4a\u6ad0;\u6ad2dot;\u62ef\u0380delprvw\u1b60\u1b6c\u1b77\u1b82\u1bac\u1bd4\u1bf9arr\u0100lr\u1b68\u1b6a;\u6938;\u6935\u0270\u1b72\0\0\u1b75r;\u62dec;\u62dfarr\u0100;p\u1b7f\u1b80\u61b6;\u693d\u0300;bcdos\u1b8f\u1b90\u1b96\u1ba1\u1ba5\u1ba8\u622arcap;\u6a48\u0100au\u1b9b\u1b9ep;\u6a46p;\u6a4aot;\u628dr;\u6a45;\uc000\u222a\ufe00\u0200alrv\u1bb5\u1bbf\u1bde\u1be3rr\u0100;m\u1bbc\u1bbd\u61b7;\u693cy\u0180evw\u1bc7\u1bd4\u1bd8q\u0270\u1bce\0\0\u1bd2re\xe3\u1b73u\xe3\u1b75ee;\u62ceedge;\u62cfen\u803b\xa4\u40a4earrow\u0100lr\u1bee\u1bf3eft\xbb\u1b80ight\xbb\u1bbde\xe4\u1bdd\u0100ci\u1c01\u1c07onin\xf4\u01f7nt;\u6231lcty;\u632d\u0980AHabcdefhijlorstuwz\u1c38\u1c3b\u1c3f\u1c5d\u1c69\u1c75\u1c8a\u1c9e\u1cac\u1cb7\u1cfb\u1cff\u1d0d\u1d7b\u1d91\u1dab\u1dbb\u1dc6\u1dcdr\xf2\u0381ar;\u6965\u0200glrs\u1c48\u1c4d\u1c52\u1c54ger;\u6020eth;\u6138\xf2\u1133h\u0100;v\u1c5a\u1c5b\u6010\xbb\u090a\u016b\u1c61\u1c67arow;\u690fa\xe3\u0315\u0100ay\u1c6e\u1c73ron;\u410f;\u4434\u0180;ao\u0332\u1c7c\u1c84\u0100gr\u02bf\u1c81r;\u61catseq;\u6a77\u0180glm\u1c91\u1c94\u1c98\u803b\xb0\u40b0ta;\u43b4ptyv;\u69b1\u0100ir\u1ca3\u1ca8sht;\u697f;\uc000\ud835\udd21ar\u0100lr\u1cb3\u1cb5\xbb\u08dc\xbb\u101e\u0280aegsv\u1cc2\u0378\u1cd6\u1cdc\u1ce0m\u0180;os\u0326\u1cca\u1cd4nd\u0100;s\u0326\u1cd1uit;\u6666amma;\u43ddin;\u62f2\u0180;io\u1ce7\u1ce8\u1cf8\u40f7de\u8100\xf7;o\u1ce7\u1cf0ntimes;\u62c7n\xf8\u1cf7cy;\u4452c\u026f\u1d06\0\0\u1d0arn;\u631eop;\u630d\u0280lptuw\u1d18\u1d1d\u1d22\u1d49\u1d55lar;\u4024f;\uc000\ud835\udd55\u0280;emps\u030b\u1d2d\u1d37\u1d3d\u1d42q\u0100;d\u0352\u1d33ot;\u6251inus;\u6238lus;\u6214quare;\u62a1blebarwedg\xe5\xfan\u0180adh\u112e\u1d5d\u1d67ownarrow\xf3\u1c83arpoon\u0100lr\u1d72\u1d76ef\xf4\u1cb4igh\xf4\u1cb6\u0162\u1d7f\u1d85karo\xf7\u0f42\u026f\u1d8a\0\0\u1d8ern;\u631fop;\u630c\u0180cot\u1d98\u1da3\u1da6\u0100ry\u1d9d\u1da1;\uc000\ud835\udcb9;\u4455l;\u69f6rok;\u4111\u0100dr\u1db0\u1db4ot;\u62f1i\u0100;f\u1dba\u1816\u65bf\u0100ah\u1dc0\u1dc3r\xf2\u0429a\xf2\u0fa6angle;\u69a6\u0100ci\u1dd2\u1dd5y;\u445fgrarr;\u67ff\u0900Dacdefglmnopqrstux\u1e01\u1e09\u1e19\u1e38\u0578\u1e3c\u1e49\u1e61\u1e7e\u1ea5\u1eaf\u1ebd\u1ee1\u1f2a\u1f37\u1f44\u1f4e\u1f5a\u0100Do\u1e06\u1d34o\xf4\u1c89\u0100cs\u1e0e\u1e14ute\u803b\xe9\u40e9ter;\u6a6e\u0200aioy\u1e22\u1e27\u1e31\u1e36ron;\u411br\u0100;c\u1e2d\u1e2e\u6256\u803b\xea\u40ealon;\u6255;\u444dot;\u4117\u0100Dr\u1e41\u1e45ot;\u6252;\uc000\ud835\udd22\u0180;rs\u1e50\u1e51\u1e57\u6a9aave\u803b\xe8\u40e8\u0100;d\u1e5c\u1e5d\u6a96ot;\u6a98\u0200;ils\u1e6a\u1e6b\u1e72\u1e74\u6a99nters;\u63e7;\u6113\u0100;d\u1e79\u1e7a\u6a95ot;\u6a97\u0180aps\u1e85\u1e89\u1e97cr;\u4113ty\u0180;sv\u1e92\u1e93\u1e95\u6205et\xbb\u1e93p\u01001;\u1e9d\u1ea4\u0133\u1ea1\u1ea3;\u6004;\u6005\u6003\u0100gs\u1eaa\u1eac;\u414bp;\u6002\u0100gp\u1eb4\u1eb8on;\u4119f;\uc000\ud835\udd56\u0180als\u1ec4\u1ece\u1ed2r\u0100;s\u1eca\u1ecb\u62d5l;\u69e3us;\u6a71i\u0180;lv\u1eda\u1edb\u1edf\u43b5on\xbb\u1edb;\u43f5\u0200csuv\u1eea\u1ef3\u1f0b\u1f23\u0100io\u1eef\u1e31rc\xbb\u1e2e\u0269\u1ef9\0\0\u1efb\xed\u0548ant\u0100gl\u1f02\u1f06tr\xbb\u1e5dess\xbb\u1e7a\u0180aei\u1f12\u1f16\u1f1als;\u403dst;\u625fv\u0100;D\u0235\u1f20D;\u6a78parsl;\u69e5\u0100Da\u1f2f\u1f33ot;\u6253rr;\u6971\u0180cdi\u1f3e\u1f41\u1ef8r;\u612fo\xf4\u0352\u0100ah\u1f49\u1f4b;\u43b7\u803b\xf0\u40f0\u0100mr\u1f53\u1f57l\u803b\xeb\u40ebo;\u60ac\u0180cip\u1f61\u1f64\u1f67l;\u4021s\xf4\u056e\u0100eo\u1f6c\u1f74ctatio\xee\u0559nential\xe5\u0579\u09e1\u1f92\0\u1f9e\0\u1fa1\u1fa7\0\0\u1fc6\u1fcc\0\u1fd3\0\u1fe6\u1fea\u2000\0\u2008\u205allingdotse\xf1\u1e44y;\u4444male;\u6640\u0180ilr\u1fad\u1fb3\u1fc1lig;\u8000\ufb03\u0269\u1fb9\0\0\u1fbdg;\u8000\ufb00ig;\u8000\ufb04;\uc000\ud835\udd23lig;\u8000\ufb01lig;\uc000fj\u0180alt\u1fd9\u1fdc\u1fe1t;\u666dig;\u8000\ufb02ns;\u65b1of;\u4192\u01f0\u1fee\0\u1ff3f;\uc000\ud835\udd57\u0100ak\u05bf\u1ff7\u0100;v\u1ffc\u1ffd\u62d4;\u6ad9artint;\u6a0d\u0100ao\u200c\u2055\u0100cs\u2011\u2052\u03b1\u201a\u2030\u2038\u2045\u2048\0\u2050\u03b2\u2022\u2025\u2027\u202a\u202c\0\u202e\u803b\xbd\u40bd;\u6153\u803b\xbc\u40bc;\u6155;\u6159;\u615b\u01b3\u2034\0\u2036;\u6154;\u6156\u02b4\u203e\u2041\0\0\u2043\u803b\xbe\u40be;\u6157;\u615c5;\u6158\u01b6\u204c\0\u204e;\u615a;\u615d8;\u615el;\u6044wn;\u6322cr;\uc000\ud835\udcbb\u0880Eabcdefgijlnorstv\u2082\u2089\u209f\u20a5\u20b0\u20b4\u20f0\u20f5\u20fa\u20ff\u2103\u2112\u2138\u0317\u213e\u2152\u219e\u0100;l\u064d\u2087;\u6a8c\u0180cmp\u2090\u2095\u209dute;\u41f5ma\u0100;d\u209c\u1cda\u43b3;\u6a86reve;\u411f\u0100iy\u20aa\u20aerc;\u411d;\u4433ot;\u4121\u0200;lqs\u063e\u0642\u20bd\u20c9\u0180;qs\u063e\u064c\u20c4lan\xf4\u0665\u0200;cdl\u0665\u20d2\u20d5\u20e5c;\u6aa9ot\u0100;o\u20dc\u20dd\u6a80\u0100;l\u20e2\u20e3\u6a82;\u6a84\u0100;e\u20ea\u20ed\uc000\u22db\ufe00s;\u6a94r;\uc000\ud835\udd24\u0100;g\u0673\u061bmel;\u6137cy;\u4453\u0200;Eaj\u065a\u210c\u210e\u2110;\u6a92;\u6aa5;\u6aa4\u0200Eaes\u211b\u211d\u2129\u2134;\u6269p\u0100;p\u2123\u2124\u6a8arox\xbb\u2124\u0100;q\u212e\u212f\u6a88\u0100;q\u212e\u211bim;\u62e7pf;\uc000\ud835\udd58\u0100ci\u2143\u2146r;\u610am\u0180;el\u066b\u214e\u2150;\u6a8e;\u6a90\u8300>;cdlqr\u05ee\u2160\u216a\u216e\u2173\u2179\u0100ci\u2165\u2167;\u6aa7r;\u6a7aot;\u62d7Par;\u6995uest;\u6a7c\u0280adels\u2184\u216a\u2190\u0656\u219b\u01f0\u2189\0\u218epro\xf8\u209er;\u6978q\u0100lq\u063f\u2196les\xf3\u2088i\xed\u066b\u0100en\u21a3\u21adrtneqq;\uc000\u2269\ufe00\xc5\u21aa\u0500Aabcefkosy\u21c4\u21c7\u21f1\u21f5\u21fa\u2218\u221d\u222f\u2268\u227dr\xf2\u03a0\u0200ilmr\u21d0\u21d4\u21d7\u21dbrs\xf0\u1484f\xbb\u2024il\xf4\u06a9\u0100dr\u21e0\u21e4cy;\u444a\u0180;cw\u08f4\u21eb\u21efir;\u6948;\u61adar;\u610firc;\u4125\u0180alr\u2201\u220e\u2213rts\u0100;u\u2209\u220a\u6665it\xbb\u220alip;\u6026con;\u62b9r;\uc000\ud835\udd25s\u0100ew\u2223\u2229arow;\u6925arow;\u6926\u0280amopr\u223a\u223e\u2243\u225e\u2263rr;\u61fftht;\u623bk\u0100lr\u2249\u2253eftarrow;\u61a9ightarrow;\u61aaf;\uc000\ud835\udd59bar;\u6015\u0180clt\u226f\u2274\u2278r;\uc000\ud835\udcbdas\xe8\u21f4rok;\u4127\u0100bp\u2282\u2287ull;\u6043hen\xbb\u1c5b\u0ae1\u22a3\0\u22aa\0\u22b8\u22c5\u22ce\0\u22d5\u22f3\0\0\u22f8\u2322\u2367\u2362\u237f\0\u2386\u23aa\u23b4cute\u803b\xed\u40ed\u0180;iy\u0771\u22b0\u22b5rc\u803b\xee\u40ee;\u4438\u0100cx\u22bc\u22bfy;\u4435cl\u803b\xa1\u40a1\u0100fr\u039f\u22c9;\uc000\ud835\udd26rave\u803b\xec\u40ec\u0200;ino\u073e\u22dd\u22e9\u22ee\u0100in\u22e2\u22e6nt;\u6a0ct;\u622dfin;\u69dcta;\u6129lig;\u4133\u0180aop\u22fe\u231a\u231d\u0180cgt\u2305\u2308\u2317r;\u412b\u0180elp\u071f\u230f\u2313in\xe5\u078ear\xf4\u0720h;\u4131f;\u62b7ed;\u41b5\u0280;cfot\u04f4\u232c\u2331\u233d\u2341are;\u6105in\u0100;t\u2338\u2339\u621eie;\u69dddo\xf4\u2319\u0280;celp\u0757\u234c\u2350\u235b\u2361al;\u62ba\u0100gr\u2355\u2359er\xf3\u1563\xe3\u234darhk;\u6a17rod;\u6a3c\u0200cgpt\u236f\u2372\u2376\u237by;\u4451on;\u412ff;\uc000\ud835\udd5aa;\u43b9uest\u803b\xbf\u40bf\u0100ci\u238a\u238fr;\uc000\ud835\udcben\u0280;Edsv\u04f4\u239b\u239d\u23a1\u04f3;\u62f9ot;\u62f5\u0100;v\u23a6\u23a7\u62f4;\u62f3\u0100;i\u0777\u23aelde;\u4129\u01eb\u23b8\0\u23bccy;\u4456l\u803b\xef\u40ef\u0300cfmosu\u23cc\u23d7\u23dc\u23e1\u23e7\u23f5\u0100iy\u23d1\u23d5rc;\u4135;\u4439r;\uc000\ud835\udd27ath;\u4237pf;\uc000\ud835\udd5b\u01e3\u23ec\0\u23f1r;\uc000\ud835\udcbfrcy;\u4458kcy;\u4454\u0400acfghjos\u240b\u2416\u2422\u2427\u242d\u2431\u2435\u243bppa\u0100;v\u2413\u2414\u43ba;\u43f0\u0100ey\u241b\u2420dil;\u4137;\u443ar;\uc000\ud835\udd28reen;\u4138cy;\u4445cy;\u445cpf;\uc000\ud835\udd5ccr;\uc000\ud835\udcc0\u0b80ABEHabcdefghjlmnoprstuv\u2470\u2481\u2486\u248d\u2491\u250e\u253d\u255a\u2580\u264e\u265e\u2665\u2679\u267d\u269a\u26b2\u26d8\u275d\u2768\u278b\u27c0\u2801\u2812\u0180art\u2477\u247a\u247cr\xf2\u09c6\xf2\u0395ail;\u691barr;\u690e\u0100;g\u0994\u248b;\u6a8bar;\u6962\u0963\u24a5\0\u24aa\0\u24b1\0\0\0\0\0\u24b5\u24ba\0\u24c6\u24c8\u24cd\0\u24f9ute;\u413amptyv;\u69b4ra\xee\u084cbda;\u43bbg\u0180;dl\u088e\u24c1\u24c3;\u6991\xe5\u088e;\u6a85uo\u803b\xab\u40abr\u0400;bfhlpst\u0899\u24de\u24e6\u24e9\u24eb\u24ee\u24f1\u24f5\u0100;f\u089d\u24e3s;\u691fs;\u691d\xeb\u2252p;\u61abl;\u6939im;\u6973l;\u61a2\u0180;ae\u24ff\u2500\u2504\u6aabil;\u6919\u0100;s\u2509\u250a\u6aad;\uc000\u2aad\ufe00\u0180abr\u2515\u2519\u251drr;\u690crk;\u6772\u0100ak\u2522\u252cc\u0100ek\u2528\u252a;\u407b;\u405b\u0100es\u2531\u2533;\u698bl\u0100du\u2539\u253b;\u698f;\u698d\u0200aeuy\u2546\u254b\u2556\u2558ron;\u413e\u0100di\u2550\u2554il;\u413c\xec\u08b0\xe2\u2529;\u443b\u0200cqrs\u2563\u2566\u256d\u257da;\u6936uo\u0100;r\u0e19\u1746\u0100du\u2572\u2577har;\u6967shar;\u694bh;\u61b2\u0280;fgqs\u258b\u258c\u0989\u25f3\u25ff\u6264t\u0280ahlrt\u2598\u25a4\u25b7\u25c2\u25e8rrow\u0100;t\u0899\u25a1a\xe9\u24f6arpoon\u0100du\u25af\u25b4own\xbb\u045ap\xbb\u0966eftarrows;\u61c7ight\u0180ahs\u25cd\u25d6\u25derrow\u0100;s\u08f4\u08a7arpoon\xf3\u0f98quigarro\xf7\u21f0hreetimes;\u62cb\u0180;qs\u258b\u0993\u25falan\xf4\u09ac\u0280;cdgs\u09ac\u260a\u260d\u261d\u2628c;\u6aa8ot\u0100;o\u2614\u2615\u6a7f\u0100;r\u261a\u261b\u6a81;\u6a83\u0100;e\u2622\u2625\uc000\u22da\ufe00s;\u6a93\u0280adegs\u2633\u2639\u263d\u2649\u264bppro\xf8\u24c6ot;\u62d6q\u0100gq\u2643\u2645\xf4\u0989gt\xf2\u248c\xf4\u099bi\xed\u09b2\u0180ilr\u2655\u08e1\u265asht;\u697c;\uc000\ud835\udd29\u0100;E\u099c\u2663;\u6a91\u0161\u2669\u2676r\u0100du\u25b2\u266e\u0100;l\u0965\u2673;\u696alk;\u6584cy;\u4459\u0280;acht\u0a48\u2688\u268b\u2691\u2696r\xf2\u25c1orne\xf2\u1d08ard;\u696bri;\u65fa\u0100io\u269f\u26a4dot;\u4140ust\u0100;a\u26ac\u26ad\u63b0che\xbb\u26ad\u0200Eaes\u26bb\u26bd\u26c9\u26d4;\u6268p\u0100;p\u26c3\u26c4\u6a89rox\xbb\u26c4\u0100;q\u26ce\u26cf\u6a87\u0100;q\u26ce\u26bbim;\u62e6\u0400abnoptwz\u26e9\u26f4\u26f7\u271a\u272f\u2741\u2747\u2750\u0100nr\u26ee\u26f1g;\u67ecr;\u61fdr\xeb\u08c1g\u0180lmr\u26ff\u270d\u2714eft\u0100ar\u09e6\u2707ight\xe1\u09f2apsto;\u67fcight\xe1\u09fdparrow\u0100lr\u2725\u2729ef\xf4\u24edight;\u61ac\u0180afl\u2736\u2739\u273dr;\u6985;\uc000\ud835\udd5dus;\u6a2dimes;\u6a34\u0161\u274b\u274fst;\u6217\xe1\u134e\u0180;ef\u2757\u2758\u1800\u65cange\xbb\u2758ar\u0100;l\u2764\u2765\u4028t;\u6993\u0280achmt\u2773\u2776\u277c\u2785\u2787r\xf2\u08a8orne\xf2\u1d8car\u0100;d\u0f98\u2783;\u696d;\u600eri;\u62bf\u0300achiqt\u2798\u279d\u0a40\u27a2\u27ae\u27bbquo;\u6039r;\uc000\ud835\udcc1m\u0180;eg\u09b2\u27aa\u27ac;\u6a8d;\u6a8f\u0100bu\u252a\u27b3o\u0100;r\u0e1f\u27b9;\u601arok;\u4142\u8400<;cdhilqr\u082b\u27d2\u2639\u27dc\u27e0\u27e5\u27ea\u27f0\u0100ci\u27d7\u27d9;\u6aa6r;\u6a79re\xe5\u25f2mes;\u62c9arr;\u6976uest;\u6a7b\u0100Pi\u27f5\u27f9ar;\u6996\u0180;ef\u2800\u092d\u181b\u65c3r\u0100du\u2807\u280dshar;\u694ahar;\u6966\u0100en\u2817\u2821rtneqq;\uc000\u2268\ufe00\xc5\u281e\u0700Dacdefhilnopsu\u2840\u2845\u2882\u288e\u2893\u28a0\u28a5\u28a8\u28da\u28e2\u28e4\u0a83\u28f3\u2902Dot;\u623a\u0200clpr\u284e\u2852\u2863\u287dr\u803b\xaf\u40af\u0100et\u2857\u2859;\u6642\u0100;e\u285e\u285f\u6720se\xbb\u285f\u0100;s\u103b\u2868to\u0200;dlu\u103b\u2873\u2877\u287bow\xee\u048cef\xf4\u090f\xf0\u13d1ker;\u65ae\u0100oy\u2887\u288cmma;\u6a29;\u443cash;\u6014asuredangle\xbb\u1626r;\uc000\ud835\udd2ao;\u6127\u0180cdn\u28af\u28b4\u28c9ro\u803b\xb5\u40b5\u0200;acd\u1464\u28bd\u28c0\u28c4s\xf4\u16a7ir;\u6af0ot\u80bb\xb7\u01b5us\u0180;bd\u28d2\u1903\u28d3\u6212\u0100;u\u1d3c\u28d8;\u6a2a\u0163\u28de\u28e1p;\u6adb\xf2\u2212\xf0\u0a81\u0100dp\u28e9\u28eeels;\u62a7f;\uc000\ud835\udd5e\u0100ct\u28f8\u28fdr;\uc000\ud835\udcc2pos\xbb\u159d\u0180;lm\u2909\u290a\u290d\u43bctimap;\u62b8\u0c00GLRVabcdefghijlmoprstuvw\u2942\u2953\u297e\u2989\u2998\u29da\u29e9\u2a15\u2a1a\u2a58\u2a5d\u2a83\u2a95\u2aa4\u2aa8\u2b04\u2b07\u2b44\u2b7f\u2bae\u2c34\u2c67\u2c7c\u2ce9\u0100gt\u2947\u294b;\uc000\u22d9\u0338\u0100;v\u2950\u0bcf\uc000\u226b\u20d2\u0180elt\u295a\u2972\u2976ft\u0100ar\u2961\u2967rrow;\u61cdightarrow;\u61ce;\uc000\u22d8\u0338\u0100;v\u297b\u0c47\uc000\u226a\u20d2ightarrow;\u61cf\u0100Dd\u298e\u2993ash;\u62afash;\u62ae\u0280bcnpt\u29a3\u29a7\u29ac\u29b1\u29ccla\xbb\u02deute;\u4144g;\uc000\u2220\u20d2\u0280;Eiop\u0d84\u29bc\u29c0\u29c5\u29c8;\uc000\u2a70\u0338d;\uc000\u224b\u0338s;\u4149ro\xf8\u0d84ur\u0100;a\u29d3\u29d4\u666el\u0100;s\u29d3\u0b38\u01f3\u29df\0\u29e3p\u80bb\xa0\u0b37mp\u0100;e\u0bf9\u0c00\u0280aeouy\u29f4\u29fe\u2a03\u2a10\u2a13\u01f0\u29f9\0\u29fb;\u6a43on;\u4148dil;\u4146ng\u0100;d\u0d7e\u2a0aot;\uc000\u2a6d\u0338p;\u6a42;\u443dash;\u6013\u0380;Aadqsx\u0b92\u2a29\u2a2d\u2a3b\u2a41\u2a45\u2a50rr;\u61d7r\u0100hr\u2a33\u2a36k;\u6924\u0100;o\u13f2\u13f0ot;\uc000\u2250\u0338ui\xf6\u0b63\u0100ei\u2a4a\u2a4ear;\u6928\xed\u0b98ist\u0100;s\u0ba0\u0b9fr;\uc000\ud835\udd2b\u0200Eest\u0bc5\u2a66\u2a79\u2a7c\u0180;qs\u0bbc\u2a6d\u0be1\u0180;qs\u0bbc\u0bc5\u2a74lan\xf4\u0be2i\xed\u0bea\u0100;r\u0bb6\u2a81\xbb\u0bb7\u0180Aap\u2a8a\u2a8d\u2a91r\xf2\u2971rr;\u61aear;\u6af2\u0180;sv\u0f8d\u2a9c\u0f8c\u0100;d\u2aa1\u2aa2\u62fc;\u62facy;\u445a\u0380AEadest\u2ab7\u2aba\u2abe\u2ac2\u2ac5\u2af6\u2af9r\xf2\u2966;\uc000\u2266\u0338rr;\u619ar;\u6025\u0200;fqs\u0c3b\u2ace\u2ae3\u2aeft\u0100ar\u2ad4\u2ad9rro\xf7\u2ac1ightarro\xf7\u2a90\u0180;qs\u0c3b\u2aba\u2aealan\xf4\u0c55\u0100;s\u0c55\u2af4\xbb\u0c36i\xed\u0c5d\u0100;r\u0c35\u2afei\u0100;e\u0c1a\u0c25i\xe4\u0d90\u0100pt\u2b0c\u2b11f;\uc000\ud835\udd5f\u8180\xac;in\u2b19\u2b1a\u2b36\u40acn\u0200;Edv\u0b89\u2b24\u2b28\u2b2e;\uc000\u22f9\u0338ot;\uc000\u22f5\u0338\u01e1\u0b89\u2b33\u2b35;\u62f7;\u62f6i\u0100;v\u0cb8\u2b3c\u01e1\u0cb8\u2b41\u2b43;\u62fe;\u62fd\u0180aor\u2b4b\u2b63\u2b69r\u0200;ast\u0b7b\u2b55\u2b5a\u2b5flle\xec\u0b7bl;\uc000\u2afd\u20e5;\uc000\u2202\u0338lint;\u6a14\u0180;ce\u0c92\u2b70\u2b73u\xe5\u0ca5\u0100;c\u0c98\u2b78\u0100;e\u0c92\u2b7d\xf1\u0c98\u0200Aait\u2b88\u2b8b\u2b9d\u2ba7r\xf2\u2988rr\u0180;cw\u2b94\u2b95\u2b99\u619b;\uc000\u2933\u0338;\uc000\u219d\u0338ghtarrow\xbb\u2b95ri\u0100;e\u0ccb\u0cd6\u0380chimpqu\u2bbd\u2bcd\u2bd9\u2b04\u0b78\u2be4\u2bef\u0200;cer\u0d32\u2bc6\u0d37\u2bc9u\xe5\u0d45;\uc000\ud835\udcc3ort\u026d\u2b05\0\0\u2bd6ar\xe1\u2b56m\u0100;e\u0d6e\u2bdf\u0100;q\u0d74\u0d73su\u0100bp\u2beb\u2bed\xe5\u0cf8\xe5\u0d0b\u0180bcp\u2bf6\u2c11\u2c19\u0200;Ees\u2bff\u2c00\u0d22\u2c04\u6284;\uc000\u2ac5\u0338et\u0100;e\u0d1b\u2c0bq\u0100;q\u0d23\u2c00c\u0100;e\u0d32\u2c17\xf1\u0d38\u0200;Ees\u2c22\u2c23\u0d5f\u2c27\u6285;\uc000\u2ac6\u0338et\u0100;e\u0d58\u2c2eq\u0100;q\u0d60\u2c23\u0200gilr\u2c3d\u2c3f\u2c45\u2c47\xec\u0bd7lde\u803b\xf1\u40f1\xe7\u0c43iangle\u0100lr\u2c52\u2c5ceft\u0100;e\u0c1a\u2c5a\xf1\u0c26ight\u0100;e\u0ccb\u2c65\xf1\u0cd7\u0100;m\u2c6c\u2c6d\u43bd\u0180;es\u2c74\u2c75\u2c79\u4023ro;\u6116p;\u6007\u0480DHadgilrs\u2c8f\u2c94\u2c99\u2c9e\u2ca3\u2cb0\u2cb6\u2cd3\u2ce3ash;\u62adarr;\u6904p;\uc000\u224d\u20d2ash;\u62ac\u0100et\u2ca8\u2cac;\uc000\u2265\u20d2;\uc000>\u20d2nfin;\u69de\u0180Aet\u2cbd\u2cc1\u2cc5rr;\u6902;\uc000\u2264\u20d2\u0100;r\u2cca\u2ccd\uc000<\u20d2ie;\uc000\u22b4\u20d2\u0100At\u2cd8\u2cdcrr;\u6903rie;\uc000\u22b5\u20d2im;\uc000\u223c\u20d2\u0180Aan\u2cf0\u2cf4\u2d02rr;\u61d6r\u0100hr\u2cfa\u2cfdk;\u6923\u0100;o\u13e7\u13e5ear;\u6927\u1253\u1a95\0\0\0\0\0\0\0\0\0\0\0\0\0\u2d2d\0\u2d38\u2d48\u2d60\u2d65\u2d72\u2d84\u1b07\0\0\u2d8d\u2dab\0\u2dc8\u2dce\0\u2ddc\u2e19\u2e2b\u2e3e\u2e43\u0100cs\u2d31\u1a97ute\u803b\xf3\u40f3\u0100iy\u2d3c\u2d45r\u0100;c\u1a9e\u2d42\u803b\xf4\u40f4;\u443e\u0280abios\u1aa0\u2d52\u2d57\u01c8\u2d5alac;\u4151v;\u6a38old;\u69bclig;\u4153\u0100cr\u2d69\u2d6dir;\u69bf;\uc000\ud835\udd2c\u036f\u2d79\0\0\u2d7c\0\u2d82n;\u42dbave\u803b\xf2\u40f2;\u69c1\u0100bm\u2d88\u0df4ar;\u69b5\u0200acit\u2d95\u2d98\u2da5\u2da8r\xf2\u1a80\u0100ir\u2d9d\u2da0r;\u69beoss;\u69bbn\xe5\u0e52;\u69c0\u0180aei\u2db1\u2db5\u2db9cr;\u414dga;\u43c9\u0180cdn\u2dc0\u2dc5\u01cdron;\u43bf;\u69b6pf;\uc000\ud835\udd60\u0180ael\u2dd4\u2dd7\u01d2r;\u69b7rp;\u69b9\u0380;adiosv\u2dea\u2deb\u2dee\u2e08\u2e0d\u2e10\u2e16\u6228r\xf2\u1a86\u0200;efm\u2df7\u2df8\u2e02\u2e05\u6a5dr\u0100;o\u2dfe\u2dff\u6134f\xbb\u2dff\u803b\xaa\u40aa\u803b\xba\u40bagof;\u62b6r;\u6a56lope;\u6a57;\u6a5b\u0180clo\u2e1f\u2e21\u2e27\xf2\u2e01ash\u803b\xf8\u40f8l;\u6298i\u016c\u2e2f\u2e34de\u803b\xf5\u40f5es\u0100;a\u01db\u2e3as;\u6a36ml\u803b\xf6\u40f6bar;\u633d\u0ae1\u2e5e\0\u2e7d\0\u2e80\u2e9d\0\u2ea2\u2eb9\0\0\u2ecb\u0e9c\0\u2f13\0\0\u2f2b\u2fbc\0\u2fc8r\u0200;ast\u0403\u2e67\u2e72\u0e85\u8100\xb6;l\u2e6d\u2e6e\u40b6le\xec\u0403\u0269\u2e78\0\0\u2e7bm;\u6af3;\u6afdy;\u443fr\u0280cimpt\u2e8b\u2e8f\u2e93\u1865\u2e97nt;\u4025od;\u402eil;\u6030enk;\u6031r;\uc000\ud835\udd2d\u0180imo\u2ea8\u2eb0\u2eb4\u0100;v\u2ead\u2eae\u43c6;\u43d5ma\xf4\u0a76ne;\u660e\u0180;tv\u2ebf\u2ec0\u2ec8\u43c0chfork\xbb\u1ffd;\u43d6\u0100au\u2ecf\u2edfn\u0100ck\u2ed5\u2eddk\u0100;h\u21f4\u2edb;\u610e\xf6\u21f4s\u0480;abcdemst\u2ef3\u2ef4\u1908\u2ef9\u2efd\u2f04\u2f06\u2f0a\u2f0e\u402bcir;\u6a23ir;\u6a22\u0100ou\u1d40\u2f02;\u6a25;\u6a72n\u80bb\xb1\u0e9dim;\u6a26wo;\u6a27\u0180ipu\u2f19\u2f20\u2f25ntint;\u6a15f;\uc000\ud835\udd61nd\u803b\xa3\u40a3\u0500;Eaceinosu\u0ec8\u2f3f\u2f41\u2f44\u2f47\u2f81\u2f89\u2f92\u2f7e\u2fb6;\u6ab3p;\u6ab7u\xe5\u0ed9\u0100;c\u0ece\u2f4c\u0300;acens\u0ec8\u2f59\u2f5f\u2f66\u2f68\u2f7eppro\xf8\u2f43urlye\xf1\u0ed9\xf1\u0ece\u0180aes\u2f6f\u2f76\u2f7approx;\u6ab9qq;\u6ab5im;\u62e8i\xed\u0edfme\u0100;s\u2f88\u0eae\u6032\u0180Eas\u2f78\u2f90\u2f7a\xf0\u2f75\u0180dfp\u0eec\u2f99\u2faf\u0180als\u2fa0\u2fa5\u2faalar;\u632eine;\u6312urf;\u6313\u0100;t\u0efb\u2fb4\xef\u0efbrel;\u62b0\u0100ci\u2fc0\u2fc5r;\uc000\ud835\udcc5;\u43c8ncsp;\u6008\u0300fiopsu\u2fda\u22e2\u2fdf\u2fe5\u2feb\u2ff1r;\uc000\ud835\udd2epf;\uc000\ud835\udd62rime;\u6057cr;\uc000\ud835\udcc6\u0180aeo\u2ff8\u3009\u3013t\u0100ei\u2ffe\u3005rnion\xf3\u06b0nt;\u6a16st\u0100;e\u3010\u3011\u403f\xf1\u1f19\xf4\u0f14\u0a80ABHabcdefhilmnoprstux\u3040\u3051\u3055\u3059\u30e0\u310e\u312b\u3147\u3162\u3172\u318e\u3206\u3215\u3224\u3229\u3258\u326e\u3272\u3290\u32b0\u32b7\u0180art\u3047\u304a\u304cr\xf2\u10b3\xf2\u03ddail;\u691car\xf2\u1c65ar;\u6964\u0380cdenqrt\u3068\u3075\u3078\u307f\u308f\u3094\u30cc\u0100eu\u306d\u3071;\uc000\u223d\u0331te;\u4155i\xe3\u116emptyv;\u69b3g\u0200;del\u0fd1\u3089\u308b\u308d;\u6992;\u69a5\xe5\u0fd1uo\u803b\xbb\u40bbr\u0580;abcfhlpstw\u0fdc\u30ac\u30af\u30b7\u30b9\u30bc\u30be\u30c0\u30c3\u30c7\u30cap;\u6975\u0100;f\u0fe0\u30b4s;\u6920;\u6933s;\u691e\xeb\u225d\xf0\u272el;\u6945im;\u6974l;\u61a3;\u619d\u0100ai\u30d1\u30d5il;\u691ao\u0100;n\u30db\u30dc\u6236al\xf3\u0f1e\u0180abr\u30e7\u30ea\u30eer\xf2\u17e5rk;\u6773\u0100ak\u30f3\u30fdc\u0100ek\u30f9\u30fb;\u407d;\u405d\u0100es\u3102\u3104;\u698cl\u0100du\u310a\u310c;\u698e;\u6990\u0200aeuy\u3117\u311c\u3127\u3129ron;\u4159\u0100di\u3121\u3125il;\u4157\xec\u0ff2\xe2\u30fa;\u4440\u0200clqs\u3134\u3137\u313d\u3144a;\u6937dhar;\u6969uo\u0100;r\u020e\u020dh;\u61b3\u0180acg\u314e\u315f\u0f44l\u0200;ips\u0f78\u3158\u315b\u109cn\xe5\u10bbar\xf4\u0fa9t;\u65ad\u0180ilr\u3169\u1023\u316esht;\u697d;\uc000\ud835\udd2f\u0100ao\u3177\u3186r\u0100du\u317d\u317f\xbb\u047b\u0100;l\u1091\u3184;\u696c\u0100;v\u318b\u318c\u43c1;\u43f1\u0180gns\u3195\u31f9\u31fcht\u0300ahlrst\u31a4\u31b0\u31c2\u31d8\u31e4\u31eerrow\u0100;t\u0fdc\u31ada\xe9\u30c8arpoon\u0100du\u31bb\u31bfow\xee\u317ep\xbb\u1092eft\u0100ah\u31ca\u31d0rrow\xf3\u0feaarpoon\xf3\u0551ightarrows;\u61c9quigarro\xf7\u30cbhreetimes;\u62ccg;\u42daingdotse\xf1\u1f32\u0180ahm\u320d\u3210\u3213r\xf2\u0feaa\xf2\u0551;\u600foust\u0100;a\u321e\u321f\u63b1che\xbb\u321fmid;\u6aee\u0200abpt\u3232\u323d\u3240\u3252\u0100nr\u3237\u323ag;\u67edr;\u61fer\xeb\u1003\u0180afl\u3247\u324a\u324er;\u6986;\uc000\ud835\udd63us;\u6a2eimes;\u6a35\u0100ap\u325d\u3267r\u0100;g\u3263\u3264\u4029t;\u6994olint;\u6a12ar\xf2\u31e3\u0200achq\u327b\u3280\u10bc\u3285quo;\u603ar;\uc000\ud835\udcc7\u0100bu\u30fb\u328ao\u0100;r\u0214\u0213\u0180hir\u3297\u329b\u32a0re\xe5\u31f8mes;\u62cai\u0200;efl\u32aa\u1059\u1821\u32ab\u65b9tri;\u69celuhar;\u6968;\u611e\u0d61\u32d5\u32db\u32df\u332c\u3338\u3371\0\u337a\u33a4\0\0\u33ec\u33f0\0\u3428\u3448\u345a\u34ad\u34b1\u34ca\u34f1\0\u3616\0\0\u3633cute;\u415bqu\xef\u27ba\u0500;Eaceinpsy\u11ed\u32f3\u32f5\u32ff\u3302\u330b\u330f\u331f\u3326\u3329;\u6ab4\u01f0\u32fa\0\u32fc;\u6ab8on;\u4161u\xe5\u11fe\u0100;d\u11f3\u3307il;\u415frc;\u415d\u0180Eas\u3316\u3318\u331b;\u6ab6p;\u6abaim;\u62e9olint;\u6a13i\xed\u1204;\u4441ot\u0180;be\u3334\u1d47\u3335\u62c5;\u6a66\u0380Aacmstx\u3346\u334a\u3357\u335b\u335e\u3363\u336drr;\u61d8r\u0100hr\u3350\u3352\xeb\u2228\u0100;o\u0a36\u0a34t\u803b\xa7\u40a7i;\u403bwar;\u6929m\u0100in\u3369\xf0nu\xf3\xf1t;\u6736r\u0100;o\u3376\u2055\uc000\ud835\udd30\u0200acoy\u3382\u3386\u3391\u33a0rp;\u666f\u0100hy\u338b\u338fcy;\u4449;\u4448rt\u026d\u3399\0\0\u339ci\xe4\u1464ara\xec\u2e6f\u803b\xad\u40ad\u0100gm\u33a8\u33b4ma\u0180;fv\u33b1\u33b2\u33b2\u43c3;\u43c2\u0400;deglnpr\u12ab\u33c5\u33c9\u33ce\u33d6\u33de\u33e1\u33e6ot;\u6a6a\u0100;q\u12b1\u12b0\u0100;E\u33d3\u33d4\u6a9e;\u6aa0\u0100;E\u33db\u33dc\u6a9d;\u6a9fe;\u6246lus;\u6a24arr;\u6972ar\xf2\u113d\u0200aeit\u33f8\u3408\u340f\u3417\u0100ls\u33fd\u3404lsetm\xe9\u336ahp;\u6a33parsl;\u69e4\u0100dl\u1463\u3414e;\u6323\u0100;e\u341c\u341d\u6aaa\u0100;s\u3422\u3423\u6aac;\uc000\u2aac\ufe00\u0180flp\u342e\u3433\u3442tcy;\u444c\u0100;b\u3438\u3439\u402f\u0100;a\u343e\u343f\u69c4r;\u633ff;\uc000\ud835\udd64a\u0100dr\u344d\u0402es\u0100;u\u3454\u3455\u6660it\xbb\u3455\u0180csu\u3460\u3479\u349f\u0100au\u3465\u346fp\u0100;s\u1188\u346b;\uc000\u2293\ufe00p\u0100;s\u11b4\u3475;\uc000\u2294\ufe00u\u0100bp\u347f\u348f\u0180;es\u1197\u119c\u3486et\u0100;e\u1197\u348d\xf1\u119d\u0180;es\u11a8\u11ad\u3496et\u0100;e\u11a8\u349d\xf1\u11ae\u0180;af\u117b\u34a6\u05b0r\u0165\u34ab\u05b1\xbb\u117car\xf2\u1148\u0200cemt\u34b9\u34be\u34c2\u34c5r;\uc000\ud835\udcc8tm\xee\xf1i\xec\u3415ar\xe6\u11be\u0100ar\u34ce\u34d5r\u0100;f\u34d4\u17bf\u6606\u0100an\u34da\u34edight\u0100ep\u34e3\u34eapsilo\xee\u1ee0h\xe9\u2eafs\xbb\u2852\u0280bcmnp\u34fb\u355e\u1209\u358b\u358e\u0480;Edemnprs\u350e\u350f\u3511\u3515\u351e\u3523\u352c\u3531\u3536\u6282;\u6ac5ot;\u6abd\u0100;d\u11da\u351aot;\u6ac3ult;\u6ac1\u0100Ee\u3528\u352a;\u6acb;\u628alus;\u6abfarr;\u6979\u0180eiu\u353d\u3552\u3555t\u0180;en\u350e\u3545\u354bq\u0100;q\u11da\u350feq\u0100;q\u352b\u3528m;\u6ac7\u0100bp\u355a\u355c;\u6ad5;\u6ad3c\u0300;acens\u11ed\u356c\u3572\u3579\u357b\u3326ppro\xf8\u32faurlye\xf1\u11fe\xf1\u11f3\u0180aes\u3582\u3588\u331bppro\xf8\u331aq\xf1\u3317g;\u666a\u0680123;Edehlmnps\u35a9\u35ac\u35af\u121c\u35b2\u35b4\u35c0\u35c9\u35d5\u35da\u35df\u35e8\u35ed\u803b\xb9\u40b9\u803b\xb2\u40b2\u803b\xb3\u40b3;\u6ac6\u0100os\u35b9\u35bct;\u6abeub;\u6ad8\u0100;d\u1222\u35c5ot;\u6ac4s\u0100ou\u35cf\u35d2l;\u67c9b;\u6ad7arr;\u697bult;\u6ac2\u0100Ee\u35e4\u35e6;\u6acc;\u628blus;\u6ac0\u0180eiu\u35f4\u3609\u360ct\u0180;en\u121c\u35fc\u3602q\u0100;q\u1222\u35b2eq\u0100;q\u35e7\u35e4m;\u6ac8\u0100bp\u3611\u3613;\u6ad4;\u6ad6\u0180Aan\u361c\u3620\u362drr;\u61d9r\u0100hr\u3626\u3628\xeb\u222e\u0100;o\u0a2b\u0a29war;\u692alig\u803b\xdf\u40df\u0be1\u3651\u365d\u3660\u12ce\u3673\u3679\0\u367e\u36c2\0\0\0\0\0\u36db\u3703\0\u3709\u376c\0\0\0\u3787\u0272\u3656\0\0\u365bget;\u6316;\u43c4r\xeb\u0e5f\u0180aey\u3666\u366b\u3670ron;\u4165dil;\u4163;\u4442lrec;\u6315r;\uc000\ud835\udd31\u0200eiko\u3686\u369d\u36b5\u36bc\u01f2\u368b\0\u3691e\u01004f\u1284\u1281a\u0180;sv\u3698\u3699\u369b\u43b8ym;\u43d1\u0100cn\u36a2\u36b2k\u0100as\u36a8\u36aeppro\xf8\u12c1im\xbb\u12acs\xf0\u129e\u0100as\u36ba\u36ae\xf0\u12c1rn\u803b\xfe\u40fe\u01ec\u031f\u36c6\u22e7es\u8180\xd7;bd\u36cf\u36d0\u36d8\u40d7\u0100;a\u190f\u36d5r;\u6a31;\u6a30\u0180eps\u36e1\u36e3\u3700\xe1\u2a4d\u0200;bcf\u0486\u36ec\u36f0\u36f4ot;\u6336ir;\u6af1\u0100;o\u36f9\u36fc\uc000\ud835\udd65rk;\u6ada\xe1\u3362rime;\u6034\u0180aip\u370f\u3712\u3764d\xe5\u1248\u0380adempst\u3721\u374d\u3740\u3751\u3757\u375c\u375fngle\u0280;dlqr\u3730\u3731\u3736\u3740\u3742\u65b5own\xbb\u1dbbeft\u0100;e\u2800\u373e\xf1\u092e;\u625cight\u0100;e\u32aa\u374b\xf1\u105aot;\u65ecinus;\u6a3alus;\u6a39b;\u69cdime;\u6a3bezium;\u63e2\u0180cht\u3772\u377d\u3781\u0100ry\u3777\u377b;\uc000\ud835\udcc9;\u4446cy;\u445brok;\u4167\u0100io\u378b\u378ex\xf4\u1777head\u0100lr\u3797\u37a0eftarro\xf7\u084fightarrow\xbb\u0f5d\u0900AHabcdfghlmoprstuw\u37d0\u37d3\u37d7\u37e4\u37f0\u37fc\u380e\u381c\u3823\u3834\u3851\u385d\u386b\u38a9\u38cc\u38d2\u38ea\u38f6r\xf2\u03edar;\u6963\u0100cr\u37dc\u37e2ute\u803b\xfa\u40fa\xf2\u1150r\u01e3\u37ea\0\u37edy;\u445eve;\u416d\u0100iy\u37f5\u37farc\u803b\xfb\u40fb;\u4443\u0180abh\u3803\u3806\u380br\xf2\u13adlac;\u4171a\xf2\u13c3\u0100ir\u3813\u3818sht;\u697e;\uc000\ud835\udd32rave\u803b\xf9\u40f9\u0161\u3827\u3831r\u0100lr\u382c\u382e\xbb\u0957\xbb\u1083lk;\u6580\u0100ct\u3839\u384d\u026f\u383f\0\0\u384arn\u0100;e\u3845\u3846\u631cr\xbb\u3846op;\u630fri;\u65f8\u0100al\u3856\u385acr;\u416b\u80bb\xa8\u0349\u0100gp\u3862\u3866on;\u4173f;\uc000\ud835\udd66\u0300adhlsu\u114b\u3878\u387d\u1372\u3891\u38a0own\xe1\u13b3arpoon\u0100lr\u3888\u388cef\xf4\u382digh\xf4\u382fi\u0180;hl\u3899\u389a\u389c\u43c5\xbb\u13faon\xbb\u389aparrows;\u61c8\u0180cit\u38b0\u38c4\u38c8\u026f\u38b6\0\0\u38c1rn\u0100;e\u38bc\u38bd\u631dr\xbb\u38bdop;\u630eng;\u416fri;\u65f9cr;\uc000\ud835\udcca\u0180dir\u38d9\u38dd\u38e2ot;\u62f0lde;\u4169i\u0100;f\u3730\u38e8\xbb\u1813\u0100am\u38ef\u38f2r\xf2\u38a8l\u803b\xfc\u40fcangle;\u69a7\u0780ABDacdeflnoprsz\u391c\u391f\u3929\u392d\u39b5\u39b8\u39bd\u39df\u39e4\u39e8\u39f3\u39f9\u39fd\u3a01\u3a20r\xf2\u03f7ar\u0100;v\u3926\u3927\u6ae8;\u6ae9as\xe8\u03e1\u0100nr\u3932\u3937grt;\u699c\u0380eknprst\u34e3\u3946\u394b\u3952\u395d\u3964\u3996app\xe1\u2415othin\xe7\u1e96\u0180hir\u34eb\u2ec8\u3959op\xf4\u2fb5\u0100;h\u13b7\u3962\xef\u318d\u0100iu\u3969\u396dgm\xe1\u33b3\u0100bp\u3972\u3984setneq\u0100;q\u397d\u3980\uc000\u228a\ufe00;\uc000\u2acb\ufe00setneq\u0100;q\u398f\u3992\uc000\u228b\ufe00;\uc000\u2acc\ufe00\u0100hr\u399b\u399fet\xe1\u369ciangle\u0100lr\u39aa\u39afeft\xbb\u0925ight\xbb\u1051y;\u4432ash\xbb\u1036\u0180elr\u39c4\u39d2\u39d7\u0180;be\u2dea\u39cb\u39cfar;\u62bbq;\u625alip;\u62ee\u0100bt\u39dc\u1468a\xf2\u1469r;\uc000\ud835\udd33tr\xe9\u39aesu\u0100bp\u39ef\u39f1\xbb\u0d1c\xbb\u0d59pf;\uc000\ud835\udd67ro\xf0\u0efbtr\xe9\u39b4\u0100cu\u3a06\u3a0br;\uc000\ud835\udccb\u0100bp\u3a10\u3a18n\u0100Ee\u3980\u3a16\xbb\u397en\u0100Ee\u3992\u3a1e\xbb\u3990igzag;\u699a\u0380cefoprs\u3a36\u3a3b\u3a56\u3a5b\u3a54\u3a61\u3a6airc;\u4175\u0100di\u3a40\u3a51\u0100bg\u3a45\u3a49ar;\u6a5fe\u0100;q\u15fa\u3a4f;\u6259erp;\u6118r;\uc000\ud835\udd34pf;\uc000\ud835\udd68\u0100;e\u1479\u3a66at\xe8\u1479cr;\uc000\ud835\udccc\u0ae3\u178e\u3a87\0\u3a8b\0\u3a90\u3a9b\0\0\u3a9d\u3aa8\u3aab\u3aaf\0\0\u3ac3\u3ace\0\u3ad8\u17dc\u17dftr\xe9\u17d1r;\uc000\ud835\udd35\u0100Aa\u3a94\u3a97r\xf2\u03c3r\xf2\u09f6;\u43be\u0100Aa\u3aa1\u3aa4r\xf2\u03b8r\xf2\u09eba\xf0\u2713is;\u62fb\u0180dpt\u17a4\u3ab5\u3abe\u0100fl\u3aba\u17a9;\uc000\ud835\udd69im\xe5\u17b2\u0100Aa\u3ac7\u3acar\xf2\u03cer\xf2\u0a01\u0100cq\u3ad2\u17b8r;\uc000\ud835\udccd\u0100pt\u17d6\u3adcr\xe9\u17d4\u0400acefiosu\u3af0\u3afd\u3b08\u3b0c\u3b11\u3b15\u3b1b\u3b21c\u0100uy\u3af6\u3afbte\u803b\xfd\u40fd;\u444f\u0100iy\u3b02\u3b06rc;\u4177;\u444bn\u803b\xa5\u40a5r;\uc000\ud835\udd36cy;\u4457pf;\uc000\ud835\udd6acr;\uc000\ud835\udcce\u0100cm\u3b26\u3b29y;\u444el\u803b\xff\u40ff\u0500acdefhiosw\u3b42\u3b48\u3b54\u3b58\u3b64\u3b69\u3b6d\u3b74\u3b7a\u3b80cute;\u417a\u0100ay\u3b4d\u3b52ron;\u417e;\u4437ot;\u417c\u0100et\u3b5d\u3b61tr\xe6\u155fa;\u43b6r;\uc000\ud835\udd37cy;\u4436grarr;\u61ddpf;\uc000\ud835\udd6bcr;\uc000\ud835\udccf\u0100jn\u3b85\u3b87;\u600dj;\u600c" + .split("") + .map(function (c) { return c.charCodeAt(0); })); +//# sourceMappingURL=decode-data-html.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-html.js.map b/node_modules/entities/lib/generated/decode-data-html.js.map new file mode 100644 index 0000000..5732f6f --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-html.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-html.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-html.ts"],"names":[],"mappings":";AAAA,8CAA8C;;AAE9C,kBAAe,IAAI,WAAW;AAC1B,kBAAkB;AAClB,268CAA268C;KACt68C,KAAK,CAAC,EAAE,CAAC;KACT,GAAG,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAf,CAAe,CAAC,CACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-xml.d.ts b/node_modules/entities/lib/generated/decode-data-xml.d.ts new file mode 100644 index 0000000..4a3f533 --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-xml.d.ts @@ -0,0 +1,3 @@ +declare const _default: Uint16Array; +export default _default; +//# sourceMappingURL=decode-data-xml.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-xml.d.ts.map b/node_modules/entities/lib/generated/decode-data-xml.d.ts.map new file mode 100644 index 0000000..be2a9a2 --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-xml.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-xml.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-xml.ts"],"names":[],"mappings":";AAEA,wBAKE"} \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-xml.js b/node_modules/entities/lib/generated/decode-data-xml.js new file mode 100644 index 0000000..8fee783 --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-xml.js @@ -0,0 +1,9 @@ +"use strict"; +// Generated using scripts/write-decode-map.ts +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = new Uint16Array( +// prettier-ignore +"\u0200aglq\t\x15\x18\x1b\u026d\x0f\0\0\x12p;\u4026os;\u4027t;\u403et;\u403cuot;\u4022" + .split("") + .map(function (c) { return c.charCodeAt(0); })); +//# sourceMappingURL=decode-data-xml.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/decode-data-xml.js.map b/node_modules/entities/lib/generated/decode-data-xml.js.map new file mode 100644 index 0000000..569fef4 --- /dev/null +++ b/node_modules/entities/lib/generated/decode-data-xml.js.map @@ -0,0 +1 @@ +{"version":3,"file":"decode-data-xml.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/decode-data-xml.ts"],"names":[],"mappings":";AAAA,8CAA8C;;AAE9C,kBAAe,IAAI,WAAW;AAC1B,kBAAkB;AAClB,uFAAuF;KAClF,KAAK,CAAC,EAAE,CAAC;KACT,GAAG,CAAC,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,EAAf,CAAe,CAAC,CACnC,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/generated/encode-html.d.ts b/node_modules/entities/lib/generated/encode-html.d.ts new file mode 100644 index 0000000..0704827 --- /dev/null +++ b/node_modules/entities/lib/generated/encode-html.d.ts @@ -0,0 +1,8 @@ +type EncodeTrieNode = string | { + v?: string; + n: number | Map; + o?: string; +}; +declare const _default: Map; +export default _default; +//# sourceMappingURL=encode-html.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/encode-html.d.ts.map b/node_modules/entities/lib/generated/encode-html.d.ts.map new file mode 100644 index 0000000..e665a6e --- /dev/null +++ b/node_modules/entities/lib/generated/encode-html.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-html.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/encode-html.ts"],"names":[],"mappings":"AAEA,KAAK,cAAc,GACb,MAAM,GACN;IAAE,CAAC,CAAC,EAAE,MAAM,CAAC;IAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC;IAAC,CAAC,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;;AAY1E,wBAAo+tB"} \ No newline at end of file diff --git a/node_modules/entities/lib/generated/encode-html.js b/node_modules/entities/lib/generated/encode-html.js new file mode 100644 index 0000000..071e853 --- /dev/null +++ b/node_modules/entities/lib/generated/encode-html.js @@ -0,0 +1,12 @@ +"use strict"; +// Generated using scripts/write-encode-map.ts +Object.defineProperty(exports, "__esModule", { value: true }); +function restoreDiff(arr) { + for (var i = 1; i < arr.length; i++) { + arr[i][0] += arr[i - 1][0] + 1; + } + return arr; +} +// prettier-ignore +exports.default = new Map(/* #__PURE__ */ restoreDiff([[9, " "], [0, " "], [22, "!"], [0, """], [0, "#"], [0, "$"], [0, "%"], [0, "&"], [0, "'"], [0, "("], [0, ")"], [0, "*"], [0, "+"], [0, ","], [1, "."], [0, "/"], [10, ":"], [0, ";"], [0, { v: "<", n: 8402, o: "<⃒" }], [0, { v: "=", n: 8421, o: "=⃥" }], [0, { v: ">", n: 8402, o: ">⃒" }], [0, "?"], [0, "@"], [26, "["], [0, "\"], [0, "]"], [0, "^"], [0, "_"], [0, "`"], [5, { n: 106, o: "fj" }], [20, "{"], [0, "|"], [0, "}"], [34, " "], [0, "¡"], [0, "¢"], [0, "£"], [0, "¤"], [0, "¥"], [0, "¦"], [0, "§"], [0, "¨"], [0, "©"], [0, "ª"], [0, "«"], [0, "¬"], [0, "­"], [0, "®"], [0, "¯"], [0, "°"], [0, "±"], [0, "²"], [0, "³"], [0, "´"], [0, "µ"], [0, "¶"], [0, "·"], [0, "¸"], [0, "¹"], [0, "º"], [0, "»"], [0, "¼"], [0, "½"], [0, "¾"], [0, "¿"], [0, "À"], [0, "Á"], [0, "Â"], [0, "Ã"], [0, "Ä"], [0, "Å"], [0, "Æ"], [0, "Ç"], [0, "È"], [0, "É"], [0, "Ê"], [0, "Ë"], [0, "Ì"], [0, "Í"], [0, "Î"], [0, "Ï"], [0, "Ð"], [0, "Ñ"], [0, "Ò"], [0, "Ó"], [0, "Ô"], [0, "Õ"], [0, "Ö"], [0, "×"], [0, "Ø"], [0, "Ù"], [0, "Ú"], [0, "Û"], [0, "Ü"], [0, "Ý"], [0, "Þ"], [0, "ß"], [0, "à"], [0, "á"], [0, "â"], [0, "ã"], [0, "ä"], [0, "å"], [0, "æ"], [0, "ç"], [0, "è"], [0, "é"], [0, "ê"], [0, "ë"], [0, "ì"], [0, "í"], [0, "î"], [0, "ï"], [0, "ð"], [0, "ñ"], [0, "ò"], [0, "ó"], [0, "ô"], [0, "õ"], [0, "ö"], [0, "÷"], [0, "ø"], [0, "ù"], [0, "ú"], [0, "û"], [0, "ü"], [0, "ý"], [0, "þ"], [0, "ÿ"], [0, "Ā"], [0, "ā"], [0, "Ă"], [0, "ă"], [0, "Ą"], [0, "ą"], [0, "Ć"], [0, "ć"], [0, "Ĉ"], [0, "ĉ"], [0, "Ċ"], [0, "ċ"], [0, "Č"], [0, "č"], [0, "Ď"], [0, "ď"], [0, "Đ"], [0, "đ"], [0, "Ē"], [0, "ē"], [2, "Ė"], [0, "ė"], [0, "Ę"], [0, "ę"], [0, "Ě"], [0, "ě"], [0, "Ĝ"], [0, "ĝ"], [0, "Ğ"], [0, "ğ"], [0, "Ġ"], [0, "ġ"], [0, "Ģ"], [1, "Ĥ"], [0, "ĥ"], [0, "Ħ"], [0, "ħ"], [0, "Ĩ"], [0, "ĩ"], [0, "Ī"], [0, "ī"], [2, "Į"], [0, "į"], [0, "İ"], [0, "ı"], [0, "IJ"], [0, "ij"], [0, "Ĵ"], [0, "ĵ"], [0, "Ķ"], [0, "ķ"], [0, "ĸ"], [0, "Ĺ"], [0, "ĺ"], [0, "Ļ"], [0, "ļ"], [0, "Ľ"], [0, "ľ"], [0, "Ŀ"], [0, "ŀ"], [0, "Ł"], [0, "ł"], [0, "Ń"], [0, "ń"], [0, "Ņ"], [0, "ņ"], [0, "Ň"], [0, "ň"], [0, "ʼn"], [0, "Ŋ"], [0, "ŋ"], [0, "Ō"], [0, "ō"], [2, "Ő"], [0, "ő"], [0, "Œ"], [0, "œ"], [0, "Ŕ"], [0, "ŕ"], [0, "Ŗ"], [0, "ŗ"], [0, "Ř"], [0, "ř"], [0, "Ś"], [0, "ś"], [0, "Ŝ"], [0, "ŝ"], [0, "Ş"], [0, "ş"], [0, "Š"], [0, "š"], [0, "Ţ"], [0, "ţ"], [0, "Ť"], [0, "ť"], [0, "Ŧ"], [0, "ŧ"], [0, "Ũ"], [0, "ũ"], [0, "Ū"], [0, "ū"], [0, "Ŭ"], [0, "ŭ"], [0, "Ů"], [0, "ů"], [0, "Ű"], [0, "ű"], [0, "Ų"], [0, "ų"], [0, "Ŵ"], [0, "ŵ"], [0, "Ŷ"], [0, "ŷ"], [0, "Ÿ"], [0, "Ź"], [0, "ź"], [0, "Ż"], [0, "ż"], [0, "Ž"], [0, "ž"], [19, "ƒ"], [34, "Ƶ"], [63, "ǵ"], [65, "ȷ"], [142, "ˆ"], [0, "ˇ"], [16, "˘"], [0, "˙"], [0, "˚"], [0, "˛"], [0, "˜"], [0, "˝"], [51, "̑"], [127, "Α"], [0, "Β"], [0, "Γ"], [0, "Δ"], [0, "Ε"], [0, "Ζ"], [0, "Η"], [0, "Θ"], [0, "Ι"], [0, "Κ"], [0, "Λ"], [0, "Μ"], [0, "Ν"], [0, "Ξ"], [0, "Ο"], [0, "Π"], [0, "Ρ"], [1, "Σ"], [0, "Τ"], [0, "Υ"], [0, "Φ"], [0, "Χ"], [0, "Ψ"], [0, "Ω"], [7, "α"], [0, "β"], [0, "γ"], [0, "δ"], [0, "ε"], [0, "ζ"], [0, "η"], [0, "θ"], [0, "ι"], [0, "κ"], [0, "λ"], [0, "μ"], [0, "ν"], [0, "ξ"], [0, "ο"], [0, "π"], [0, "ρ"], [0, "ς"], [0, "σ"], [0, "τ"], [0, "υ"], [0, "φ"], [0, "χ"], [0, "ψ"], [0, "ω"], [7, "ϑ"], [0, "ϒ"], [2, "ϕ"], [0, "ϖ"], [5, "Ϝ"], [0, "ϝ"], [18, "ϰ"], [0, "ϱ"], [3, "ϵ"], [0, "϶"], [10, "Ё"], [0, "Ђ"], [0, "Ѓ"], [0, "Є"], [0, "Ѕ"], [0, "І"], [0, "Ї"], [0, "Ј"], [0, "Љ"], [0, "Њ"], [0, "Ћ"], [0, "Ќ"], [1, "Ў"], [0, "Џ"], [0, "А"], [0, "Б"], [0, "В"], [0, "Г"], [0, "Д"], [0, "Е"], [0, "Ж"], [0, "З"], [0, "И"], [0, "Й"], [0, "К"], [0, "Л"], [0, "М"], [0, "Н"], [0, "О"], [0, "П"], [0, "Р"], [0, "С"], [0, "Т"], [0, "У"], [0, "Ф"], [0, "Х"], [0, "Ц"], [0, "Ч"], [0, "Ш"], [0, "Щ"], [0, "Ъ"], [0, "Ы"], [0, "Ь"], [0, "Э"], [0, "Ю"], [0, "Я"], [0, "а"], [0, "б"], [0, "в"], [0, "г"], [0, "д"], [0, "е"], [0, "ж"], [0, "з"], [0, "и"], [0, "й"], [0, "к"], [0, "л"], [0, "м"], [0, "н"], [0, "о"], [0, "п"], [0, "р"], [0, "с"], [0, "т"], [0, "у"], [0, "ф"], [0, "х"], [0, "ц"], [0, "ч"], [0, "ш"], [0, "щ"], [0, "ъ"], [0, "ы"], [0, "ь"], [0, "э"], [0, "ю"], [0, "я"], [1, "ё"], [0, "ђ"], [0, "ѓ"], [0, "є"], [0, "ѕ"], [0, "і"], [0, "ї"], [0, "ј"], [0, "љ"], [0, "њ"], [0, "ћ"], [0, "ќ"], [1, "ў"], [0, "џ"], [7074, " "], [0, " "], [0, " "], [0, " "], [1, " "], [0, " "], [0, " "], [0, " "], [0, "​"], [0, "‌"], [0, "‍"], [0, "‎"], [0, "‏"], [0, "‐"], [2, "–"], [0, "—"], [0, "―"], [0, "‖"], [1, "‘"], [0, "’"], [0, "‚"], [1, "“"], [0, "”"], [0, "„"], [1, "†"], [0, "‡"], [0, "•"], [2, "‥"], [0, "…"], [9, "‰"], [0, "‱"], [0, "′"], [0, "″"], [0, "‴"], [0, "‵"], [3, "‹"], [0, "›"], [3, "‾"], [2, "⁁"], [1, "⁃"], [0, "⁄"], [10, "⁏"], [7, "⁗"], [7, { v: " ", n: 8202, o: "  " }], [0, "⁠"], [0, "⁡"], [0, "⁢"], [0, "⁣"], [72, "€"], [46, "⃛"], [0, "⃜"], [37, "ℂ"], [2, "℅"], [4, "ℊ"], [0, "ℋ"], [0, "ℌ"], [0, "ℍ"], [0, "ℎ"], [0, "ℏ"], [0, "ℐ"], [0, "ℑ"], [0, "ℒ"], [0, "ℓ"], [1, "ℕ"], [0, "№"], [0, "℗"], [0, "℘"], [0, "ℙ"], [0, "ℚ"], [0, "ℛ"], [0, "ℜ"], [0, "ℝ"], [0, "℞"], [3, "™"], [1, "ℤ"], [2, "℧"], [0, "ℨ"], [0, "℩"], [2, "ℬ"], [0, "ℭ"], [1, "ℯ"], [0, "ℰ"], [0, "ℱ"], [1, "ℳ"], [0, "ℴ"], [0, "ℵ"], [0, "ℶ"], [0, "ℷ"], [0, "ℸ"], [12, "ⅅ"], [0, "ⅆ"], [0, "ⅇ"], [0, "ⅈ"], [10, "⅓"], [0, "⅔"], [0, "⅕"], [0, "⅖"], [0, "⅗"], [0, "⅘"], [0, "⅙"], [0, "⅚"], [0, "⅛"], [0, "⅜"], [0, "⅝"], [0, "⅞"], [49, "←"], [0, "↑"], [0, "→"], [0, "↓"], [0, "↔"], [0, "↕"], [0, "↖"], [0, "↗"], [0, "↘"], [0, "↙"], [0, "↚"], [0, "↛"], [1, { v: "↝", n: 824, o: "↝̸" }], [0, "↞"], [0, "↟"], [0, "↠"], [0, "↡"], [0, "↢"], [0, "↣"], [0, "↤"], [0, "↥"], [0, "↦"], [0, "↧"], [1, "↩"], [0, "↪"], [0, "↫"], [0, "↬"], [0, "↭"], [0, "↮"], [1, "↰"], [0, "↱"], [0, "↲"], [0, "↳"], [1, "↵"], [0, "↶"], [0, "↷"], [2, "↺"], [0, "↻"], [0, "↼"], [0, "↽"], [0, "↾"], [0, "↿"], [0, "⇀"], [0, "⇁"], [0, "⇂"], [0, "⇃"], [0, "⇄"], [0, "⇅"], [0, "⇆"], [0, "⇇"], [0, "⇈"], [0, "⇉"], [0, "⇊"], [0, "⇋"], [0, "⇌"], [0, "⇍"], [0, "⇎"], [0, "⇏"], [0, "⇐"], [0, "⇑"], [0, "⇒"], [0, "⇓"], [0, "⇔"], [0, "⇕"], [0, "⇖"], [0, "⇗"], [0, "⇘"], [0, "⇙"], [0, "⇚"], [0, "⇛"], [1, "⇝"], [6, "⇤"], [0, "⇥"], [15, "⇵"], [7, "⇽"], [0, "⇾"], [0, "⇿"], [0, "∀"], [0, "∁"], [0, { v: "∂", n: 824, o: "∂̸" }], [0, "∃"], [0, "∄"], [0, "∅"], [1, "∇"], [0, "∈"], [0, "∉"], [1, "∋"], [0, "∌"], [2, "∏"], [0, "∐"], [0, "∑"], [0, "−"], [0, "∓"], [0, "∔"], [1, "∖"], [0, "∗"], [0, "∘"], [1, "√"], [2, "∝"], [0, "∞"], [0, "∟"], [0, { v: "∠", n: 8402, o: "∠⃒" }], [0, "∡"], [0, "∢"], [0, "∣"], [0, "∤"], [0, "∥"], [0, "∦"], [0, "∧"], [0, "∨"], [0, { v: "∩", n: 65024, o: "∩︀" }], [0, { v: "∪", n: 65024, o: "∪︀" }], [0, "∫"], [0, "∬"], [0, "∭"], [0, "∮"], [0, "∯"], [0, "∰"], [0, "∱"], [0, "∲"], [0, "∳"], [0, "∴"], [0, "∵"], [0, "∶"], [0, "∷"], [0, "∸"], [1, "∺"], [0, "∻"], [0, { v: "∼", n: 8402, o: "∼⃒" }], [0, { v: "∽", n: 817, o: "∽̱" }], [0, { v: "∾", n: 819, o: "∾̳" }], [0, "∿"], [0, "≀"], [0, "≁"], [0, { v: "≂", n: 824, o: "≂̸" }], [0, "≃"], [0, "≄"], [0, "≅"], [0, "≆"], [0, "≇"], [0, "≈"], [0, "≉"], [0, "≊"], [0, { v: "≋", n: 824, o: "≋̸" }], [0, "≌"], [0, { v: "≍", n: 8402, o: "≍⃒" }], [0, { v: "≎", n: 824, o: "≎̸" }], [0, { v: "≏", n: 824, o: "≏̸" }], [0, { v: "≐", n: 824, o: "≐̸" }], [0, "≑"], [0, "≒"], [0, "≓"], [0, "≔"], [0, "≕"], [0, "≖"], [0, "≗"], [1, "≙"], [0, "≚"], [1, "≜"], [2, "≟"], [0, "≠"], [0, { v: "≡", n: 8421, o: "≡⃥" }], [0, "≢"], [1, { v: "≤", n: 8402, o: "≤⃒" }], [0, { v: "≥", n: 8402, o: "≥⃒" }], [0, { v: "≦", n: 824, o: "≦̸" }], [0, { v: "≧", n: 824, o: "≧̸" }], [0, { v: "≨", n: 65024, o: "≨︀" }], [0, { v: "≩", n: 65024, o: "≩︀" }], [0, { v: "≪", n: new Map(/* #__PURE__ */ restoreDiff([[824, "≪̸"], [7577, "≪⃒"]])) }], [0, { v: "≫", n: new Map(/* #__PURE__ */ restoreDiff([[824, "≫̸"], [7577, "≫⃒"]])) }], [0, "≬"], [0, "≭"], [0, "≮"], [0, "≯"], [0, "≰"], [0, "≱"], [0, "≲"], [0, "≳"], [0, "≴"], [0, "≵"], [0, "≶"], [0, "≷"], [0, "≸"], [0, "≹"], [0, "≺"], [0, "≻"], [0, "≼"], [0, "≽"], [0, "≾"], [0, { v: "≿", n: 824, o: "≿̸" }], [0, "⊀"], [0, "⊁"], [0, { v: "⊂", n: 8402, o: "⊂⃒" }], [0, { v: "⊃", n: 8402, o: "⊃⃒" }], [0, "⊄"], [0, "⊅"], [0, "⊆"], [0, "⊇"], [0, "⊈"], [0, "⊉"], [0, { v: "⊊", n: 65024, o: "⊊︀" }], [0, { v: "⊋", n: 65024, o: "⊋︀" }], [1, "⊍"], [0, "⊎"], [0, { v: "⊏", n: 824, o: "⊏̸" }], [0, { v: "⊐", n: 824, o: "⊐̸" }], [0, "⊑"], [0, "⊒"], [0, { v: "⊓", n: 65024, o: "⊓︀" }], [0, { v: "⊔", n: 65024, o: "⊔︀" }], [0, "⊕"], [0, "⊖"], [0, "⊗"], [0, "⊘"], [0, "⊙"], [0, "⊚"], [0, "⊛"], [1, "⊝"], [0, "⊞"], [0, "⊟"], [0, "⊠"], [0, "⊡"], [0, "⊢"], [0, "⊣"], [0, "⊤"], [0, "⊥"], [1, "⊧"], [0, "⊨"], [0, "⊩"], [0, "⊪"], [0, "⊫"], [0, "⊬"], [0, "⊭"], [0, "⊮"], [0, "⊯"], [0, "⊰"], [1, "⊲"], [0, "⊳"], [0, { v: "⊴", n: 8402, o: "⊴⃒" }], [0, { v: "⊵", n: 8402, o: "⊵⃒" }], [0, "⊶"], [0, "⊷"], [0, "⊸"], [0, "⊹"], [0, "⊺"], [0, "⊻"], [1, "⊽"], [0, "⊾"], [0, "⊿"], [0, "⋀"], [0, "⋁"], [0, "⋂"], [0, "⋃"], [0, "⋄"], [0, "⋅"], [0, "⋆"], [0, "⋇"], [0, "⋈"], [0, "⋉"], [0, "⋊"], [0, "⋋"], [0, "⋌"], [0, "⋍"], [0, "⋎"], [0, "⋏"], [0, "⋐"], [0, "⋑"], [0, "⋒"], [0, "⋓"], [0, "⋔"], [0, "⋕"], [0, "⋖"], [0, "⋗"], [0, { v: "⋘", n: 824, o: "⋘̸" }], [0, { v: "⋙", n: 824, o: "⋙̸" }], [0, { v: "⋚", n: 65024, o: "⋚︀" }], [0, { v: "⋛", n: 65024, o: "⋛︀" }], [2, "⋞"], [0, "⋟"], [0, "⋠"], [0, "⋡"], [0, "⋢"], [0, "⋣"], [2, "⋦"], [0, "⋧"], [0, "⋨"], [0, "⋩"], [0, "⋪"], [0, "⋫"], [0, "⋬"], [0, "⋭"], [0, "⋮"], [0, "⋯"], [0, "⋰"], [0, "⋱"], [0, "⋲"], [0, "⋳"], [0, "⋴"], [0, { v: "⋵", n: 824, o: "⋵̸" }], [0, "⋶"], [0, "⋷"], [1, { v: "⋹", n: 824, o: "⋹̸" }], [0, "⋺"], [0, "⋻"], [0, "⋼"], [0, "⋽"], [0, "⋾"], [6, "⌅"], [0, "⌆"], [1, "⌈"], [0, "⌉"], [0, "⌊"], [0, "⌋"], [0, "⌌"], [0, "⌍"], [0, "⌎"], [0, "⌏"], [0, "⌐"], [1, "⌒"], [0, "⌓"], [1, "⌕"], [0, "⌖"], [5, "⌜"], [0, "⌝"], [0, "⌞"], [0, "⌟"], [2, "⌢"], [0, "⌣"], [9, "⌭"], [0, "⌮"], [7, "⌶"], [6, "⌽"], [1, "⌿"], [60, "⍼"], [51, "⎰"], [0, "⎱"], [2, "⎴"], [0, "⎵"], [0, "⎶"], [37, "⏜"], [0, "⏝"], [0, "⏞"], [0, "⏟"], [2, "⏢"], [4, "⏧"], [59, "␣"], [164, "Ⓢ"], [55, "─"], [1, "│"], [9, "┌"], [3, "┐"], [3, "└"], [3, "┘"], [3, "├"], [7, "┤"], [7, "┬"], [7, "┴"], [7, "┼"], [19, "═"], [0, "║"], [0, "╒"], [0, "╓"], [0, "╔"], [0, "╕"], [0, "╖"], [0, "╗"], [0, "╘"], [0, "╙"], [0, "╚"], [0, "╛"], [0, "╜"], [0, "╝"], [0, "╞"], [0, "╟"], [0, "╠"], [0, "╡"], [0, "╢"], [0, "╣"], [0, "╤"], [0, "╥"], [0, "╦"], [0, "╧"], [0, "╨"], [0, "╩"], [0, "╪"], [0, "╫"], [0, "╬"], [19, "▀"], [3, "▄"], [3, "█"], [8, "░"], [0, "▒"], [0, "▓"], [13, "□"], [8, "▪"], [0, "▫"], [1, "▭"], [0, "▮"], [2, "▱"], [1, "△"], [0, "▴"], [0, "▵"], [2, "▸"], [0, "▹"], [3, "▽"], [0, "▾"], [0, "▿"], [2, "◂"], [0, "◃"], [6, "◊"], [0, "○"], [32, "◬"], [2, "◯"], [8, "◸"], [0, "◹"], [0, "◺"], [0, "◻"], [0, "◼"], [8, "★"], [0, "☆"], [7, "☎"], [49, "♀"], [1, "♂"], [29, "♠"], [2, "♣"], [1, "♥"], [0, "♦"], [3, "♪"], [2, "♭"], [0, "♮"], [0, "♯"], [163, "✓"], [3, "✗"], [8, "✠"], [21, "✶"], [33, "❘"], [25, "❲"], [0, "❳"], [84, "⟈"], [0, "⟉"], [28, "⟦"], [0, "⟧"], [0, "⟨"], [0, "⟩"], [0, "⟪"], [0, "⟫"], [0, "⟬"], [0, "⟭"], [7, "⟵"], [0, "⟶"], [0, "⟷"], [0, "⟸"], [0, "⟹"], [0, "⟺"], [1, "⟼"], [2, "⟿"], [258, "⤂"], [0, "⤃"], [0, "⤄"], [0, "⤅"], [6, "⤌"], [0, "⤍"], [0, "⤎"], [0, "⤏"], [0, "⤐"], [0, "⤑"], [0, "⤒"], [0, "⤓"], [2, "⤖"], [2, "⤙"], [0, "⤚"], [0, "⤛"], [0, "⤜"], [0, "⤝"], [0, "⤞"], [0, "⤟"], [0, "⤠"], [2, "⤣"], [0, "⤤"], [0, "⤥"], [0, "⤦"], [0, "⤧"], [0, "⤨"], [0, "⤩"], [0, "⤪"], [8, { v: "⤳", n: 824, o: "⤳̸" }], [1, "⤵"], [0, "⤶"], [0, "⤷"], [0, "⤸"], [0, "⤹"], [2, "⤼"], [0, "⤽"], [7, "⥅"], [2, "⥈"], [0, "⥉"], [0, "⥊"], [0, "⥋"], [2, "⥎"], [0, "⥏"], [0, "⥐"], [0, "⥑"], [0, "⥒"], [0, "⥓"], [0, "⥔"], [0, "⥕"], [0, "⥖"], [0, "⥗"], [0, "⥘"], [0, "⥙"], [0, "⥚"], [0, "⥛"], [0, "⥜"], [0, "⥝"], [0, "⥞"], [0, "⥟"], [0, "⥠"], [0, "⥡"], [0, "⥢"], [0, "⥣"], [0, "⥤"], [0, "⥥"], [0, "⥦"], [0, "⥧"], [0, "⥨"], [0, "⥩"], [0, "⥪"], [0, "⥫"], [0, "⥬"], [0, "⥭"], [0, "⥮"], [0, "⥯"], [0, "⥰"], [0, "⥱"], [0, "⥲"], [0, "⥳"], [0, "⥴"], [0, "⥵"], [0, "⥶"], [1, "⥸"], [0, "⥹"], [1, "⥻"], [0, "⥼"], [0, "⥽"], [0, "⥾"], [0, "⥿"], [5, "⦅"], [0, "⦆"], [4, "⦋"], [0, "⦌"], [0, "⦍"], [0, "⦎"], [0, "⦏"], [0, "⦐"], [0, "⦑"], [0, "⦒"], [0, "⦓"], [0, "⦔"], [0, "⦕"], [0, "⦖"], [3, "⦚"], [1, "⦜"], [0, "⦝"], [6, "⦤"], [0, "⦥"], [0, "⦦"], [0, "⦧"], [0, "⦨"], [0, "⦩"], [0, "⦪"], [0, "⦫"], [0, "⦬"], [0, "⦭"], [0, "⦮"], [0, "⦯"], [0, "⦰"], [0, "⦱"], [0, "⦲"], [0, "⦳"], [0, "⦴"], [0, "⦵"], [0, "⦶"], [0, "⦷"], [1, "⦹"], [1, "⦻"], [0, "⦼"], [1, "⦾"], [0, "⦿"], [0, "⧀"], [0, "⧁"], [0, "⧂"], [0, "⧃"], [0, "⧄"], [0, "⧅"], [3, "⧉"], [3, "⧍"], [0, "⧎"], [0, { v: "⧏", n: 824, o: "⧏̸" }], [0, { v: "⧐", n: 824, o: "⧐̸" }], [11, "⧜"], [0, "⧝"], [0, "⧞"], [4, "⧣"], [0, "⧤"], [0, "⧥"], [5, "⧫"], [8, "⧴"], [1, "⧶"], [9, "⨀"], [0, "⨁"], [0, "⨂"], [1, "⨄"], [1, "⨆"], [5, "⨌"], [0, "⨍"], [2, "⨐"], [0, "⨑"], [0, "⨒"], [0, "⨓"], [0, "⨔"], [0, "⨕"], [0, "⨖"], [0, "⨗"], [10, "⨢"], [0, "⨣"], [0, "⨤"], [0, "⨥"], [0, "⨦"], [0, "⨧"], [1, "⨩"], [0, "⨪"], [2, "⨭"], [0, "⨮"], [0, "⨯"], [0, "⨰"], [0, "⨱"], [1, "⨳"], [0, "⨴"], [0, "⨵"], [0, "⨶"], [0, "⨷"], [0, "⨸"], [0, "⨹"], [0, "⨺"], [0, "⨻"], [0, "⨼"], [2, "⨿"], [0, "⩀"], [1, "⩂"], [0, "⩃"], [0, "⩄"], [0, "⩅"], [0, "⩆"], [0, "⩇"], [0, "⩈"], [0, "⩉"], [0, "⩊"], [0, "⩋"], [0, "⩌"], [0, "⩍"], [2, "⩐"], [2, "⩓"], [0, "⩔"], [0, "⩕"], [0, "⩖"], [0, "⩗"], [0, "⩘"], [1, "⩚"], [0, "⩛"], [0, "⩜"], [0, "⩝"], [1, "⩟"], [6, "⩦"], [3, "⩪"], [2, { v: "⩭", n: 824, o: "⩭̸" }], [0, "⩮"], [0, "⩯"], [0, { v: "⩰", n: 824, o: "⩰̸" }], [0, "⩱"], [0, "⩲"], [0, "⩳"], [0, "⩴"], [0, "⩵"], [1, "⩷"], [0, "⩸"], [0, "⩹"], [0, "⩺"], [0, "⩻"], [0, "⩼"], [0, { v: "⩽", n: 824, o: "⩽̸" }], [0, { v: "⩾", n: 824, o: "⩾̸" }], [0, "⩿"], [0, "⪀"], [0, "⪁"], [0, "⪂"], [0, "⪃"], [0, "⪄"], [0, "⪅"], [0, "⪆"], [0, "⪇"], [0, "⪈"], [0, "⪉"], [0, "⪊"], [0, "⪋"], [0, "⪌"], [0, "⪍"], [0, "⪎"], [0, "⪏"], [0, "⪐"], [0, "⪑"], [0, "⪒"], [0, "⪓"], [0, "⪔"], [0, "⪕"], [0, "⪖"], [0, "⪗"], [0, "⪘"], [0, "⪙"], [0, "⪚"], [2, "⪝"], [0, "⪞"], [0, "⪟"], [0, "⪠"], [0, { v: "⪡", n: 824, o: "⪡̸" }], [0, { v: "⪢", n: 824, o: "⪢̸" }], [1, "⪤"], [0, "⪥"], [0, "⪦"], [0, "⪧"], [0, "⪨"], [0, "⪩"], [0, "⪪"], [0, "⪫"], [0, { v: "⪬", n: 65024, o: "⪬︀" }], [0, { v: "⪭", n: 65024, o: "⪭︀" }], [0, "⪮"], [0, { v: "⪯", n: 824, o: "⪯̸" }], [0, { v: "⪰", n: 824, o: "⪰̸" }], [2, "⪳"], [0, "⪴"], [0, "⪵"], [0, "⪶"], [0, "⪷"], [0, "⪸"], [0, "⪹"], [0, "⪺"], [0, "⪻"], [0, "⪼"], [0, "⪽"], [0, "⪾"], [0, "⪿"], [0, "⫀"], [0, "⫁"], [0, "⫂"], [0, "⫃"], [0, "⫄"], [0, { v: "⫅", n: 824, o: "⫅̸" }], [0, { v: "⫆", n: 824, o: "⫆̸" }], [0, "⫇"], [0, "⫈"], [2, { v: "⫋", n: 65024, o: "⫋︀" }], [0, { v: "⫌", n: 65024, o: "⫌︀" }], [2, "⫏"], [0, "⫐"], [0, "⫑"], [0, "⫒"], [0, "⫓"], [0, "⫔"], [0, "⫕"], [0, "⫖"], [0, "⫗"], [0, "⫘"], [0, "⫙"], [0, "⫚"], [0, "⫛"], [8, "⫤"], [1, "⫦"], [0, "⫧"], [0, "⫨"], [0, "⫩"], [1, "⫫"], [0, "⫬"], [0, "⫭"], [0, "⫮"], [0, "⫯"], [0, "⫰"], [0, "⫱"], [0, "⫲"], [0, "⫳"], [9, { v: "⫽", n: 8421, o: "⫽⃥" }], [44343, { n: new Map(/* #__PURE__ */ restoreDiff([[56476, "𝒜"], [1, "𝒞"], [0, "𝒟"], [2, "𝒢"], [2, "𝒥"], [0, "𝒦"], [2, "𝒩"], [0, "𝒪"], [0, "𝒫"], [0, "𝒬"], [1, "𝒮"], [0, "𝒯"], [0, "𝒰"], [0, "𝒱"], [0, "𝒲"], [0, "𝒳"], [0, "𝒴"], [0, "𝒵"], [0, "𝒶"], [0, "𝒷"], [0, "𝒸"], [0, "𝒹"], [1, "𝒻"], [1, "𝒽"], [0, "𝒾"], [0, "𝒿"], [0, "𝓀"], [0, "𝓁"], [0, "𝓂"], [0, "𝓃"], [1, "𝓅"], [0, "𝓆"], [0, "𝓇"], [0, "𝓈"], [0, "𝓉"], [0, "𝓊"], [0, "𝓋"], [0, "𝓌"], [0, "𝓍"], [0, "𝓎"], [0, "𝓏"], [52, "𝔄"], [0, "𝔅"], [1, "𝔇"], [0, "𝔈"], [0, "𝔉"], [0, "𝔊"], [2, "𝔍"], [0, "𝔎"], [0, "𝔏"], [0, "𝔐"], [0, "𝔑"], [0, "𝔒"], [0, "𝔓"], [0, "𝔔"], [1, "𝔖"], [0, "𝔗"], [0, "𝔘"], [0, "𝔙"], [0, "𝔚"], [0, "𝔛"], [0, "𝔜"], [1, "𝔞"], [0, "𝔟"], [0, "𝔠"], [0, "𝔡"], [0, "𝔢"], [0, "𝔣"], [0, "𝔤"], [0, "𝔥"], [0, "𝔦"], [0, "𝔧"], [0, "𝔨"], [0, "𝔩"], [0, "𝔪"], [0, "𝔫"], [0, "𝔬"], [0, "𝔭"], [0, "𝔮"], [0, "𝔯"], [0, "𝔰"], [0, "𝔱"], [0, "𝔲"], [0, "𝔳"], [0, "𝔴"], [0, "𝔵"], [0, "𝔶"], [0, "𝔷"], [0, "𝔸"], [0, "𝔹"], [1, "𝔻"], [0, "𝔼"], [0, "𝔽"], [0, "𝔾"], [1, "𝕀"], [0, "𝕁"], [0, "𝕂"], [0, "𝕃"], [0, "𝕄"], [1, "𝕆"], [3, "𝕊"], [0, "𝕋"], [0, "𝕌"], [0, "𝕍"], [0, "𝕎"], [0, "𝕏"], [0, "𝕐"], [1, "𝕒"], [0, "𝕓"], [0, "𝕔"], [0, "𝕕"], [0, "𝕖"], [0, "𝕗"], [0, "𝕘"], [0, "𝕙"], [0, "𝕚"], [0, "𝕛"], [0, "𝕜"], [0, "𝕝"], [0, "𝕞"], [0, "𝕟"], [0, "𝕠"], [0, "𝕡"], [0, "𝕢"], [0, "𝕣"], [0, "𝕤"], [0, "𝕥"], [0, "𝕦"], [0, "𝕧"], [0, "𝕨"], [0, "𝕩"], [0, "𝕪"], [0, "𝕫"]])) }], [8906, "ff"], [0, "fi"], [0, "fl"], [0, "ffi"], [0, "ffl"]])); +//# sourceMappingURL=encode-html.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/generated/encode-html.js.map b/node_modules/entities/lib/generated/encode-html.js.map new file mode 100644 index 0000000..2d2d9be --- /dev/null +++ b/node_modules/entities/lib/generated/encode-html.js.map @@ -0,0 +1 @@ +{"version":3,"file":"encode-html.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["generated/encode-html.ts"],"names":[],"mappings":";AAAA,8CAA8C;;AAM9C,SAAS,WAAW,CAChB,GAAM;IAEN,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACjC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,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C"} \ No newline at end of file diff --git a/node_modules/entities/lib/index.d.ts b/node_modules/entities/lib/index.d.ts index 68c8cd5..dd4eb11 100644 --- a/node_modules/entities/lib/index.d.ts +++ b/node_modules/entities/lib/index.d.ts @@ -1,27 +1,96 @@ +import { DecodingMode } from "./decode.js"; +/** The level of entities to support. */ +export declare enum EntityLevel { + /** Support only XML entities. */ + XML = 0, + /** Support HTML entities, which are a superset of XML entities. */ + HTML = 1 +} +export declare enum EncodingMode { + /** + * The output is UTF-8 encoded. Only characters that need escaping within + * XML will be escaped. + */ + UTF8 = 0, + /** + * The output consists only of ASCII characters. Characters that need + * escaping within HTML, and characters that aren't ASCII characters will + * be escaped. + */ + ASCII = 1, + /** + * Encode all characters that have an equivalent entity, as well as all + * characters that are not ASCII characters. + */ + Extensive = 2, + /** + * Encode all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + Attribute = 3, + /** + * Encode all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + Text = 4 +} +export interface DecodingOptions { + /** + * The level of entities to support. + * @default {@link EntityLevel.XML} + */ + level?: EntityLevel; + /** + * Decoding mode. If `Legacy`, will support legacy entities not terminated + * with a semicolon (`;`). + * + * Always `Strict` for XML. For HTML, set this to `true` if you are parsing + * an attribute value. + * + * The deprecated `decodeStrict` function defaults this to `Strict`. + * + * @default {@link DecodingMode.Legacy} + */ + mode?: DecodingMode | undefined; +} /** * Decodes a string with entities. * * @param data String to decode. - * @param level Optional level to decode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `decodeXML` or `decodeHTML` directly. + * @param options Decoding options. */ -export declare function decode(data: string, level?: number): string; +export declare function decode(data: string, options?: DecodingOptions | EntityLevel): string; /** * Decodes a string with entities. Does not allow missing trailing semicolons for entities. * * @param data String to decode. - * @param level Optional level to decode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `decodeHTMLStrict` or `decodeXML` directly. + * @param options Decoding options. + * @deprecated Use `decode` with the `mode` set to `Strict`. */ -export declare function decodeStrict(data: string, level?: number): string; +export declare function decodeStrict(data: string, options?: DecodingOptions | EntityLevel): string; +/** + * Options for `encode`. + */ +export interface EncodingOptions { + /** + * The level of entities to support. + * @default {@link EntityLevel.XML} + */ + level?: EntityLevel; + /** + * Output format. + * @default {@link EncodingMode.Extensive} + */ + mode?: EncodingMode; +} /** * Encodes a string with entities. * * @param data String to encode. - * @param level Optional level to encode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `encodeHTML`, `encodeXML` or `encodeNonAsciiHTML` directly. + * @param options Encoding options. */ -export declare function encode(data: string, level?: number): string; -export { encodeXML, encodeHTML, encodeNonAsciiHTML, escape, escapeUTF8, encodeHTML as encodeHTML4, encodeHTML as encodeHTML5, } from "./encode"; -export { decodeXML, decodeHTML, decodeHTMLStrict, decodeHTML as decodeHTML4, decodeHTML as decodeHTML5, decodeHTMLStrict as decodeHTML4Strict, decodeHTMLStrict as decodeHTML5Strict, decodeXML as decodeXMLStrict, } from "./decode"; +export declare function encode(data: string, options?: EncodingOptions | EntityLevel): string; +export { encodeXML, escape, escapeUTF8, escapeAttribute, escapeText, } from "./escape.js"; +export { encodeHTML, encodeNonAsciiHTML, encodeHTML as encodeHTML4, encodeHTML as encodeHTML5, } from "./encode.js"; +export { EntityDecoder, DecodingMode, decodeXML, decodeHTML, decodeHTMLStrict, decodeHTMLAttribute, decodeHTML as decodeHTML4, decodeHTML as decodeHTML5, decodeHTMLStrict as decodeHTML4Strict, decodeHTMLStrict as decodeHTML5Strict, decodeXML as decodeXMLStrict, } from "./decode.js"; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/entities/lib/index.d.ts.map b/node_modules/entities/lib/index.d.ts.map index 24b32ca..cfeef9f 100644 --- a/node_modules/entities/lib/index.d.ts.map +++ b/node_modules/entities/lib/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAEjE;AAED;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAE3D;AAED,OAAO,EACH,SAAS,EACT,UAAU,EACV,kBAAkB,EAClB,MAAM,EACN,UAAU,EAEV,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,GAC5B,MAAM,UAAU,CAAC;AAElB,OAAO,EACH,SAAS,EACT,UAAU,EACV,gBAAgB,EAEhB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,gBAAgB,IAAI,iBAAiB,EACrC,gBAAgB,IAAI,iBAAiB,EACrC,SAAS,IAAI,eAAe,GAC/B,MAAM,UAAU,CAAC"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyB,YAAY,EAAE,MAAM,aAAa,CAAC;AASlE,wCAAwC;AACxC,oBAAY,WAAW;IACnB,iCAAiC;IACjC,GAAG,IAAI;IACP,mEAAmE;IACnE,IAAI,IAAI;CACX;AAED,oBAAY,YAAY;IACpB;;;OAGG;IACH,IAAI,IAAA;IACJ;;;;OAIG;IACH,KAAK,IAAA;IACL;;;OAGG;IACH,SAAS,IAAA;IACT;;;OAGG;IACH,SAAS,IAAA;IACT;;;OAGG;IACH,IAAI,IAAA;CACP;AAED,MAAM,WAAW,eAAe;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB;;;;;;;;;;OAUG;IACH,IAAI,CAAC,EAAE,YAAY,GAAG,SAAS,CAAC;CACnC;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CASR;AAED;;;;;;GAMG;AACH,wBAAgB,YAAY,CACxB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CAKR;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC5B;;;OAGG;IACH,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB;;;OAGG;IACH,IAAI,CAAC,EAAE,YAAY,CAAC;CACvB;AAED;;;;;GAKG;AACH,wBAAgB,MAAM,CAClB,IAAI,EAAE,MAAM,EACZ,OAAO,GAAE,eAAe,GAAG,WAA6B,GACzD,MAAM,CAkBR;AAED,OAAO,EACH,SAAS,EACT,MAAM,EACN,UAAU,EACV,eAAe,EACf,UAAU,GACb,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,UAAU,EACV,kBAAkB,EAElB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,GAC5B,MAAM,aAAa,CAAC;AAErB,OAAO,EACH,aAAa,EACb,YAAY,EACZ,SAAS,EACT,UAAU,EACV,gBAAgB,EAChB,mBAAmB,EAEnB,UAAU,IAAI,WAAW,EACzB,UAAU,IAAI,WAAW,EACzB,gBAAgB,IAAI,iBAAiB,EACrC,gBAAgB,IAAI,iBAAiB,EACrC,SAAS,IAAI,eAAe,GAC/B,MAAM,aAAa,CAAC"} \ No newline at end of file diff --git a/node_modules/entities/lib/index.js b/node_modules/entities/lib/index.js index 1b8c3da..f809b1b 100644 --- a/node_modules/entities/lib/index.js +++ b/node_modules/entities/lib/index.js @@ -1,57 +1,126 @@ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); -exports.decodeXMLStrict = exports.decodeHTML5Strict = exports.decodeHTML4Strict = exports.decodeHTML5 = exports.decodeHTML4 = exports.decodeHTMLStrict = exports.decodeHTML = exports.decodeXML = exports.encodeHTML5 = exports.encodeHTML4 = exports.escapeUTF8 = exports.escape = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.encodeXML = exports.encode = exports.decodeStrict = exports.decode = void 0; -var decode_1 = require("./decode"); -var encode_1 = require("./encode"); +exports.decodeXMLStrict = exports.decodeHTML5Strict = exports.decodeHTML4Strict = exports.decodeHTML5 = exports.decodeHTML4 = exports.decodeHTMLAttribute = exports.decodeHTMLStrict = exports.decodeHTML = exports.decodeXML = exports.DecodingMode = exports.EntityDecoder = exports.encodeHTML5 = exports.encodeHTML4 = exports.encodeNonAsciiHTML = exports.encodeHTML = exports.escapeText = exports.escapeAttribute = exports.escapeUTF8 = exports.escape = exports.encodeXML = exports.encode = exports.decodeStrict = exports.decode = exports.EncodingMode = exports.EntityLevel = void 0; +var decode_js_1 = require("./decode.js"); +var encode_js_1 = require("./encode.js"); +var escape_js_1 = require("./escape.js"); +/** The level of entities to support. */ +var EntityLevel; +(function (EntityLevel) { + /** Support only XML entities. */ + EntityLevel[EntityLevel["XML"] = 0] = "XML"; + /** Support HTML entities, which are a superset of XML entities. */ + EntityLevel[EntityLevel["HTML"] = 1] = "HTML"; +})(EntityLevel = exports.EntityLevel || (exports.EntityLevel = {})); +var EncodingMode; +(function (EncodingMode) { + /** + * The output is UTF-8 encoded. Only characters that need escaping within + * XML will be escaped. + */ + EncodingMode[EncodingMode["UTF8"] = 0] = "UTF8"; + /** + * The output consists only of ASCII characters. Characters that need + * escaping within HTML, and characters that aren't ASCII characters will + * be escaped. + */ + EncodingMode[EncodingMode["ASCII"] = 1] = "ASCII"; + /** + * Encode all characters that have an equivalent entity, as well as all + * characters that are not ASCII characters. + */ + EncodingMode[EncodingMode["Extensive"] = 2] = "Extensive"; + /** + * Encode all characters that have to be escaped in HTML attributes, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[EncodingMode["Attribute"] = 3] = "Attribute"; + /** + * Encode all characters that have to be escaped in HTML text, + * following {@link https://html.spec.whatwg.org/multipage/parsing.html#escapingString}. + */ + EncodingMode[EncodingMode["Text"] = 4] = "Text"; +})(EncodingMode = exports.EncodingMode || (exports.EncodingMode = {})); /** * Decodes a string with entities. * * @param data String to decode. - * @param level Optional level to decode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `decodeXML` or `decodeHTML` directly. + * @param options Decoding options. */ -function decode(data, level) { - return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTML)(data); +function decode(data, options) { + if (options === void 0) { options = EntityLevel.XML; } + var level = typeof options === "number" ? options : options.level; + if (level === EntityLevel.HTML) { + var mode = typeof options === "object" ? options.mode : undefined; + return (0, decode_js_1.decodeHTML)(data, mode); + } + return (0, decode_js_1.decodeXML)(data); } exports.decode = decode; /** * Decodes a string with entities. Does not allow missing trailing semicolons for entities. * * @param data String to decode. - * @param level Optional level to decode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `decodeHTMLStrict` or `decodeXML` directly. + * @param options Decoding options. + * @deprecated Use `decode` with the `mode` set to `Strict`. */ -function decodeStrict(data, level) { - return (!level || level <= 0 ? decode_1.decodeXML : decode_1.decodeHTMLStrict)(data); +function decodeStrict(data, options) { + var _a; + if (options === void 0) { options = EntityLevel.XML; } + var opts = typeof options === "number" ? { level: options } : options; + (_a = opts.mode) !== null && _a !== void 0 ? _a : (opts.mode = decode_js_1.DecodingMode.Strict); + return decode(data, opts); } exports.decodeStrict = decodeStrict; /** * Encodes a string with entities. * * @param data String to encode. - * @param level Optional level to encode at. 0 = XML, 1 = HTML. Default is 0. - * @deprecated Use `encodeHTML`, `encodeXML` or `encodeNonAsciiHTML` directly. + * @param options Encoding options. */ -function encode(data, level) { - return (!level || level <= 0 ? encode_1.encodeXML : encode_1.encodeHTML)(data); +function encode(data, options) { + if (options === void 0) { options = EntityLevel.XML; } + var opts = typeof options === "number" ? { level: options } : options; + // Mode `UTF8` just escapes XML entities + if (opts.mode === EncodingMode.UTF8) + return (0, escape_js_1.escapeUTF8)(data); + if (opts.mode === EncodingMode.Attribute) + return (0, escape_js_1.escapeAttribute)(data); + if (opts.mode === EncodingMode.Text) + return (0, escape_js_1.escapeText)(data); + if (opts.level === EntityLevel.HTML) { + if (opts.mode === EncodingMode.ASCII) { + return (0, encode_js_1.encodeNonAsciiHTML)(data); + } + return (0, encode_js_1.encodeHTML)(data); + } + // ASCII and Extensive are equivalent + return (0, escape_js_1.encodeXML)(data); } exports.encode = encode; -var encode_2 = require("./encode"); -Object.defineProperty(exports, "encodeXML", { enumerable: true, get: function () { return encode_2.encodeXML; } }); -Object.defineProperty(exports, "encodeHTML", { enumerable: true, get: function () { return encode_2.encodeHTML; } }); -Object.defineProperty(exports, "encodeNonAsciiHTML", { enumerable: true, get: function () { return encode_2.encodeNonAsciiHTML; } }); -Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return encode_2.escape; } }); -Object.defineProperty(exports, "escapeUTF8", { enumerable: true, get: function () { return encode_2.escapeUTF8; } }); +var escape_js_2 = require("./escape.js"); +Object.defineProperty(exports, "encodeXML", { enumerable: true, get: function () { return escape_js_2.encodeXML; } }); +Object.defineProperty(exports, "escape", { enumerable: true, get: function () { return escape_js_2.escape; } }); +Object.defineProperty(exports, "escapeUTF8", { enumerable: true, get: function () { return escape_js_2.escapeUTF8; } }); +Object.defineProperty(exports, "escapeAttribute", { enumerable: true, get: function () { return escape_js_2.escapeAttribute; } }); +Object.defineProperty(exports, "escapeText", { enumerable: true, get: function () { return escape_js_2.escapeText; } }); +var encode_js_2 = require("./encode.js"); +Object.defineProperty(exports, "encodeHTML", { enumerable: true, get: function () { return encode_js_2.encodeHTML; } }); +Object.defineProperty(exports, "encodeNonAsciiHTML", { enumerable: true, get: function () { return encode_js_2.encodeNonAsciiHTML; } }); // Legacy aliases (deprecated) -Object.defineProperty(exports, "encodeHTML4", { enumerable: true, get: function () { return encode_2.encodeHTML; } }); -Object.defineProperty(exports, "encodeHTML5", { enumerable: true, get: function () { return encode_2.encodeHTML; } }); -var decode_2 = require("./decode"); -Object.defineProperty(exports, "decodeXML", { enumerable: true, get: function () { return decode_2.decodeXML; } }); -Object.defineProperty(exports, "decodeHTML", { enumerable: true, get: function () { return decode_2.decodeHTML; } }); -Object.defineProperty(exports, "decodeHTMLStrict", { enumerable: true, get: function () { return decode_2.decodeHTMLStrict; } }); +Object.defineProperty(exports, "encodeHTML4", { enumerable: true, get: function () { return encode_js_2.encodeHTML; } }); +Object.defineProperty(exports, "encodeHTML5", { enumerable: true, get: function () { return encode_js_2.encodeHTML; } }); +var decode_js_2 = require("./decode.js"); +Object.defineProperty(exports, "EntityDecoder", { enumerable: true, get: function () { return decode_js_2.EntityDecoder; } }); +Object.defineProperty(exports, "DecodingMode", { enumerable: true, get: function () { return decode_js_2.DecodingMode; } }); +Object.defineProperty(exports, "decodeXML", { enumerable: true, get: function () { return decode_js_2.decodeXML; } }); +Object.defineProperty(exports, "decodeHTML", { enumerable: true, get: function () { return decode_js_2.decodeHTML; } }); +Object.defineProperty(exports, "decodeHTMLStrict", { enumerable: true, get: function () { return decode_js_2.decodeHTMLStrict; } }); +Object.defineProperty(exports, "decodeHTMLAttribute", { enumerable: true, get: function () { return decode_js_2.decodeHTMLAttribute; } }); // Legacy aliases (deprecated) -Object.defineProperty(exports, "decodeHTML4", { enumerable: true, get: function () { return decode_2.decodeHTML; } }); -Object.defineProperty(exports, "decodeHTML5", { enumerable: true, get: function () { return decode_2.decodeHTML; } }); -Object.defineProperty(exports, "decodeHTML4Strict", { enumerable: true, get: function () { return decode_2.decodeHTMLStrict; } }); -Object.defineProperty(exports, "decodeHTML5Strict", { enumerable: true, get: function () { return decode_2.decodeHTMLStrict; } }); -Object.defineProperty(exports, "decodeXMLStrict", { enumerable: true, get: function () { return decode_2.decodeXML; } }); +Object.defineProperty(exports, "decodeHTML4", { enumerable: true, get: function () { return decode_js_2.decodeHTML; } }); +Object.defineProperty(exports, "decodeHTML5", { enumerable: true, get: function () { return decode_js_2.decodeHTML; } }); +Object.defineProperty(exports, "decodeHTML4Strict", { enumerable: true, get: function () { return decode_js_2.decodeHTMLStrict; } }); +Object.defineProperty(exports, "decodeHTML5Strict", { enumerable: true, get: function () { return decode_js_2.decodeHTMLStrict; } }); +Object.defineProperty(exports, "decodeXMLStrict", { enumerable: true, get: function () { return decode_js_2.decodeXML; } }); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/entities/lib/index.js.map b/node_modules/entities/lib/index.js.map new file mode 100644 index 0000000..2ef7751 --- /dev/null +++ b/node_modules/entities/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"https://raw.githubusercontent.com/fb55/entities/61afd4701eaa736978b13c7351cd3de9a96b04bc/src/","sources":["index.ts"],"names":[],"mappings":";;;AAAA,yCAAkE;AAClE,yCAA6D;AAC7D,yCAKqB;AAErB,wCAAwC;AACxC,IAAY,WAKX;AALD,WAAY,WAAW;IACnB,iCAAiC;IACjC,2CAAO,CAAA;IACP,mEAAmE;IACnE,6CAAQ,CAAA;AACZ,CAAC,EALW,WAAW,GAAX,mBAAW,KAAX,mBAAW,QAKtB;AAED,IAAY,YA2BX;AA3BD,WAAY,YAAY;IACpB;;;OAGG;IACH,+CAAI,CAAA;IACJ;;;;OAIG;IACH,iDAAK,CAAA;IACL;;;OAGG;IACH,yDAAS,CAAA;IACT;;;OAGG;IACH,yDAAS,CAAA;IACT;;;OAGG;IACH,+CAAI,CAAA;AACR,CAAC,EA3BW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QA2BvB;AAsBD;;;;;GAKG;AACH,SAAgB,MAAM,CAClB,IAAY,EACZ,OAAwD;IAAxD,wBAAA,EAAA,UAAyC,WAAW,CAAC,GAAG;IAExD,IAAM,KAAK,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC;I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AAA,sBAAU,EAAC,IAAI,CAAC,CAAC;IAE7D,IAAI,IAAI,CAAC,KAAK,KAAK,WAAW,CAAC,IAAI,EAAE;QACjC,IAAI,IAAI,CAAC,IAAI,KAAK,YAAY,CAAC,KAAK,EAAE;YAClC,OAAO,IAAA,8BAAkB,EAAC,IAAI,CAAC,CAAC;SACnC;QAED,OAAO,IAAA,sBAAU,EAAC,IAAI,CAAC,CAAC;KAC3B;IAED,qCAAqC;IACrC,OAAO,IAAA,qBAAS,EAAC,IAAI,CAAC,CAAC;AAC3B,CAAC;AArBD,wBAqBC;AAED,yCAMqB;AALjB,sGAAA,SAAS,OAAA;AACT,mGAAA,MAAM,OAAA;AACN,uGAAA,UAAU,OAAA;AACV,4GAAA,eAAe,OAAA;AACf,uGAAA,UAAU,OAAA;AAGd,yCAMqB;AALjB,uGAAA,UAAU,OAAA;AACV,+GAAA,kBAAkB,OAAA;AAClB,8BAA8B;AAC9B,wGAAA,UAAU,OAAe;AACzB,wGAAA,UAAU,OAAe;AAG7B,yCAaqB;AAZjB,0GAAA,aAAa,OAAA;AACb,yGAAA,YAAY,OAAA;AACZ,sGAAA,SAAS,OAAA;AACT,uGAAA,UAAU,OAAA;AACV,6GAAA,gBAAgB,OAAA;AAChB,gHAAA,mBAAmB,OAAA;AACnB,8BAA8B;AAC9B,wGAAA,UAAU,OAAe;AACzB,wGAAA,UAAU,OAAe;AACzB,8GAAA,gBAAgB,OAAqB;AACrC,8GAAA,gBAAgB,OAAqB;AACrC,4GAAA,SAAS,OAAmB"} \ No newline at end of file diff --git a/node_modules/entities/lib/maps/decode.json b/node_modules/entities/lib/maps/decode.json deleted file mode 100644 index 80ef449..0000000 --- a/node_modules/entities/lib/maps/decode.json +++ /dev/null @@ -1 +0,0 @@ -{"0":65533,"128":8364,"130":8218,"131":402,"132":8222,"133":8230,"134":8224,"135":8225,"136":710,"137":8240,"138":352,"139":8249,"140":338,"142":381,"145":8216,"146":8217,"147":8220,"148":8221,"149":8226,"150":8211,"151":8212,"152":732,"153":8482,"154":353,"155":8250,"156":339,"158":382,"159":376} diff --git a/node_modules/entities/lib/maps/entities.json b/node_modules/entities/lib/maps/entities.json deleted file mode 100644 index c5b1c4e..0000000 --- a/node_modules/entities/lib/maps/entities.json +++ /dev/null @@ -1 +0,0 @@ -{"Aacute":"Á","aacute":"á","Abreve":"Ă","abreve":"ă","ac":"∾","acd":"∿","acE":"∾̳","Acirc":"Â","acirc":"â","acute":"´","Acy":"А","acy":"а","AElig":"Æ","aelig":"æ","af":"⁡","Afr":"𝔄","afr":"𝔞","Agrave":"À","agrave":"à","alefsym":"ℵ","aleph":"ℵ","Alpha":"Α","alpha":"α","Amacr":"Ā","amacr":"ā","amalg":"⨿","amp":"&","AMP":"&","andand":"⩕","And":"⩓","and":"∧","andd":"⩜","andslope":"⩘","andv":"⩚","ang":"∠","ange":"⦤","angle":"∠","angmsdaa":"⦨","angmsdab":"⦩","angmsdac":"⦪","angmsdad":"⦫","angmsdae":"⦬","angmsdaf":"⦭","angmsdag":"⦮","angmsdah":"⦯","angmsd":"∡","angrt":"∟","angrtvb":"⊾","angrtvbd":"⦝","angsph":"∢","angst":"Å","angzarr":"⍼","Aogon":"Ą","aogon":"ą","Aopf":"𝔸","aopf":"𝕒","apacir":"⩯","ap":"≈","apE":"⩰","ape":"≊","apid":"≋","apos":"'","ApplyFunction":"⁡","approx":"≈","approxeq":"≊","Aring":"Å","aring":"å","Ascr":"𝒜","ascr":"𝒶","Assign":"≔","ast":"*","asymp":"≈","asympeq":"≍","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","awconint":"∳","awint":"⨑","backcong":"≌","backepsilon":"϶","backprime":"‵","backsim":"∽","backsimeq":"⋍","Backslash":"∖","Barv":"⫧","barvee":"⊽","barwed":"⌅","Barwed":"⌆","barwedge":"⌅","bbrk":"⎵","bbrktbrk":"⎶","bcong":"≌","Bcy":"Б","bcy":"б","bdquo":"„","becaus":"∵","because":"∵","Because":"∵","bemptyv":"⦰","bepsi":"϶","bernou":"ℬ","Bernoullis":"ℬ","Beta":"Β","beta":"β","beth":"ℶ","between":"≬","Bfr":"𝔅","bfr":"𝔟","bigcap":"⋂","bigcirc":"◯","bigcup":"⋃","bigodot":"⨀","bigoplus":"⨁","bigotimes":"⨂","bigsqcup":"⨆","bigstar":"★","bigtriangledown":"▽","bigtriangleup":"△","biguplus":"⨄","bigvee":"⋁","bigwedge":"⋀","bkarow":"⤍","blacklozenge":"⧫","blacksquare":"▪","blacktriangle":"▴","blacktriangledown":"▾","blacktriangleleft":"◂","blacktriangleright":"▸","blank":"␣","blk12":"▒","blk14":"░","blk34":"▓","block":"█","bne":"=⃥","bnequiv":"≡⃥","bNot":"⫭","bnot":"⌐","Bopf":"𝔹","bopf":"𝕓","bot":"⊥","bottom":"⊥","bowtie":"⋈","boxbox":"⧉","boxdl":"┐","boxdL":"╕","boxDl":"╖","boxDL":"╗","boxdr":"┌","boxdR":"╒","boxDr":"╓","boxDR":"╔","boxh":"─","boxH":"═","boxhd":"┬","boxHd":"╤","boxhD":"╥","boxHD":"╦","boxhu":"┴","boxHu":"╧","boxhU":"╨","boxHU":"╩","boxminus":"⊟","boxplus":"⊞","boxtimes":"⊠","boxul":"┘","boxuL":"╛","boxUl":"╜","boxUL":"╝","boxur":"└","boxuR":"╘","boxUr":"╙","boxUR":"╚","boxv":"│","boxV":"║","boxvh":"┼","boxvH":"╪","boxVh":"╫","boxVH":"╬","boxvl":"┤","boxvL":"╡","boxVl":"╢","boxVL":"╣","boxvr":"├","boxvR":"╞","boxVr":"╟","boxVR":"╠","bprime":"‵","breve":"˘","Breve":"˘","brvbar":"¦","bscr":"𝒷","Bscr":"ℬ","bsemi":"⁏","bsim":"∽","bsime":"⋍","bsolb":"⧅","bsol":"\\","bsolhsub":"⟈","bull":"•","bullet":"•","bump":"≎","bumpE":"⪮","bumpe":"≏","Bumpeq":"≎","bumpeq":"≏","Cacute":"Ć","cacute":"ć","capand":"⩄","capbrcup":"⩉","capcap":"⩋","cap":"∩","Cap":"⋒","capcup":"⩇","capdot":"⩀","CapitalDifferentialD":"ⅅ","caps":"∩︀","caret":"⁁","caron":"ˇ","Cayleys":"ℭ","ccaps":"⩍","Ccaron":"Č","ccaron":"č","Ccedil":"Ç","ccedil":"ç","Ccirc":"Ĉ","ccirc":"ĉ","Cconint":"∰","ccups":"⩌","ccupssm":"⩐","Cdot":"Ċ","cdot":"ċ","cedil":"¸","Cedilla":"¸","cemptyv":"⦲","cent":"¢","centerdot":"·","CenterDot":"·","cfr":"𝔠","Cfr":"ℭ","CHcy":"Ч","chcy":"ч","check":"✓","checkmark":"✓","Chi":"Χ","chi":"χ","circ":"ˆ","circeq":"≗","circlearrowleft":"↺","circlearrowright":"↻","circledast":"⊛","circledcirc":"⊚","circleddash":"⊝","CircleDot":"⊙","circledR":"®","circledS":"Ⓢ","CircleMinus":"⊖","CirclePlus":"⊕","CircleTimes":"⊗","cir":"○","cirE":"⧃","cire":"≗","cirfnint":"⨐","cirmid":"⫯","cirscir":"⧂","ClockwiseContourIntegral":"∲","CloseCurlyDoubleQuote":"”","CloseCurlyQuote":"’","clubs":"♣","clubsuit":"♣","colon":":","Colon":"∷","Colone":"⩴","colone":"≔","coloneq":"≔","comma":",","commat":"@","comp":"∁","compfn":"∘","complement":"∁","complexes":"ℂ","cong":"≅","congdot":"⩭","Congruent":"≡","conint":"∮","Conint":"∯","ContourIntegral":"∮","copf":"𝕔","Copf":"ℂ","coprod":"∐","Coproduct":"∐","copy":"©","COPY":"©","copysr":"℗","CounterClockwiseContourIntegral":"∳","crarr":"↵","cross":"✗","Cross":"⨯","Cscr":"𝒞","cscr":"𝒸","csub":"⫏","csube":"⫑","csup":"⫐","csupe":"⫒","ctdot":"⋯","cudarrl":"⤸","cudarrr":"⤵","cuepr":"⋞","cuesc":"⋟","cularr":"↶","cularrp":"⤽","cupbrcap":"⩈","cupcap":"⩆","CupCap":"≍","cup":"∪","Cup":"⋓","cupcup":"⩊","cupdot":"⊍","cupor":"⩅","cups":"∪︀","curarr":"↷","curarrm":"⤼","curlyeqprec":"⋞","curlyeqsucc":"⋟","curlyvee":"⋎","curlywedge":"⋏","curren":"¤","curvearrowleft":"↶","curvearrowright":"↷","cuvee":"⋎","cuwed":"⋏","cwconint":"∲","cwint":"∱","cylcty":"⌭","dagger":"†","Dagger":"‡","daleth":"ℸ","darr":"↓","Darr":"↡","dArr":"⇓","dash":"‐","Dashv":"⫤","dashv":"⊣","dbkarow":"⤏","dblac":"˝","Dcaron":"Ď","dcaron":"ď","Dcy":"Д","dcy":"д","ddagger":"‡","ddarr":"⇊","DD":"ⅅ","dd":"ⅆ","DDotrahd":"⤑","ddotseq":"⩷","deg":"°","Del":"∇","Delta":"Δ","delta":"δ","demptyv":"⦱","dfisht":"⥿","Dfr":"𝔇","dfr":"𝔡","dHar":"⥥","dharl":"⇃","dharr":"⇂","DiacriticalAcute":"´","DiacriticalDot":"˙","DiacriticalDoubleAcute":"˝","DiacriticalGrave":"`","DiacriticalTilde":"˜","diam":"⋄","diamond":"⋄","Diamond":"⋄","diamondsuit":"♦","diams":"♦","die":"¨","DifferentialD":"ⅆ","digamma":"ϝ","disin":"⋲","div":"÷","divide":"÷","divideontimes":"⋇","divonx":"⋇","DJcy":"Ђ","djcy":"ђ","dlcorn":"⌞","dlcrop":"⌍","dollar":"$","Dopf":"𝔻","dopf":"𝕕","Dot":"¨","dot":"˙","DotDot":"⃜","doteq":"≐","doteqdot":"≑","DotEqual":"≐","dotminus":"∸","dotplus":"∔","dotsquare":"⊡","doublebarwedge":"⌆","DoubleContourIntegral":"∯","DoubleDot":"¨","DoubleDownArrow":"⇓","DoubleLeftArrow":"⇐","DoubleLeftRightArrow":"⇔","DoubleLeftTee":"⫤","DoubleLongLeftArrow":"⟸","DoubleLongLeftRightArrow":"⟺","DoubleLongRightArrow":"⟹","DoubleRightArrow":"⇒","DoubleRightTee":"⊨","DoubleUpArrow":"⇑","DoubleUpDownArrow":"⇕","DoubleVerticalBar":"∥","DownArrowBar":"⤓","downarrow":"↓","DownArrow":"↓","Downarrow":"⇓","DownArrowUpArrow":"⇵","DownBreve":"̑","downdownarrows":"⇊","downharpoonleft":"⇃","downharpoonright":"⇂","DownLeftRightVector":"⥐","DownLeftTeeVector":"⥞","DownLeftVectorBar":"⥖","DownLeftVector":"↽","DownRightTeeVector":"⥟","DownRightVectorBar":"⥗","DownRightVector":"⇁","DownTeeArrow":"↧","DownTee":"⊤","drbkarow":"⤐","drcorn":"⌟","drcrop":"⌌","Dscr":"𝒟","dscr":"𝒹","DScy":"Ѕ","dscy":"ѕ","dsol":"⧶","Dstrok":"Đ","dstrok":"đ","dtdot":"⋱","dtri":"▿","dtrif":"▾","duarr":"⇵","duhar":"⥯","dwangle":"⦦","DZcy":"Џ","dzcy":"џ","dzigrarr":"⟿","Eacute":"É","eacute":"é","easter":"⩮","Ecaron":"Ě","ecaron":"ě","Ecirc":"Ê","ecirc":"ê","ecir":"≖","ecolon":"≕","Ecy":"Э","ecy":"э","eDDot":"⩷","Edot":"Ė","edot":"ė","eDot":"≑","ee":"ⅇ","efDot":"≒","Efr":"𝔈","efr":"𝔢","eg":"⪚","Egrave":"È","egrave":"è","egs":"⪖","egsdot":"⪘","el":"⪙","Element":"∈","elinters":"⏧","ell":"ℓ","els":"⪕","elsdot":"⪗","Emacr":"Ē","emacr":"ē","empty":"∅","emptyset":"∅","EmptySmallSquare":"◻","emptyv":"∅","EmptyVerySmallSquare":"▫","emsp13":" ","emsp14":" ","emsp":" ","ENG":"Ŋ","eng":"ŋ","ensp":" ","Eogon":"Ę","eogon":"ę","Eopf":"𝔼","eopf":"𝕖","epar":"⋕","eparsl":"⧣","eplus":"⩱","epsi":"ε","Epsilon":"Ε","epsilon":"ε","epsiv":"ϵ","eqcirc":"≖","eqcolon":"≕","eqsim":"≂","eqslantgtr":"⪖","eqslantless":"⪕","Equal":"⩵","equals":"=","EqualTilde":"≂","equest":"≟","Equilibrium":"⇌","equiv":"≡","equivDD":"⩸","eqvparsl":"⧥","erarr":"⥱","erDot":"≓","escr":"ℯ","Escr":"ℰ","esdot":"≐","Esim":"⩳","esim":"≂","Eta":"Η","eta":"η","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","euro":"€","excl":"!","exist":"∃","Exists":"∃","expectation":"ℰ","exponentiale":"ⅇ","ExponentialE":"ⅇ","fallingdotseq":"≒","Fcy":"Ф","fcy":"ф","female":"♀","ffilig":"ffi","fflig":"ff","ffllig":"ffl","Ffr":"𝔉","ffr":"𝔣","filig":"fi","FilledSmallSquare":"◼","FilledVerySmallSquare":"▪","fjlig":"fj","flat":"♭","fllig":"fl","fltns":"▱","fnof":"ƒ","Fopf":"𝔽","fopf":"𝕗","forall":"∀","ForAll":"∀","fork":"⋔","forkv":"⫙","Fouriertrf":"ℱ","fpartint":"⨍","frac12":"½","frac13":"⅓","frac14":"¼","frac15":"⅕","frac16":"⅙","frac18":"⅛","frac23":"⅔","frac25":"⅖","frac34":"¾","frac35":"⅗","frac38":"⅜","frac45":"⅘","frac56":"⅚","frac58":"⅝","frac78":"⅞","frasl":"⁄","frown":"⌢","fscr":"𝒻","Fscr":"ℱ","gacute":"ǵ","Gamma":"Γ","gamma":"γ","Gammad":"Ϝ","gammad":"ϝ","gap":"⪆","Gbreve":"Ğ","gbreve":"ğ","Gcedil":"Ģ","Gcirc":"Ĝ","gcirc":"ĝ","Gcy":"Г","gcy":"г","Gdot":"Ġ","gdot":"ġ","ge":"≥","gE":"≧","gEl":"⪌","gel":"⋛","geq":"≥","geqq":"≧","geqslant":"⩾","gescc":"⪩","ges":"⩾","gesdot":"⪀","gesdoto":"⪂","gesdotol":"⪄","gesl":"⋛︀","gesles":"⪔","Gfr":"𝔊","gfr":"𝔤","gg":"≫","Gg":"⋙","ggg":"⋙","gimel":"ℷ","GJcy":"Ѓ","gjcy":"ѓ","gla":"⪥","gl":"≷","glE":"⪒","glj":"⪤","gnap":"⪊","gnapprox":"⪊","gne":"⪈","gnE":"≩","gneq":"⪈","gneqq":"≩","gnsim":"⋧","Gopf":"𝔾","gopf":"𝕘","grave":"`","GreaterEqual":"≥","GreaterEqualLess":"⋛","GreaterFullEqual":"≧","GreaterGreater":"⪢","GreaterLess":"≷","GreaterSlantEqual":"⩾","GreaterTilde":"≳","Gscr":"𝒢","gscr":"ℊ","gsim":"≳","gsime":"⪎","gsiml":"⪐","gtcc":"⪧","gtcir":"⩺","gt":">","GT":">","Gt":"≫","gtdot":"⋗","gtlPar":"⦕","gtquest":"⩼","gtrapprox":"⪆","gtrarr":"⥸","gtrdot":"⋗","gtreqless":"⋛","gtreqqless":"⪌","gtrless":"≷","gtrsim":"≳","gvertneqq":"≩︀","gvnE":"≩︀","Hacek":"ˇ","hairsp":" ","half":"½","hamilt":"ℋ","HARDcy":"Ъ","hardcy":"ъ","harrcir":"⥈","harr":"↔","hArr":"⇔","harrw":"↭","Hat":"^","hbar":"ℏ","Hcirc":"Ĥ","hcirc":"ĥ","hearts":"♥","heartsuit":"♥","hellip":"…","hercon":"⊹","hfr":"𝔥","Hfr":"ℌ","HilbertSpace":"ℋ","hksearow":"⤥","hkswarow":"⤦","hoarr":"⇿","homtht":"∻","hookleftarrow":"↩","hookrightarrow":"↪","hopf":"𝕙","Hopf":"ℍ","horbar":"―","HorizontalLine":"─","hscr":"𝒽","Hscr":"ℋ","hslash":"ℏ","Hstrok":"Ħ","hstrok":"ħ","HumpDownHump":"≎","HumpEqual":"≏","hybull":"⁃","hyphen":"‐","Iacute":"Í","iacute":"í","ic":"⁣","Icirc":"Î","icirc":"î","Icy":"И","icy":"и","Idot":"İ","IEcy":"Е","iecy":"е","iexcl":"¡","iff":"⇔","ifr":"𝔦","Ifr":"ℑ","Igrave":"Ì","igrave":"ì","ii":"ⅈ","iiiint":"⨌","iiint":"∭","iinfin":"⧜","iiota":"℩","IJlig":"IJ","ijlig":"ij","Imacr":"Ī","imacr":"ī","image":"ℑ","ImaginaryI":"ⅈ","imagline":"ℐ","imagpart":"ℑ","imath":"ı","Im":"ℑ","imof":"⊷","imped":"Ƶ","Implies":"⇒","incare":"℅","in":"∈","infin":"∞","infintie":"⧝","inodot":"ı","intcal":"⊺","int":"∫","Int":"∬","integers":"ℤ","Integral":"∫","intercal":"⊺","Intersection":"⋂","intlarhk":"⨗","intprod":"⨼","InvisibleComma":"⁣","InvisibleTimes":"⁢","IOcy":"Ё","iocy":"ё","Iogon":"Į","iogon":"į","Iopf":"𝕀","iopf":"𝕚","Iota":"Ι","iota":"ι","iprod":"⨼","iquest":"¿","iscr":"𝒾","Iscr":"ℐ","isin":"∈","isindot":"⋵","isinE":"⋹","isins":"⋴","isinsv":"⋳","isinv":"∈","it":"⁢","Itilde":"Ĩ","itilde":"ĩ","Iukcy":"І","iukcy":"і","Iuml":"Ï","iuml":"ï","Jcirc":"Ĵ","jcirc":"ĵ","Jcy":"Й","jcy":"й","Jfr":"𝔍","jfr":"𝔧","jmath":"ȷ","Jopf":"𝕁","jopf":"𝕛","Jscr":"𝒥","jscr":"𝒿","Jsercy":"Ј","jsercy":"ј","Jukcy":"Є","jukcy":"є","Kappa":"Κ","kappa":"κ","kappav":"ϰ","Kcedil":"Ķ","kcedil":"ķ","Kcy":"К","kcy":"к","Kfr":"𝔎","kfr":"𝔨","kgreen":"ĸ","KHcy":"Х","khcy":"х","KJcy":"Ќ","kjcy":"ќ","Kopf":"𝕂","kopf":"𝕜","Kscr":"𝒦","kscr":"𝓀","lAarr":"⇚","Lacute":"Ĺ","lacute":"ĺ","laemptyv":"⦴","lagran":"ℒ","Lambda":"Λ","lambda":"λ","lang":"⟨","Lang":"⟪","langd":"⦑","langle":"⟨","lap":"⪅","Laplacetrf":"ℒ","laquo":"«","larrb":"⇤","larrbfs":"⤟","larr":"←","Larr":"↞","lArr":"⇐","larrfs":"⤝","larrhk":"↩","larrlp":"↫","larrpl":"⤹","larrsim":"⥳","larrtl":"↢","latail":"⤙","lAtail":"⤛","lat":"⪫","late":"⪭","lates":"⪭︀","lbarr":"⤌","lBarr":"⤎","lbbrk":"❲","lbrace":"{","lbrack":"[","lbrke":"⦋","lbrksld":"⦏","lbrkslu":"⦍","Lcaron":"Ľ","lcaron":"ľ","Lcedil":"Ļ","lcedil":"ļ","lceil":"⌈","lcub":"{","Lcy":"Л","lcy":"л","ldca":"⤶","ldquo":"“","ldquor":"„","ldrdhar":"⥧","ldrushar":"⥋","ldsh":"↲","le":"≤","lE":"≦","LeftAngleBracket":"⟨","LeftArrowBar":"⇤","leftarrow":"←","LeftArrow":"←","Leftarrow":"⇐","LeftArrowRightArrow":"⇆","leftarrowtail":"↢","LeftCeiling":"⌈","LeftDoubleBracket":"⟦","LeftDownTeeVector":"⥡","LeftDownVectorBar":"⥙","LeftDownVector":"⇃","LeftFloor":"⌊","leftharpoondown":"↽","leftharpoonup":"↼","leftleftarrows":"⇇","leftrightarrow":"↔","LeftRightArrow":"↔","Leftrightarrow":"⇔","leftrightarrows":"⇆","leftrightharpoons":"⇋","leftrightsquigarrow":"↭","LeftRightVector":"⥎","LeftTeeArrow":"↤","LeftTee":"⊣","LeftTeeVector":"⥚","leftthreetimes":"⋋","LeftTriangleBar":"⧏","LeftTriangle":"⊲","LeftTriangleEqual":"⊴","LeftUpDownVector":"⥑","LeftUpTeeVector":"⥠","LeftUpVectorBar":"⥘","LeftUpVector":"↿","LeftVectorBar":"⥒","LeftVector":"↼","lEg":"⪋","leg":"⋚","leq":"≤","leqq":"≦","leqslant":"⩽","lescc":"⪨","les":"⩽","lesdot":"⩿","lesdoto":"⪁","lesdotor":"⪃","lesg":"⋚︀","lesges":"⪓","lessapprox":"⪅","lessdot":"⋖","lesseqgtr":"⋚","lesseqqgtr":"⪋","LessEqualGreater":"⋚","LessFullEqual":"≦","LessGreater":"≶","lessgtr":"≶","LessLess":"⪡","lesssim":"≲","LessSlantEqual":"⩽","LessTilde":"≲","lfisht":"⥼","lfloor":"⌊","Lfr":"𝔏","lfr":"𝔩","lg":"≶","lgE":"⪑","lHar":"⥢","lhard":"↽","lharu":"↼","lharul":"⥪","lhblk":"▄","LJcy":"Љ","ljcy":"љ","llarr":"⇇","ll":"≪","Ll":"⋘","llcorner":"⌞","Lleftarrow":"⇚","llhard":"⥫","lltri":"◺","Lmidot":"Ŀ","lmidot":"ŀ","lmoustache":"⎰","lmoust":"⎰","lnap":"⪉","lnapprox":"⪉","lne":"⪇","lnE":"≨","lneq":"⪇","lneqq":"≨","lnsim":"⋦","loang":"⟬","loarr":"⇽","lobrk":"⟦","longleftarrow":"⟵","LongLeftArrow":"⟵","Longleftarrow":"⟸","longleftrightarrow":"⟷","LongLeftRightArrow":"⟷","Longleftrightarrow":"⟺","longmapsto":"⟼","longrightarrow":"⟶","LongRightArrow":"⟶","Longrightarrow":"⟹","looparrowleft":"↫","looparrowright":"↬","lopar":"⦅","Lopf":"𝕃","lopf":"𝕝","loplus":"⨭","lotimes":"⨴","lowast":"∗","lowbar":"_","LowerLeftArrow":"↙","LowerRightArrow":"↘","loz":"◊","lozenge":"◊","lozf":"⧫","lpar":"(","lparlt":"⦓","lrarr":"⇆","lrcorner":"⌟","lrhar":"⇋","lrhard":"⥭","lrm":"‎","lrtri":"⊿","lsaquo":"‹","lscr":"𝓁","Lscr":"ℒ","lsh":"↰","Lsh":"↰","lsim":"≲","lsime":"⪍","lsimg":"⪏","lsqb":"[","lsquo":"‘","lsquor":"‚","Lstrok":"Ł","lstrok":"ł","ltcc":"⪦","ltcir":"⩹","lt":"<","LT":"<","Lt":"≪","ltdot":"⋖","lthree":"⋋","ltimes":"⋉","ltlarr":"⥶","ltquest":"⩻","ltri":"◃","ltrie":"⊴","ltrif":"◂","ltrPar":"⦖","lurdshar":"⥊","luruhar":"⥦","lvertneqq":"≨︀","lvnE":"≨︀","macr":"¯","male":"♂","malt":"✠","maltese":"✠","Map":"⤅","map":"↦","mapsto":"↦","mapstodown":"↧","mapstoleft":"↤","mapstoup":"↥","marker":"▮","mcomma":"⨩","Mcy":"М","mcy":"м","mdash":"—","mDDot":"∺","measuredangle":"∡","MediumSpace":" ","Mellintrf":"ℳ","Mfr":"𝔐","mfr":"𝔪","mho":"℧","micro":"µ","midast":"*","midcir":"⫰","mid":"∣","middot":"·","minusb":"⊟","minus":"−","minusd":"∸","minusdu":"⨪","MinusPlus":"∓","mlcp":"⫛","mldr":"…","mnplus":"∓","models":"⊧","Mopf":"𝕄","mopf":"𝕞","mp":"∓","mscr":"𝓂","Mscr":"ℳ","mstpos":"∾","Mu":"Μ","mu":"μ","multimap":"⊸","mumap":"⊸","nabla":"∇","Nacute":"Ń","nacute":"ń","nang":"∠⃒","nap":"≉","napE":"⩰̸","napid":"≋̸","napos":"ʼn","napprox":"≉","natural":"♮","naturals":"ℕ","natur":"♮","nbsp":" ","nbump":"≎̸","nbumpe":"≏̸","ncap":"⩃","Ncaron":"Ň","ncaron":"ň","Ncedil":"Ņ","ncedil":"ņ","ncong":"≇","ncongdot":"⩭̸","ncup":"⩂","Ncy":"Н","ncy":"н","ndash":"–","nearhk":"⤤","nearr":"↗","neArr":"⇗","nearrow":"↗","ne":"≠","nedot":"≐̸","NegativeMediumSpace":"​","NegativeThickSpace":"​","NegativeThinSpace":"​","NegativeVeryThinSpace":"​","nequiv":"≢","nesear":"⤨","nesim":"≂̸","NestedGreaterGreater":"≫","NestedLessLess":"≪","NewLine":"\n","nexist":"∄","nexists":"∄","Nfr":"𝔑","nfr":"𝔫","ngE":"≧̸","nge":"≱","ngeq":"≱","ngeqq":"≧̸","ngeqslant":"⩾̸","nges":"⩾̸","nGg":"⋙̸","ngsim":"≵","nGt":"≫⃒","ngt":"≯","ngtr":"≯","nGtv":"≫̸","nharr":"↮","nhArr":"⇎","nhpar":"⫲","ni":"∋","nis":"⋼","nisd":"⋺","niv":"∋","NJcy":"Њ","njcy":"њ","nlarr":"↚","nlArr":"⇍","nldr":"‥","nlE":"≦̸","nle":"≰","nleftarrow":"↚","nLeftarrow":"⇍","nleftrightarrow":"↮","nLeftrightarrow":"⇎","nleq":"≰","nleqq":"≦̸","nleqslant":"⩽̸","nles":"⩽̸","nless":"≮","nLl":"⋘̸","nlsim":"≴","nLt":"≪⃒","nlt":"≮","nltri":"⋪","nltrie":"⋬","nLtv":"≪̸","nmid":"∤","NoBreak":"⁠","NonBreakingSpace":" ","nopf":"𝕟","Nopf":"ℕ","Not":"⫬","not":"¬","NotCongruent":"≢","NotCupCap":"≭","NotDoubleVerticalBar":"∦","NotElement":"∉","NotEqual":"≠","NotEqualTilde":"≂̸","NotExists":"∄","NotGreater":"≯","NotGreaterEqual":"≱","NotGreaterFullEqual":"≧̸","NotGreaterGreater":"≫̸","NotGreaterLess":"≹","NotGreaterSlantEqual":"⩾̸","NotGreaterTilde":"≵","NotHumpDownHump":"≎̸","NotHumpEqual":"≏̸","notin":"∉","notindot":"⋵̸","notinE":"⋹̸","notinva":"∉","notinvb":"⋷","notinvc":"⋶","NotLeftTriangleBar":"⧏̸","NotLeftTriangle":"⋪","NotLeftTriangleEqual":"⋬","NotLess":"≮","NotLessEqual":"≰","NotLessGreater":"≸","NotLessLess":"≪̸","NotLessSlantEqual":"⩽̸","NotLessTilde":"≴","NotNestedGreaterGreater":"⪢̸","NotNestedLessLess":"⪡̸","notni":"∌","notniva":"∌","notnivb":"⋾","notnivc":"⋽","NotPrecedes":"⊀","NotPrecedesEqual":"⪯̸","NotPrecedesSlantEqual":"⋠","NotReverseElement":"∌","NotRightTriangleBar":"⧐̸","NotRightTriangle":"⋫","NotRightTriangleEqual":"⋭","NotSquareSubset":"⊏̸","NotSquareSubsetEqual":"⋢","NotSquareSuperset":"⊐̸","NotSquareSupersetEqual":"⋣","NotSubset":"⊂⃒","NotSubsetEqual":"⊈","NotSucceeds":"⊁","NotSucceedsEqual":"⪰̸","NotSucceedsSlantEqual":"⋡","NotSucceedsTilde":"≿̸","NotSuperset":"⊃⃒","NotSupersetEqual":"⊉","NotTilde":"≁","NotTildeEqual":"≄","NotTildeFullEqual":"≇","NotTildeTilde":"≉","NotVerticalBar":"∤","nparallel":"∦","npar":"∦","nparsl":"⫽⃥","npart":"∂̸","npolint":"⨔","npr":"⊀","nprcue":"⋠","nprec":"⊀","npreceq":"⪯̸","npre":"⪯̸","nrarrc":"⤳̸","nrarr":"↛","nrArr":"⇏","nrarrw":"↝̸","nrightarrow":"↛","nRightarrow":"⇏","nrtri":"⋫","nrtrie":"⋭","nsc":"⊁","nsccue":"⋡","nsce":"⪰̸","Nscr":"𝒩","nscr":"𝓃","nshortmid":"∤","nshortparallel":"∦","nsim":"≁","nsime":"≄","nsimeq":"≄","nsmid":"∤","nspar":"∦","nsqsube":"⋢","nsqsupe":"⋣","nsub":"⊄","nsubE":"⫅̸","nsube":"⊈","nsubset":"⊂⃒","nsubseteq":"⊈","nsubseteqq":"⫅̸","nsucc":"⊁","nsucceq":"⪰̸","nsup":"⊅","nsupE":"⫆̸","nsupe":"⊉","nsupset":"⊃⃒","nsupseteq":"⊉","nsupseteqq":"⫆̸","ntgl":"≹","Ntilde":"Ñ","ntilde":"ñ","ntlg":"≸","ntriangleleft":"⋪","ntrianglelefteq":"⋬","ntriangleright":"⋫","ntrianglerighteq":"⋭","Nu":"Ν","nu":"ν","num":"#","numero":"№","numsp":" ","nvap":"≍⃒","nvdash":"⊬","nvDash":"⊭","nVdash":"⊮","nVDash":"⊯","nvge":"≥⃒","nvgt":">⃒","nvHarr":"⤄","nvinfin":"⧞","nvlArr":"⤂","nvle":"≤⃒","nvlt":"<⃒","nvltrie":"⊴⃒","nvrArr":"⤃","nvrtrie":"⊵⃒","nvsim":"∼⃒","nwarhk":"⤣","nwarr":"↖","nwArr":"⇖","nwarrow":"↖","nwnear":"⤧","Oacute":"Ó","oacute":"ó","oast":"⊛","Ocirc":"Ô","ocirc":"ô","ocir":"⊚","Ocy":"О","ocy":"о","odash":"⊝","Odblac":"Ő","odblac":"ő","odiv":"⨸","odot":"⊙","odsold":"⦼","OElig":"Œ","oelig":"œ","ofcir":"⦿","Ofr":"𝔒","ofr":"𝔬","ogon":"˛","Ograve":"Ò","ograve":"ò","ogt":"⧁","ohbar":"⦵","ohm":"Ω","oint":"∮","olarr":"↺","olcir":"⦾","olcross":"⦻","oline":"‾","olt":"⧀","Omacr":"Ō","omacr":"ō","Omega":"Ω","omega":"ω","Omicron":"Ο","omicron":"ο","omid":"⦶","ominus":"⊖","Oopf":"𝕆","oopf":"𝕠","opar":"⦷","OpenCurlyDoubleQuote":"“","OpenCurlyQuote":"‘","operp":"⦹","oplus":"⊕","orarr":"↻","Or":"⩔","or":"∨","ord":"⩝","order":"ℴ","orderof":"ℴ","ordf":"ª","ordm":"º","origof":"⊶","oror":"⩖","orslope":"⩗","orv":"⩛","oS":"Ⓢ","Oscr":"𝒪","oscr":"ℴ","Oslash":"Ø","oslash":"ø","osol":"⊘","Otilde":"Õ","otilde":"õ","otimesas":"⨶","Otimes":"⨷","otimes":"⊗","Ouml":"Ö","ouml":"ö","ovbar":"⌽","OverBar":"‾","OverBrace":"⏞","OverBracket":"⎴","OverParenthesis":"⏜","para":"¶","parallel":"∥","par":"∥","parsim":"⫳","parsl":"⫽","part":"∂","PartialD":"∂","Pcy":"П","pcy":"п","percnt":"%","period":".","permil":"‰","perp":"⊥","pertenk":"‱","Pfr":"𝔓","pfr":"𝔭","Phi":"Φ","phi":"φ","phiv":"ϕ","phmmat":"ℳ","phone":"☎","Pi":"Π","pi":"π","pitchfork":"⋔","piv":"ϖ","planck":"ℏ","planckh":"ℎ","plankv":"ℏ","plusacir":"⨣","plusb":"⊞","pluscir":"⨢","plus":"+","plusdo":"∔","plusdu":"⨥","pluse":"⩲","PlusMinus":"±","plusmn":"±","plussim":"⨦","plustwo":"⨧","pm":"±","Poincareplane":"ℌ","pointint":"⨕","popf":"𝕡","Popf":"ℙ","pound":"£","prap":"⪷","Pr":"⪻","pr":"≺","prcue":"≼","precapprox":"⪷","prec":"≺","preccurlyeq":"≼","Precedes":"≺","PrecedesEqual":"⪯","PrecedesSlantEqual":"≼","PrecedesTilde":"≾","preceq":"⪯","precnapprox":"⪹","precneqq":"⪵","precnsim":"⋨","pre":"⪯","prE":"⪳","precsim":"≾","prime":"′","Prime":"″","primes":"ℙ","prnap":"⪹","prnE":"⪵","prnsim":"⋨","prod":"∏","Product":"∏","profalar":"⌮","profline":"⌒","profsurf":"⌓","prop":"∝","Proportional":"∝","Proportion":"∷","propto":"∝","prsim":"≾","prurel":"⊰","Pscr":"𝒫","pscr":"𝓅","Psi":"Ψ","psi":"ψ","puncsp":" ","Qfr":"𝔔","qfr":"𝔮","qint":"⨌","qopf":"𝕢","Qopf":"ℚ","qprime":"⁗","Qscr":"𝒬","qscr":"𝓆","quaternions":"ℍ","quatint":"⨖","quest":"?","questeq":"≟","quot":"\"","QUOT":"\"","rAarr":"⇛","race":"∽̱","Racute":"Ŕ","racute":"ŕ","radic":"√","raemptyv":"⦳","rang":"⟩","Rang":"⟫","rangd":"⦒","range":"⦥","rangle":"⟩","raquo":"»","rarrap":"⥵","rarrb":"⇥","rarrbfs":"⤠","rarrc":"⤳","rarr":"→","Rarr":"↠","rArr":"⇒","rarrfs":"⤞","rarrhk":"↪","rarrlp":"↬","rarrpl":"⥅","rarrsim":"⥴","Rarrtl":"⤖","rarrtl":"↣","rarrw":"↝","ratail":"⤚","rAtail":"⤜","ratio":"∶","rationals":"ℚ","rbarr":"⤍","rBarr":"⤏","RBarr":"⤐","rbbrk":"❳","rbrace":"}","rbrack":"]","rbrke":"⦌","rbrksld":"⦎","rbrkslu":"⦐","Rcaron":"Ř","rcaron":"ř","Rcedil":"Ŗ","rcedil":"ŗ","rceil":"⌉","rcub":"}","Rcy":"Р","rcy":"р","rdca":"⤷","rdldhar":"⥩","rdquo":"”","rdquor":"”","rdsh":"↳","real":"ℜ","realine":"ℛ","realpart":"ℜ","reals":"ℝ","Re":"ℜ","rect":"▭","reg":"®","REG":"®","ReverseElement":"∋","ReverseEquilibrium":"⇋","ReverseUpEquilibrium":"⥯","rfisht":"⥽","rfloor":"⌋","rfr":"𝔯","Rfr":"ℜ","rHar":"⥤","rhard":"⇁","rharu":"⇀","rharul":"⥬","Rho":"Ρ","rho":"ρ","rhov":"ϱ","RightAngleBracket":"⟩","RightArrowBar":"⇥","rightarrow":"→","RightArrow":"→","Rightarrow":"⇒","RightArrowLeftArrow":"⇄","rightarrowtail":"↣","RightCeiling":"⌉","RightDoubleBracket":"⟧","RightDownTeeVector":"⥝","RightDownVectorBar":"⥕","RightDownVector":"⇂","RightFloor":"⌋","rightharpoondown":"⇁","rightharpoonup":"⇀","rightleftarrows":"⇄","rightleftharpoons":"⇌","rightrightarrows":"⇉","rightsquigarrow":"↝","RightTeeArrow":"↦","RightTee":"⊢","RightTeeVector":"⥛","rightthreetimes":"⋌","RightTriangleBar":"⧐","RightTriangle":"⊳","RightTriangleEqual":"⊵","RightUpDownVector":"⥏","RightUpTeeVector":"⥜","RightUpVectorBar":"⥔","RightUpVector":"↾","RightVectorBar":"⥓","RightVector":"⇀","ring":"˚","risingdotseq":"≓","rlarr":"⇄","rlhar":"⇌","rlm":"‏","rmoustache":"⎱","rmoust":"⎱","rnmid":"⫮","roang":"⟭","roarr":"⇾","robrk":"⟧","ropar":"⦆","ropf":"𝕣","Ropf":"ℝ","roplus":"⨮","rotimes":"⨵","RoundImplies":"⥰","rpar":")","rpargt":"⦔","rppolint":"⨒","rrarr":"⇉","Rrightarrow":"⇛","rsaquo":"›","rscr":"𝓇","Rscr":"ℛ","rsh":"↱","Rsh":"↱","rsqb":"]","rsquo":"’","rsquor":"’","rthree":"⋌","rtimes":"⋊","rtri":"▹","rtrie":"⊵","rtrif":"▸","rtriltri":"⧎","RuleDelayed":"⧴","ruluhar":"⥨","rx":"℞","Sacute":"Ś","sacute":"ś","sbquo":"‚","scap":"⪸","Scaron":"Š","scaron":"š","Sc":"⪼","sc":"≻","sccue":"≽","sce":"⪰","scE":"⪴","Scedil":"Ş","scedil":"ş","Scirc":"Ŝ","scirc":"ŝ","scnap":"⪺","scnE":"⪶","scnsim":"⋩","scpolint":"⨓","scsim":"≿","Scy":"С","scy":"с","sdotb":"⊡","sdot":"⋅","sdote":"⩦","searhk":"⤥","searr":"↘","seArr":"⇘","searrow":"↘","sect":"§","semi":";","seswar":"⤩","setminus":"∖","setmn":"∖","sext":"✶","Sfr":"𝔖","sfr":"𝔰","sfrown":"⌢","sharp":"♯","SHCHcy":"Щ","shchcy":"щ","SHcy":"Ш","shcy":"ш","ShortDownArrow":"↓","ShortLeftArrow":"←","shortmid":"∣","shortparallel":"∥","ShortRightArrow":"→","ShortUpArrow":"↑","shy":"­","Sigma":"Σ","sigma":"σ","sigmaf":"ς","sigmav":"ς","sim":"∼","simdot":"⩪","sime":"≃","simeq":"≃","simg":"⪞","simgE":"⪠","siml":"⪝","simlE":"⪟","simne":"≆","simplus":"⨤","simrarr":"⥲","slarr":"←","SmallCircle":"∘","smallsetminus":"∖","smashp":"⨳","smeparsl":"⧤","smid":"∣","smile":"⌣","smt":"⪪","smte":"⪬","smtes":"⪬︀","SOFTcy":"Ь","softcy":"ь","solbar":"⌿","solb":"⧄","sol":"/","Sopf":"𝕊","sopf":"𝕤","spades":"♠","spadesuit":"♠","spar":"∥","sqcap":"⊓","sqcaps":"⊓︀","sqcup":"⊔","sqcups":"⊔︀","Sqrt":"√","sqsub":"⊏","sqsube":"⊑","sqsubset":"⊏","sqsubseteq":"⊑","sqsup":"⊐","sqsupe":"⊒","sqsupset":"⊐","sqsupseteq":"⊒","square":"□","Square":"□","SquareIntersection":"⊓","SquareSubset":"⊏","SquareSubsetEqual":"⊑","SquareSuperset":"⊐","SquareSupersetEqual":"⊒","SquareUnion":"⊔","squarf":"▪","squ":"□","squf":"▪","srarr":"→","Sscr":"𝒮","sscr":"𝓈","ssetmn":"∖","ssmile":"⌣","sstarf":"⋆","Star":"⋆","star":"☆","starf":"★","straightepsilon":"ϵ","straightphi":"ϕ","strns":"¯","sub":"⊂","Sub":"⋐","subdot":"⪽","subE":"⫅","sube":"⊆","subedot":"⫃","submult":"⫁","subnE":"⫋","subne":"⊊","subplus":"⪿","subrarr":"⥹","subset":"⊂","Subset":"⋐","subseteq":"⊆","subseteqq":"⫅","SubsetEqual":"⊆","subsetneq":"⊊","subsetneqq":"⫋","subsim":"⫇","subsub":"⫕","subsup":"⫓","succapprox":"⪸","succ":"≻","succcurlyeq":"≽","Succeeds":"≻","SucceedsEqual":"⪰","SucceedsSlantEqual":"≽","SucceedsTilde":"≿","succeq":"⪰","succnapprox":"⪺","succneqq":"⪶","succnsim":"⋩","succsim":"≿","SuchThat":"∋","sum":"∑","Sum":"∑","sung":"♪","sup1":"¹","sup2":"²","sup3":"³","sup":"⊃","Sup":"⋑","supdot":"⪾","supdsub":"⫘","supE":"⫆","supe":"⊇","supedot":"⫄","Superset":"⊃","SupersetEqual":"⊇","suphsol":"⟉","suphsub":"⫗","suplarr":"⥻","supmult":"⫂","supnE":"⫌","supne":"⊋","supplus":"⫀","supset":"⊃","Supset":"⋑","supseteq":"⊇","supseteqq":"⫆","supsetneq":"⊋","supsetneqq":"⫌","supsim":"⫈","supsub":"⫔","supsup":"⫖","swarhk":"⤦","swarr":"↙","swArr":"⇙","swarrow":"↙","swnwar":"⤪","szlig":"ß","Tab":"\t","target":"⌖","Tau":"Τ","tau":"τ","tbrk":"⎴","Tcaron":"Ť","tcaron":"ť","Tcedil":"Ţ","tcedil":"ţ","Tcy":"Т","tcy":"т","tdot":"⃛","telrec":"⌕","Tfr":"𝔗","tfr":"𝔱","there4":"∴","therefore":"∴","Therefore":"∴","Theta":"Θ","theta":"θ","thetasym":"ϑ","thetav":"ϑ","thickapprox":"≈","thicksim":"∼","ThickSpace":"  ","ThinSpace":" ","thinsp":" ","thkap":"≈","thksim":"∼","THORN":"Þ","thorn":"þ","tilde":"˜","Tilde":"∼","TildeEqual":"≃","TildeFullEqual":"≅","TildeTilde":"≈","timesbar":"⨱","timesb":"⊠","times":"×","timesd":"⨰","tint":"∭","toea":"⤨","topbot":"⌶","topcir":"⫱","top":"⊤","Topf":"𝕋","topf":"𝕥","topfork":"⫚","tosa":"⤩","tprime":"‴","trade":"™","TRADE":"™","triangle":"▵","triangledown":"▿","triangleleft":"◃","trianglelefteq":"⊴","triangleq":"≜","triangleright":"▹","trianglerighteq":"⊵","tridot":"◬","trie":"≜","triminus":"⨺","TripleDot":"⃛","triplus":"⨹","trisb":"⧍","tritime":"⨻","trpezium":"⏢","Tscr":"𝒯","tscr":"𝓉","TScy":"Ц","tscy":"ц","TSHcy":"Ћ","tshcy":"ћ","Tstrok":"Ŧ","tstrok":"ŧ","twixt":"≬","twoheadleftarrow":"↞","twoheadrightarrow":"↠","Uacute":"Ú","uacute":"ú","uarr":"↑","Uarr":"↟","uArr":"⇑","Uarrocir":"⥉","Ubrcy":"Ў","ubrcy":"ў","Ubreve":"Ŭ","ubreve":"ŭ","Ucirc":"Û","ucirc":"û","Ucy":"У","ucy":"у","udarr":"⇅","Udblac":"Ű","udblac":"ű","udhar":"⥮","ufisht":"⥾","Ufr":"𝔘","ufr":"𝔲","Ugrave":"Ù","ugrave":"ù","uHar":"⥣","uharl":"↿","uharr":"↾","uhblk":"▀","ulcorn":"⌜","ulcorner":"⌜","ulcrop":"⌏","ultri":"◸","Umacr":"Ū","umacr":"ū","uml":"¨","UnderBar":"_","UnderBrace":"⏟","UnderBracket":"⎵","UnderParenthesis":"⏝","Union":"⋃","UnionPlus":"⊎","Uogon":"Ų","uogon":"ų","Uopf":"𝕌","uopf":"𝕦","UpArrowBar":"⤒","uparrow":"↑","UpArrow":"↑","Uparrow":"⇑","UpArrowDownArrow":"⇅","updownarrow":"↕","UpDownArrow":"↕","Updownarrow":"⇕","UpEquilibrium":"⥮","upharpoonleft":"↿","upharpoonright":"↾","uplus":"⊎","UpperLeftArrow":"↖","UpperRightArrow":"↗","upsi":"υ","Upsi":"ϒ","upsih":"ϒ","Upsilon":"Υ","upsilon":"υ","UpTeeArrow":"↥","UpTee":"⊥","upuparrows":"⇈","urcorn":"⌝","urcorner":"⌝","urcrop":"⌎","Uring":"Ů","uring":"ů","urtri":"◹","Uscr":"𝒰","uscr":"𝓊","utdot":"⋰","Utilde":"Ũ","utilde":"ũ","utri":"▵","utrif":"▴","uuarr":"⇈","Uuml":"Ü","uuml":"ü","uwangle":"⦧","vangrt":"⦜","varepsilon":"ϵ","varkappa":"ϰ","varnothing":"∅","varphi":"ϕ","varpi":"ϖ","varpropto":"∝","varr":"↕","vArr":"⇕","varrho":"ϱ","varsigma":"ς","varsubsetneq":"⊊︀","varsubsetneqq":"⫋︀","varsupsetneq":"⊋︀","varsupsetneqq":"⫌︀","vartheta":"ϑ","vartriangleleft":"⊲","vartriangleright":"⊳","vBar":"⫨","Vbar":"⫫","vBarv":"⫩","Vcy":"В","vcy":"в","vdash":"⊢","vDash":"⊨","Vdash":"⊩","VDash":"⊫","Vdashl":"⫦","veebar":"⊻","vee":"∨","Vee":"⋁","veeeq":"≚","vellip":"⋮","verbar":"|","Verbar":"‖","vert":"|","Vert":"‖","VerticalBar":"∣","VerticalLine":"|","VerticalSeparator":"❘","VerticalTilde":"≀","VeryThinSpace":" ","Vfr":"𝔙","vfr":"𝔳","vltri":"⊲","vnsub":"⊂⃒","vnsup":"⊃⃒","Vopf":"𝕍","vopf":"𝕧","vprop":"∝","vrtri":"⊳","Vscr":"𝒱","vscr":"𝓋","vsubnE":"⫋︀","vsubne":"⊊︀","vsupnE":"⫌︀","vsupne":"⊋︀","Vvdash":"⊪","vzigzag":"⦚","Wcirc":"Ŵ","wcirc":"ŵ","wedbar":"⩟","wedge":"∧","Wedge":"⋀","wedgeq":"≙","weierp":"℘","Wfr":"𝔚","wfr":"𝔴","Wopf":"𝕎","wopf":"𝕨","wp":"℘","wr":"≀","wreath":"≀","Wscr":"𝒲","wscr":"𝓌","xcap":"⋂","xcirc":"◯","xcup":"⋃","xdtri":"▽","Xfr":"𝔛","xfr":"𝔵","xharr":"⟷","xhArr":"⟺","Xi":"Ξ","xi":"ξ","xlarr":"⟵","xlArr":"⟸","xmap":"⟼","xnis":"⋻","xodot":"⨀","Xopf":"𝕏","xopf":"𝕩","xoplus":"⨁","xotime":"⨂","xrarr":"⟶","xrArr":"⟹","Xscr":"𝒳","xscr":"𝓍","xsqcup":"⨆","xuplus":"⨄","xutri":"△","xvee":"⋁","xwedge":"⋀","Yacute":"Ý","yacute":"ý","YAcy":"Я","yacy":"я","Ycirc":"Ŷ","ycirc":"ŷ","Ycy":"Ы","ycy":"ы","yen":"¥","Yfr":"𝔜","yfr":"𝔶","YIcy":"Ї","yicy":"ї","Yopf":"𝕐","yopf":"𝕪","Yscr":"𝒴","yscr":"𝓎","YUcy":"Ю","yucy":"ю","yuml":"ÿ","Yuml":"Ÿ","Zacute":"Ź","zacute":"ź","Zcaron":"Ž","zcaron":"ž","Zcy":"З","zcy":"з","Zdot":"Ż","zdot":"ż","zeetrf":"ℨ","ZeroWidthSpace":"​","Zeta":"Ζ","zeta":"ζ","zfr":"𝔷","Zfr":"ℨ","ZHcy":"Ж","zhcy":"ж","zigrarr":"⇝","zopf":"𝕫","Zopf":"ℤ","Zscr":"𝒵","zscr":"𝓏","zwj":"‍","zwnj":"‌"} diff --git a/node_modules/entities/lib/maps/legacy.json b/node_modules/entities/lib/maps/legacy.json deleted file mode 100644 index 43dbea6..0000000 --- a/node_modules/entities/lib/maps/legacy.json +++ /dev/null @@ -1 +0,0 @@ -{"Aacute":"Á","aacute":"á","Acirc":"Â","acirc":"â","acute":"´","AElig":"Æ","aelig":"æ","Agrave":"À","agrave":"à","amp":"&","AMP":"&","Aring":"Å","aring":"å","Atilde":"Ã","atilde":"ã","Auml":"Ä","auml":"ä","brvbar":"¦","Ccedil":"Ç","ccedil":"ç","cedil":"¸","cent":"¢","copy":"©","COPY":"©","curren":"¤","deg":"°","divide":"÷","Eacute":"É","eacute":"é","Ecirc":"Ê","ecirc":"ê","Egrave":"È","egrave":"è","ETH":"Ð","eth":"ð","Euml":"Ë","euml":"ë","frac12":"½","frac14":"¼","frac34":"¾","gt":">","GT":">","Iacute":"Í","iacute":"í","Icirc":"Î","icirc":"î","iexcl":"¡","Igrave":"Ì","igrave":"ì","iquest":"¿","Iuml":"Ï","iuml":"ï","laquo":"«","lt":"<","LT":"<","macr":"¯","micro":"µ","middot":"·","nbsp":" ","not":"¬","Ntilde":"Ñ","ntilde":"ñ","Oacute":"Ó","oacute":"ó","Ocirc":"Ô","ocirc":"ô","Ograve":"Ò","ograve":"ò","ordf":"ª","ordm":"º","Oslash":"Ø","oslash":"ø","Otilde":"Õ","otilde":"õ","Ouml":"Ö","ouml":"ö","para":"¶","plusmn":"±","pound":"£","quot":"\"","QUOT":"\"","raquo":"»","reg":"®","REG":"®","sect":"§","shy":"­","sup1":"¹","sup2":"²","sup3":"³","szlig":"ß","THORN":"Þ","thorn":"þ","times":"×","Uacute":"Ú","uacute":"ú","Ucirc":"Û","ucirc":"û","Ugrave":"Ù","ugrave":"ù","uml":"¨","Uuml":"Ü","uuml":"ü","Yacute":"Ý","yacute":"ý","yen":"¥","yuml":"ÿ"} diff --git a/node_modules/entities/lib/maps/xml.json b/node_modules/entities/lib/maps/xml.json deleted file mode 100644 index de8db10..0000000 --- a/node_modules/entities/lib/maps/xml.json +++ /dev/null @@ -1 +0,0 @@ -{"amp":"&","apos":"'","gt":">","lt":"<","quot":"\""} diff --git a/node_modules/entities/package.json b/node_modules/entities/package.json index cb9aedd..2e857f8 100644 --- a/node_modules/entities/package.json +++ b/node_modules/entities/package.json @@ -1,7 +1,7 @@ { "name": "entities", - "version": "2.2.0", - "description": "Encode & decode XML and HTML entities with ease", + "version": "4.5.0", + "description": "Encode & decode XML and HTML entities with ease & speed", "author": "Felix Boehm ", "funding": "https://github.com/fb55/entities?sponsor=1", "sideEffects": false, @@ -18,26 +18,44 @@ }, "main": "lib/index.js", "types": "lib/index.d.ts", + "module": "lib/esm/index.js", + "exports": { + ".": { + "require": "./lib/index.js", + "import": "./lib/esm/index.js" + }, + "./lib/decode.js": { + "require": "./lib/decode.js", + "import": "./lib/esm/decode.js" + }, + "./lib/escape.js": { + "require": "./lib/escape.js", + "import": "./lib/esm/escape.js" + } + }, "files": [ "lib/**/*" ], + "engines": { + "node": ">=0.12" + }, "devDependencies": { - "@types/jest": "^26.0.0", - "@types/node": "^14.11.8", - "@typescript-eslint/eslint-plugin": "^4.4.1", - "@typescript-eslint/parser": "^4.4.1", - "coveralls": "*", - "eslint": "^7.11.0", - "eslint-config-prettier": "^7.0.0", + "@types/jest": "^28.1.8", + "@types/node": "^18.15.11", + "@typescript-eslint/eslint-plugin": "^5.58.0", + "@typescript-eslint/parser": "^5.58.0", + "eslint": "^8.38.0", + "eslint-config-prettier": "^8.8.0", "eslint-plugin-node": "^11.1.0", - "jest": "^26.5.3", - "prettier": "^2.0.5", - "ts-jest": "^26.1.0", - "typescript": "^4.0.2" + "jest": "^28.1.3", + "prettier": "^2.8.7", + "ts-jest": "^28.0.8", + "typedoc": "^0.24.1", + "typescript": "^5.0.4" }, "scripts": { - "test": "jest --coverage && npm run lint", - "coverage": "cat coverage/lcov.info | coveralls", + "test": "npm run test:jest && npm run lint", + "test:jest": "jest", "lint": "npm run lint:es && npm run lint:prettier", "lint:es": "eslint .", "lint:prettier": "npm run prettier -- --check", @@ -45,7 +63,12 @@ "format:es": "npm run lint:es -- --fix", "format:prettier": "npm run prettier -- --write", "prettier": "prettier '**/*.{ts,md,json,yml}'", - "build": "tsc && cp -r src/maps lib", + "build": "npm run build:cjs && npm run build:esm", + "build:cjs": "tsc --sourceRoot https://raw.githubusercontent.com/fb55/entities/$(git rev-parse HEAD)/src/", + "build:esm": "npm run build:cjs -- --module esnext --target es2019 --outDir lib/esm && echo '{\"type\":\"module\"}' > lib/esm/package.json", + "build:docs": "typedoc --hideGenerator src/index.ts", + "build:trie": "ts-node scripts/write-decode-map.ts", + "build:encode-trie": "ts-node scripts/write-encode-map.ts", "prepare": "npm run build" }, "repository": { @@ -55,7 +78,10 @@ "license": "BSD-2-Clause", "jest": { "preset": "ts-jest", - "testEnvironment": "node" + "coverageProvider": "v8", + "moduleNameMapper": { + "^(.*)\\.js$": "$1" + } }, "prettier": { "tabWidth": 4, diff --git a/node_modules/entities/readme.md b/node_modules/entities/readme.md index f69264a..731d90c 100644 --- a/node_modules/entities/readme.md +++ b/node_modules/entities/readme.md @@ -1,7 +1,20 @@ -# entities [![NPM version](http://img.shields.io/npm/v/entities.svg)](https://npmjs.org/package/entities) [![Downloads](https://img.shields.io/npm/dm/entities.svg)](https://npmjs.org/package/entities) [![Build Status](http://img.shields.io/travis/fb55/entities.svg)](http://travis-ci.org/fb55/entities) [![Coverage](http://img.shields.io/coveralls/fb55/entities.svg)](https://coveralls.io/r/fb55/entities) +# entities [![NPM version](https://img.shields.io/npm/v/entities.svg)](https://npmjs.org/package/entities) [![Downloads](https://img.shields.io/npm/dm/entities.svg)](https://npmjs.org/package/entities) [![Node.js CI](https://github.com/fb55/entities/actions/workflows/nodejs-test.yml/badge.svg)](https://github.com/fb55/entities/actions/workflows/nodejs-test.yml) Encode & decode HTML & XML entities with ease & speed. +## Features + +- 😇 Tried and true: `entities` is used by many popular libraries; eg. + [`htmlparser2`](https://github.com/fb55/htmlparser2), the official + [AWS SDK](https://github.com/aws/aws-sdk-js-v3) and + [`commonmark`](https://github.com/commonmark/commonmark.js) use it to + process HTML entities. +- ⚡️ Fast: `entities` is the fastest library for decoding HTML entities (as + of April 2022); see [performance](#performance). +- 🎛 Configurable: Get an output tailored for your needs. You are fine with + UTF8? That'll save you some bytes. Prefer to only have ASCII characters? We + can do that as well! + ## How to… ### …install `entities` @@ -13,12 +26,12 @@ Encode & decode HTML & XML entities with ease & speed. ```javascript const entities = require("entities"); -//encoding -entities.escape("&"); // "&#38;" -entities.encodeXML("&"); // "&#38;" -entities.encodeHTML("&"); // "&#38;" +// Encoding +entities.escapeUTF8("& ü"); // "&#38; ü" +entities.encodeXML("& ü"); // "&#38; ü" +entities.encodeHTML("& ü"); // "&#38; ü" -//decoding +// Decoding entities.decodeXML("asdf & ÿ ü '"); // "asdf & ÿ ü '" entities.decodeHTML("asdf & ÿ ü '"); // "asdf & ÿ ü '" ``` @@ -26,14 +39,66 @@ entities.decodeHTML("asdf & ÿ ü '"); // "asdf & ÿ ü '" ## Performance This is how `entities` compares to other libraries on a very basic benchmark -(see `scripts/benchmark.ts`, for 10,000,000 iterations): - -| Library | `decode` performance | `encode` performance | Bundle size | -| -------------- | -------------------- | -------------------- | -------------------------------------------------------------------------- | -| entities | 10.809s | 17.683s | ![npm bundle size](https://img.shields.io/bundlephobia/min/entities) | -| html-entities | 14.029s | 22.670s | ![npm bundle size](https://img.shields.io/bundlephobia/min/html-entities) | -| he | 16.163s | 44.010s | ![npm bundle size](https://img.shields.io/bundlephobia/min/he) | -| parse-entities | 28.507s | N/A | ![npm bundle size](https://img.shields.io/bundlephobia/min/parse-entities) | +(see `scripts/benchmark.ts`, for 10,000,000 iterations; **lower is better**): + +| Library | Version | `decode` perf | `encode` perf | `escape` perf | +| -------------- | ------- | ------------- | ------------- | ------------- | +| entities | `3.0.1` | 1.418s | 6.786s | 2.196s | +| html-entities | `2.3.2` | 2.530s | 6.829s | 2.415s | +| he | `1.2.0` | 5.800s | 24.237s | 3.624s | +| parse-entities | `3.0.0` | 9.660s | N/A | N/A | + +--- + +## FAQ + +> What methods should I actually use to encode my documents? + +If your target supports UTF-8, the `escapeUTF8` method is going to be your best +choice. Otherwise, use either `encodeHTML` or `encodeXML` based on whether +you're dealing with an HTML or an XML document. + +You can have a look at the options for the `encode` and `decode` methods to see +everything you can configure. + +> When should I use strict decoding? + +When strict decoding, entities not terminated with a semicolon will be ignored. +This is helpful for decoding entities in legacy environments. + +> Why should I use `entities` instead of alternative modules? + +As of April 2022, `entities` is a bit faster than other modules. Still, this is +not a very differentiated space and other modules can catch up. + +**More importantly**, you might already have `entities` in your dependency graph +(as a dependency of eg. `cheerio`, or `htmlparser2`), and including it directly +might not even increase your bundle size. The same is true for other entity +libraries, so have a look through your `node_modules` directory! + +> Does `entities` support tree shaking? + +Yes! `entities` ships as both a CommonJS and a ES module. Note that for best +results, you should not use the `encode` and `decode` functions, as they wrap +around a number of other functions, all of which will remain in the bundle. +Instead, use the functions that you need directly. + +--- + +## Acknowledgements + +This library wouldn't be possible without the work of these individuals. Thanks +to + +- [@mathiasbynens](https://github.com/mathiasbynens) for his explanations + about character encodings, and his library `he`, which was one of the + inspirations for `entities` +- [@inikulin](https://github.com/inikulin) for his work on optimized tries for + decoding HTML entities for the `parse5` project +- [@mdevils](https://github.com/mdevils) for taking on the challenge of + producing a quick entity library with his `html-entities` library. + `entities` would be quite a bit slower if there wasn't any competition. + Right now `entities` is on top, but we'll see how long that lasts! --- diff --git a/node_modules/escalade/package.json b/node_modules/escalade/package.json index 0d1bfce..e0f5271 100644 --- a/node_modules/escalade/package.json +++ b/node_modules/escalade/package.json @@ -1,6 +1,6 @@ { "name": "escalade", - "version": "3.1.1", + "version": "3.1.2", "repository": "lukeed/escalade", "description": "A tiny (183B to 210B) and fast utility to ascend parent directories", "module": "dist/index.mjs", @@ -15,6 +15,7 @@ "exports": { ".": [ { + "types": "./index.d.ts", "import": "./dist/index.mjs", "require": "./dist/index.js" }, @@ -22,6 +23,7 @@ ], "./sync": [ { + "types": "./sync/index.d.ts", "import": "./sync/index.mjs", "require": "./sync/index.js" }, diff --git a/node_modules/escalade/readme.md b/node_modules/escalade/readme.md index 4e2195c..e07ee0d 100644 --- a/node_modules/escalade/readme.md +++ b/node_modules/escalade/readme.md @@ -1,4 +1,4 @@ -# escalade [![CI](https://github.com/lukeed/escalade/workflows/CI/badge.svg)](https://github.com/lukeed/escalade/actions) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/escalade)](https://codecov.io/gh/lukeed/escalade) +# escalade [![CI](https://github.com/lukeed/escalade/workflows/CI/badge.svg)](https://github.com/lukeed/escalade/actions) [![licenses](https://licenses.dev/b/npm/escalade)](https://licenses.dev/npm/escalade) [![codecov](https://badgen.now.sh/codecov/c/github/lukeed/escalade)](https://codecov.io/gh/lukeed/escalade) > A tiny (183B to 210B) and [fast](#benchmarks) utility to ascend parent directories diff --git a/node_modules/filelist/node_modules/minimatch/LICENSE b/node_modules/filelist/node_modules/minimatch/LICENSE index 9517b7d..1493534 100644 --- a/node_modules/filelist/node_modules/minimatch/LICENSE +++ b/node_modules/filelist/node_modules/minimatch/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) 2011-2022 Isaac Z. Schlueter and Contributors +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above diff --git a/node_modules/filelist/node_modules/minimatch/minimatch.js b/node_modules/filelist/node_modules/minimatch/minimatch.js index 71c96a1..6c8bfc3 100644 --- a/node_modules/filelist/node_modules/minimatch/minimatch.js +++ b/node_modules/filelist/node_modules/minimatch/minimatch.js @@ -157,7 +157,9 @@ minimatch.match = (list, pattern, options = {}) => { // replace stuff like \* with * const globUnescape = s => s.replace(/\\(.)/g, '$1') +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') class Minimatch { constructor (pattern, options) { @@ -243,7 +245,7 @@ class Minimatch { negateOffset++ } - if (negateOffset) this.pattern = pattern.substr(negateOffset) + if (negateOffset) this.pattern = pattern.slice(negateOffset) this.negate = negate } @@ -425,7 +427,7 @@ class Minimatch { if (pattern === '') return '' let re = '' - let hasMagic = !!options.nocase + let hasMagic = false let escaping = false // ? => one single character const patternListStack = [] @@ -438,11 +440,23 @@ class Minimatch { let pl let sp // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - const patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.' + let dotFileAllowed = options.dot || dotTravAllowed + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const clearStateChar = () => { if (stateChar) { @@ -492,6 +506,11 @@ class Minimatch { } case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c + continue + } + clearStateChar() escaping = true continue @@ -526,7 +545,7 @@ class Minimatch { if (options.noext) clearStateChar() continue - case '(': + case '(': { if (inClass) { re += '(' continue @@ -537,46 +556,64 @@ class Minimatch { continue } - patternListStack.push({ + const plEntry = { type: stateChar, start: i - 1, reStart: re.length, open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + close: plTypes[stateChar].close, + } + this.debug(this.pattern, '\t', plEntry) + patternListStack.push(plEntry) + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } this.debug('plType %j %j', stateChar, re) stateChar = false - continue + continue + } - case ')': - if (inClass || !patternListStack.length) { + case ')': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { re += '\\)' continue } + patternListStack.pop() + // closing an extglob clearStateChar() hasMagic = true - pl = patternListStack.pop() + pl = plEntry // negation is (?:(?!js)[^/]*) // The others are (?:) re += pl.close if (pl.type === '!') { - negativeLists.push(pl) + negativeLists.push(Object.assign(pl, { reEnd: re.length })) } - pl.reEnd = re.length - continue + continue + } - case '|': - if (inClass || !patternListStack.length) { + case '|': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { re += '\\|' continue } clearStateChar() re += '|' - continue + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + continue + } // these are mostly the same in regexp and glob case '[': @@ -604,8 +641,6 @@ class Minimatch { continue } - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that @@ -615,20 +650,16 @@ class Minimatch { // to do safely. For now, this is safe and works. cs = pattern.substring(classStart + 1, i) try { - RegExp('[' + cs + ']') + RegExp('[' + braExpEscape(charUnescape(cs)) + ']') + // looks good, finish up the class. + re += c } catch (er) { - // not a valid class! - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever } - - // finish up the class. hasMagic = true inClass = false - re += c continue default: @@ -652,9 +683,9 @@ class Minimatch { // this is a huge pita. We now have to re-walk // the contents of the would-be class to re-translate // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) + cs = pattern.slice(classStart + 1) sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + re = re.substring(0, reClassStart) + '\\[' + sp[0] hasMagic = hasMagic || sp[1] } @@ -721,14 +752,16 @@ class Minimatch { // Handle nested stuff like *(*.js|!(*.json)), where open parens // mean that we should *not* include the ) in the bit that is considered // "after" the negated section. - const openParensBefore = nlBefore.split('(').length - 1 + const closeParensBefore = nlBefore.split(')').length + const openParensBefore = nlBefore.split('(').length - closeParensBefore let cleanAfter = nlAfter for (let i = 0; i < openParensBefore; i++) { cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') } nlAfter = cleanAfter - const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '' + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' + re = nlBefore + nlFirst + nlAfter + dollar + nlLast } @@ -740,7 +773,7 @@ class Minimatch { } if (addPatternStart) { - re = patternStart + re + re = patternStart() + re } // parsing just a piece of a larger pattern. @@ -748,6 +781,11 @@ class Minimatch { return [re, hasMagic] } + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() + } + // skip the regexp for non-magical patterns // unescape anything in it, though, so that it'll be // an exact match against a file etc. diff --git a/node_modules/filelist/node_modules/minimatch/package.json b/node_modules/filelist/node_modules/minimatch/package.json index 8e1a842..c8809db 100644 --- a/node_modules/filelist/node_modules/minimatch/package.json +++ b/node_modules/filelist/node_modules/minimatch/package.json @@ -2,7 +2,10 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me)", "name": "minimatch", "description": "a glob matcher in javascript", - "version": "5.1.0", + "publishConfig": { + "tag": "legacy-v5" + }, + "version": "5.1.6", "repository": { "type": "git", "url": "git://github.com/isaacs/minimatch.git" @@ -22,7 +25,7 @@ "brace-expansion": "^2.0.1" }, "devDependencies": { - "tap": "^15.1.6" + "tap": "^16.3.2" }, "license": "ISC", "files": [ diff --git a/node_modules/flat/cli.js b/node_modules/flat/cli.js old mode 100755 new mode 100644 diff --git a/node_modules/fsevents/README.md b/node_modules/fsevents/README.md deleted file mode 100644 index 025c9a1..0000000 --- a/node_modules/fsevents/README.md +++ /dev/null @@ -1,83 +0,0 @@ -# fsevents [![NPM](https://nodei.co/npm/fsevents.png)](https://nodei.co/npm/fsevents/) - -Native access to MacOS FSEvents in [Node.js](https://nodejs.org/) - -The FSEvents API in MacOS allows applications to register for notifications of -changes to a given directory tree. It is a very fast and lightweight alternative -to kqueue. - -This is a low-level library. For a cross-platform file watching module that -uses fsevents, check out [Chokidar](https://github.com/paulmillr/chokidar). - -## Installation - -Supports only **Node.js v8.16 and higher**. - -```sh -npm install fsevents -``` - -## Usage - -```js -const fsevents = require('fsevents'); -const stop = fsevents.watch(__dirname, (path, flags, id) => { - const info = fsevents.getInfo(path, flags, id); -}); // To start observation -stop(); // To end observation -``` - -The callback passed as the second parameter to `.watch` get's called whenever the operating system detects a -a change in the file system. It takes three arguments: - -###### `fsevents.watch(dirname: string, (path: string, flags: number, id: string) => void): () => Promise` - - * `path: string` - the item in the filesystem that have been changed - * `flags: number` - a numeric value describing what the change was - * `id: string` - an unique-id identifying this specific event - - Returns closer callback which when called returns a Promise resolving when the watcher process has been shut down. - -###### `fsevents.getInfo(path: string, flags: number, id: string): FsEventInfo` - -The `getInfo` function takes the `path`, `flags` and `id` arguments and converts those parameters into a structure -that is easier to digest to determine what the change was. - -The `FsEventsInfo` has the following shape: - -```js -/** - * @typedef {'created'|'modified'|'deleted'|'moved'|'root-changed'|'cloned'|'unknown'} FsEventsEvent - * @typedef {'file'|'directory'|'symlink'} FsEventsType - */ -{ - "event": "created", // {FsEventsEvent} - "path": "file.txt", - "type": "file", // {FsEventsType} - "changes": { - "inode": true, // Had iNode Meta-Information changed - "finder": false, // Had Finder Meta-Data changed - "access": false, // Had access permissions changed - "xattrs": false // Had xAttributes changed - }, - "flags": 0x100000000 -} -``` - -## Changelog - -- v2.3 supports Apple Silicon ARM CPUs -- v2 supports node 8.16+ and reduces package size massively -- v1.2.8 supports node 6+ -- v1.2.7 supports node 4+ - -## Troubleshooting - -- I'm getting `EBADPLATFORM` `Unsupported platform for fsevents` error. -- It's fine, nothing is broken. fsevents is macos-only. Other platforms are skipped. If you want to hide this warning, report a bug to NPM bugtracker asking them to hide ebadplatform warnings by default. - -## License - -The MIT License Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller — see LICENSE file. - -Visit our [GitHub page](https://github.com/fsevents/fsevents) and [NPM Page](https://npmjs.org/package/fsevents) diff --git a/node_modules/fsevents/fsevents.d.ts b/node_modules/fsevents/fsevents.d.ts deleted file mode 100644 index 2723c04..0000000 --- a/node_modules/fsevents/fsevents.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -declare type Event = "created" | "cloned" | "modified" | "deleted" | "moved" | "root-changed" | "unknown"; -declare type Type = "file" | "directory" | "symlink"; -declare type FileChanges = { - inode: boolean; - finder: boolean; - access: boolean; - xattrs: boolean; -}; -declare type Info = { - event: Event; - path: string; - type: Type; - changes: FileChanges; - flags: number; -}; -declare type WatchHandler = (path: string, flags: number, id: string) => void; -export declare function watch(path: string, handler: WatchHandler): () => Promise; -export declare function watch(path: string, since: number, handler: WatchHandler): () => Promise; -export declare function getInfo(path: string, flags: number): Info; -export declare const constants: { - None: 0x00000000; - MustScanSubDirs: 0x00000001; - UserDropped: 0x00000002; - KernelDropped: 0x00000004; - EventIdsWrapped: 0x00000008; - HistoryDone: 0x00000010; - RootChanged: 0x00000020; - Mount: 0x00000040; - Unmount: 0x00000080; - ItemCreated: 0x00000100; - ItemRemoved: 0x00000200; - ItemInodeMetaMod: 0x00000400; - ItemRenamed: 0x00000800; - ItemModified: 0x00001000; - ItemFinderInfoMod: 0x00002000; - ItemChangeOwner: 0x00004000; - ItemXattrMod: 0x00008000; - ItemIsFile: 0x00010000; - ItemIsDir: 0x00020000; - ItemIsSymlink: 0x00040000; - ItemIsHardlink: 0x00100000; - ItemIsLastHardlink: 0x00200000; - OwnEvent: 0x00080000; - ItemCloned: 0x00400000; -}; -export {}; diff --git a/node_modules/fsevents/fsevents.js b/node_modules/fsevents/fsevents.js deleted file mode 100644 index f1b31c9..0000000 --- a/node_modules/fsevents/fsevents.js +++ /dev/null @@ -1,82 +0,0 @@ -/* - ** © 2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller - ** Licensed under MIT License. - */ - -/* jshint node:true */ -"use strict"; - -if (process.platform !== "darwin") { - throw new Error(`Module 'fsevents' is not compatible with platform '${process.platform}'`); -} - -const Native = require("./fsevents.node"); -const events = Native.constants; - -function watch(path, since, handler) { - if (typeof path !== "string") { - throw new TypeError(`fsevents argument 1 must be a string and not a ${typeof path}`); - } - if ("function" === typeof since && "undefined" === typeof handler) { - handler = since; - since = Native.flags.SinceNow; - } - if (typeof since !== "number") { - throw new TypeError(`fsevents argument 2 must be a number and not a ${typeof since}`); - } - if (typeof handler !== "function") { - throw new TypeError(`fsevents argument 3 must be a function and not a ${typeof handler}`); - } - - let instance = Native.start(Native.global, path, since, handler); - if (!instance) throw new Error(`could not watch: ${path}`); - return () => { - const result = instance ? Promise.resolve(instance).then(Native.stop) : Promise.resolve(undefined); - instance = undefined; - return result; - }; -} - -function getInfo(path, flags) { - return { - path, - flags, - event: getEventType(flags), - type: getFileType(flags), - changes: getFileChanges(flags), - }; -} - -function getFileType(flags) { - if (events.ItemIsFile & flags) return "file"; - if (events.ItemIsDir & flags) return "directory"; - if (events.ItemIsSymlink & flags) return "symlink"; -} -function anyIsTrue(obj) { - for (let key in obj) { - if (obj[key]) return true; - } - return false; -} -function getEventType(flags) { - if (events.ItemRemoved & flags) return "deleted"; - if (events.ItemRenamed & flags) return "moved"; - if (events.ItemCreated & flags) return "created"; - if (events.ItemModified & flags) return "modified"; - if (events.RootChanged & flags) return "root-changed"; - if (events.ItemCloned & flags) return "cloned"; - if (anyIsTrue(flags)) return "modified"; - return "unknown"; -} -function getFileChanges(flags) { - return { - inode: !!(events.ItemInodeMetaMod & flags), - finder: !!(events.ItemFinderInfoMod & flags), - access: !!(events.ItemChangeOwner & flags), - xattrs: !!(events.ItemXattrMod & flags), - }; -} - -exports.watch = watch; -exports.getInfo = getInfo; -exports.constants = events; diff --git a/node_modules/fsevents/fsevents.node b/node_modules/fsevents/fsevents.node deleted file mode 100755 index 00fac7e..0000000 Binary files a/node_modules/fsevents/fsevents.node and /dev/null differ diff --git a/node_modules/fsevents/package.json b/node_modules/fsevents/package.json deleted file mode 100644 index af6da84..0000000 --- a/node_modules/fsevents/package.json +++ /dev/null @@ -1,62 +0,0 @@ -{ - "name": "fsevents", - "version": "2.3.2", - "description": "Native Access to MacOS FSEvents", - "main": "fsevents.js", - "types": "fsevents.d.ts", - "os": [ - "darwin" - ], - "files": [ - "fsevents.d.ts", - "fsevents.js", - "fsevents.node" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - }, - "scripts": { - "clean": "node-gyp clean && rm -f fsevents.node", - "build": "node-gyp clean && rm -f fsevents.node && node-gyp rebuild && node-gyp clean", - "test": "/bin/bash ./test.sh 2>/dev/null", - "prepublishOnly": "npm run build" - }, - "repository": { - "type": "git", - "url": "https://github.com/fsevents/fsevents.git" - }, - "keywords": [ - "fsevents", - "mac" - ], - "contributors": [ - { - "name": "Philipp Dunkel", - "email": "pip@pipobscure.com" - }, - { - "name": "Ben Noordhuis", - "email": "info@bnoordhuis.nl" - }, - { - "name": "Elan Shankar", - "email": "elan.shanker@gmail.com" - }, - { - "name": "Miroslav Bajtoš", - "email": "mbajtoss@gmail.com" - }, - { - "name": "Paul Miller", - "url": "https://paulmillr.com" - } - ], - "license": "MIT", - "bugs": { - "url": "https://github.com/fsevents/fsevents/issues" - }, - "homepage": "https://github.com/fsevents/fsevents", - "devDependencies": { - "node-gyp": "^6.1.0" - } -} diff --git a/node_modules/glob/LICENSE b/node_modules/glob/LICENSE index 42ca266..39e8fe1 100644 --- a/node_modules/glob/LICENSE +++ b/node_modules/glob/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) Isaac Z. Schlueter and Contributors +Copyright (c) 2009-2022 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above @@ -13,9 +13,3 @@ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -## Glob Logo - -Glob's logo created by Tanya Brassie , licensed -under a Creative Commons Attribution-ShareAlike 4.0 International License -https://creativecommons.org/licenses/by-sa/4.0/ diff --git a/node_modules/glob/README.md b/node_modules/glob/README.md index 0916a48..6293911 100644 --- a/node_modules/glob/README.md +++ b/node_modules/glob/README.md @@ -7,7 +7,7 @@ Match files using the patterns the shell uses, like stars and stuff. This is a glob implementation in JavaScript. It uses the `minimatch` library to do its matching. -![](logo/glob.png) +![a fun cartoon logo made of glob characters](logo/glob.png) ## Usage @@ -210,10 +210,26 @@ parallel glob operations will be sped up by sharing information about the filesystem. * `cwd` The current working directory in which to search. Defaults - to `process.cwd()`. + to `process.cwd()`. This option is always coerced to use + forward-slashes as a path separator, because it is not tested + as a glob pattern, so there is no need to escape anything. * `root` The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix - systems, and `C:\` or some such on Windows.) + systems, and `C:\` or some such on Windows.) This option is + always coerced to use forward-slashes as a path separator, + because it is not tested as a glob pattern, so there is no need + to escape anything. +* `windowsPathsNoEscape` Use `\\` as a path separator _only_, and + _never_ as an escape character. If set, all `\\` characters + are replaced with `/` in the pattern. Note that this makes it + **impossible** to match against paths containing literal glob + pattern characters, but allows matching with patterns constructed + using `path.join()` and `path.resolve()` on Windows platforms, + mimicking the (buggy!) behavior of Glob v7 and before on + Windows. Please use with caution, and be mindful of [the caveat + below about Windows paths](#windows). (For legacy reasons, + this is also set if `allowWindowsEscape` is set to the exact + value `false`.) * `dot` Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. @@ -276,6 +292,9 @@ the filesystem. * `absolute` Set to true to always receive absolute paths for matched files. Unlike `realpath`, this also affects the values returned in the `match` event. +* `fs` File-system object with Node's `fs` API. By default, the built-in + `fs` module will be used. Set to a volume provided by a library like + `memfs` to avoid using the "real" file-system. ## Comparisons to other fnmatch/glob implementations @@ -329,6 +348,11 @@ Results from absolute patterns such as `/foo/*` are mounted onto the root setting using `path.join`. On windows, this will by default result in `/foo/*` matching `C:\foo\bar.txt`. +To automatically coerce all `\` characters to `/` in pattern +strings, **thus making it impossible to escape literal glob +characters**, you may set the `windowsPathsNoEscape` option to +`true`. + ## Race Conditions Glob searching, by its very nature, is susceptible to race conditions, diff --git a/node_modules/glob/changelog.md b/node_modules/glob/changelog.md deleted file mode 100644 index 4163677..0000000 --- a/node_modules/glob/changelog.md +++ /dev/null @@ -1,67 +0,0 @@ -## 7.0 - -- Raise error if `options.cwd` is specified, and not a directory - -## 6.0 - -- Remove comment and negation pattern support -- Ignore patterns are always in `dot:true` mode - -## 5.0 - -- Deprecate comment and negation patterns -- Fix regression in `mark` and `nodir` options from making all cache - keys absolute path. -- Abort if `fs.readdir` returns an error that's unexpected -- Don't emit `match` events for ignored items -- Treat ENOTSUP like ENOTDIR in readdir - -## 4.5 - -- Add `options.follow` to always follow directory symlinks in globstar -- Add `options.realpath` to call `fs.realpath` on all results -- Always cache based on absolute path - -## 4.4 - -- Add `options.ignore` -- Fix handling of broken symlinks - -## 4.3 - -- Bump minimatch to 2.x -- Pass all tests on Windows - -## 4.2 - -- Add `glob.hasMagic` function -- Add `options.nodir` flag - -## 4.1 - -- Refactor sync and async implementations for performance -- Throw if callback provided to sync glob function -- Treat symbolic links in globstar results the same as Bash 4.3 - -## 4.0 - -- Use `^` for dependency versions (bumped major because this breaks - older npm versions) -- Ensure callbacks are only ever called once -- switch to ISC license - -## 3.x - -- Rewrite in JavaScript -- Add support for setting root, cwd, and windows support -- Cache many fs calls -- Add globstar support -- emit match events - -## 2.x - -- Use `glob.h` and `fnmatch.h` from NetBSD - -## 1.x - -- `glob.h` static binding. diff --git a/node_modules/glob/common.js b/node_modules/glob/common.js index 66651bb..61a4452 100644 --- a/node_modules/glob/common.js +++ b/node_modules/glob/common.js @@ -1,5 +1,3 @@ -exports.alphasort = alphasort -exports.alphasorti = alphasorti exports.setopts = setopts exports.ownProp = ownProp exports.makeAbs = makeAbs @@ -12,17 +10,14 @@ function ownProp (obj, field) { return Object.prototype.hasOwnProperty.call(obj, field) } +var fs = require("fs") var path = require("path") var minimatch = require("minimatch") -var isAbsolute = require("path-is-absolute") +var isAbsolute = require("path").isAbsolute var Minimatch = minimatch.Minimatch -function alphasorti (a, b) { - return a.toLowerCase().localeCompare(b.toLowerCase()) -} - function alphasort (a, b) { - return a.localeCompare(b) + return a.localeCompare(b, 'en') } function setupIgnores (self, options) { @@ -62,6 +57,12 @@ function setopts (self, pattern, options) { pattern = "**/" + pattern } + self.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (self.windowsPathsNoEscape) { + pattern = pattern.replace(/\\/g, '/') + } + self.silent = !!options.silent self.pattern = pattern self.strict = options.strict !== false @@ -81,6 +82,7 @@ function setopts (self, pattern, options) { self.stat = !!options.stat self.noprocess = !!options.noprocess self.absolute = !!options.absolute + self.fs = options.fs || fs self.maxLength = options.maxLength || Infinity self.cache = options.cache || Object.create(null) @@ -92,7 +94,7 @@ function setopts (self, pattern, options) { self.changedCwd = false var cwd = process.cwd() if (!ownProp(options, "cwd")) - self.cwd = cwd + self.cwd = path.resolve(cwd) else { self.cwd = path.resolve(options.cwd) self.changedCwd = self.cwd !== cwd @@ -100,16 +102,18 @@ function setopts (self, pattern, options) { self.root = options.root || path.resolve(self.cwd, "/") self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") // TODO: is an absolute `cwd` supposed to be resolved against `root`? // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") self.nomount = !!options.nomount + if (process.platform === "win32") { + self.root = self.root.replace(/\\/g, "/") + self.cwd = self.cwd.replace(/\\/g, "/") + self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") + } + // disable comments and negation in Minimatch. // Note that they are not supported in Glob itself anyway. options.nonegate = true @@ -150,7 +154,7 @@ function finish (self) { all = Object.keys(all) if (!self.nosort) - all = all.sort(self.nocase ? alphasorti : alphasort) + all = all.sort(alphasort) // at *some* point we statted all of these if (self.mark) { diff --git a/node_modules/glob/glob.js b/node_modules/glob/glob.js index 58dec0f..2112a95 100644 --- a/node_modules/glob/glob.js +++ b/node_modules/glob/glob.js @@ -40,7 +40,6 @@ module.exports = glob -var fs = require('fs') var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch @@ -48,11 +47,9 @@ var inherits = require('inherits') var EE = require('events').EventEmitter var path = require('path') var assert = require('assert') -var isAbsolute = require('path-is-absolute') +var isAbsolute = require('path').isAbsolute var globSync = require('./sync.js') var common = require('./common.js') -var alphasort = common.alphasort -var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var inflight = require('inflight') @@ -345,7 +342,10 @@ Glob.prototype._process = function (pattern, index, inGlobStar, cb) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix @@ -503,7 +503,7 @@ Glob.prototype._readdirInGlobStar = function (abs, cb) { var lstatcb = inflight(lstatkey, lstatcb_) if (lstatcb) - fs.lstat(abs, lstatcb) + self.fs.lstat(abs, lstatcb) function lstatcb_ (er, lstat) { if (er && er.code === 'ENOENT') @@ -544,7 +544,7 @@ Glob.prototype._readdir = function (abs, inGlobStar, cb) { } var self = this - fs.readdir(abs, readdirCb(this, abs, cb)) + self.fs.readdir(abs, readdirCb(this, abs, cb)) } function readdirCb (self, abs, cb) { @@ -748,13 +748,13 @@ Glob.prototype._stat = function (f, cb) { var self = this var statcb = inflight('stat\0' + abs, lstatcb_) if (statcb) - fs.lstat(abs, statcb) + self.fs.lstat(abs, statcb) function lstatcb_ (er, lstat) { if (lstat && lstat.isSymbolicLink()) { // If it's a symlink, then treat it as the target, unless // the target does not exist, then treat it as a file. - return fs.stat(abs, function (er, stat) { + return self.fs.stat(abs, function (er, stat) { if (er) self._stat2(f, abs, null, lstat, cb) else diff --git a/node_modules/glob/node_modules/brace-expansion/.github/FUNDING.yml b/node_modules/glob/node_modules/brace-expansion/.github/FUNDING.yml new file mode 100644 index 0000000..79d1eaf --- /dev/null +++ b/node_modules/glob/node_modules/brace-expansion/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/brace-expansion" +patreon: juliangruber diff --git a/node_modules/fsevents/LICENSE b/node_modules/glob/node_modules/brace-expansion/LICENSE similarity index 83% rename from node_modules/fsevents/LICENSE rename to node_modules/glob/node_modules/brace-expansion/LICENSE index 5d70441..de32266 100644 --- a/node_modules/fsevents/LICENSE +++ b/node_modules/glob/node_modules/brace-expansion/LICENSE @@ -1,7 +1,6 @@ MIT License ------------ -Copyright (C) 2010-2020 by Philipp Dunkel, Ben Noordhuis, Elan Shankar, Paul Miller +Copyright (c) 2013 Julian Gruber Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -10,13 +9,13 @@ 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 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. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/glob/node_modules/brace-expansion/README.md b/node_modules/glob/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..e55c583 --- /dev/null +++ b/node_modules/glob/node_modules/brace-expansion/README.md @@ -0,0 +1,135 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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. diff --git a/node_modules/glob/node_modules/brace-expansion/index.js b/node_modules/glob/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..4af9dde --- /dev/null +++ b/node_modules/glob/node_modules/brace-expansion/index.js @@ -0,0 +1,203 @@ +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; +} + diff --git a/node_modules/glob/node_modules/brace-expansion/package.json b/node_modules/glob/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..7097d41 --- /dev/null +++ b/node_modules/glob/node_modules/brace-expansion/package.json @@ -0,0 +1,46 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "2.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0" + }, + "devDependencies": { + "@c4312/matcha": "^1.3.1", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/isexe/LICENSE b/node_modules/glob/node_modules/minimatch/LICENSE similarity index 92% rename from node_modules/isexe/LICENSE rename to node_modules/glob/node_modules/minimatch/LICENSE index 19129e3..1493534 100644 --- a/node_modules/isexe/LICENSE +++ b/node_modules/glob/node_modules/minimatch/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) Isaac Z. Schlueter and Contributors +Copyright (c) 2011-2023 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above diff --git a/node_modules/glob/node_modules/minimatch/README.md b/node_modules/glob/node_modules/minimatch/README.md new file mode 100644 index 0000000..a5bdefa --- /dev/null +++ b/node_modules/glob/node_modules/minimatch/README.md @@ -0,0 +1,259 @@ +# minimatch + +A minimal matching utility. + +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) + + +This is the matching library used internally by npm. + +It works by converting glob expressions into JavaScript `RegExp` +objects. + +## Usage + +```javascript +var minimatch = require("minimatch") + +minimatch("bar.foo", "*.foo") // true! +minimatch("bar.foo", "*.bar") // false! +minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy! +``` + +## Features + +Supports these glob features: + +* Brace Expansion +* Extended glob matching +* "Globstar" `**` matching + +See: + +* `man sh` +* `man bash` +* `man 3 fnmatch` +* `man 5 gitignore` + +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + +## Minimatch Class + +Create a minimatch object by instantiating the `minimatch.Minimatch` class. + +```javascript +var Minimatch = require("minimatch").Minimatch +var mm = new Minimatch(pattern, options) +``` + +### Properties + +* `pattern` The original pattern the minimatch object represents. +* `options` The options supplied to the constructor. +* `set` A 2-dimensional array of regexp or string expressions. + Each row in the + array corresponds to a brace-expanded pattern. Each item in the row + corresponds to a single path-part. For example, the pattern + `{a,b/c}/d` would expand to a set of patterns like: + + [ [ a, d ] + , [ b, c, d ] ] + + If a portion of the pattern doesn't have any "magic" in it + (that is, it's something like `"foo"` rather than `fo*o?`), then it + will be left as a string rather than converted to a regular + expression. + +* `regexp` Created by the `makeRe` method. A single regular expression + expressing the entire pattern. This is useful in cases where you wish + to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. +* `negate` True if the pattern is negated. +* `comment` True if the pattern is a comment. +* `empty` True if the pattern is `""`. + +### Methods + +* `makeRe` Generate the `regexp` member if necessary, and return it. + Will return `false` if the pattern is invalid. +* `match(fname)` Return true if the filename matches the pattern, or + false otherwise. +* `matchOne(fileArray, patternArray, partial)` Take a `/`-split + filename, and match it against a single row in the `regExpSet`. This + method is mainly for internal use, but is exposed so that it can be + used by a glob-walker that needs to avoid excessive filesystem calls. + +All other methods are internal, and will be called as necessary. + +### minimatch(path, pattern, options) + +Main export. Tests a path against the pattern using the options. + +```javascript +var isJS = minimatch(file, "*.js", { matchBase: true }) +``` + +### minimatch.filter(pattern, options) + +Returns a function that tests its +supplied argument, suitable for use with `Array.filter`. Example: + +```javascript +var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true})) +``` + +### minimatch.match(list, pattern, options) + +Match against the list of +files, in the style of fnmatch or glob. If nothing is matched, and +options.nonull is set, then return a list containing the pattern itself. + +```javascript +var javascripts = minimatch.match(fileList, "*.js", {matchBase: true}) +``` + +### minimatch.makeRe(pattern, options) + +Make a regular expression object from the pattern. + +## Options + +All options are `false` by default. + +### debug + +Dump a ton of stuff to stderr. + +### nobrace + +Do not expand `{a,b}` and `{1..3}` brace sets. + +### noglobstar + +Disable `**` matching against multiple folder names. + +### dot + +Allow patterns to match filenames starting with a period, even if +the pattern does not explicitly have a period in that spot. + +Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot` +is set. + +### noext + +Disable "extglob" style patterns like `+(a|b)`. + +### nocase + +Perform a case-insensitive match. + +### nonull + +When a match is not found by `minimatch.match`, return a list containing +the pattern itself if this option is set. When not set, an empty list +is returned if there are no matches. + +### matchBase + +If set, then patterns without slashes will be matched +against the basename of the path if it contains slashes. For example, +`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. + +### nocomment + +Suppress the behavior of treating `#` at the start of a pattern as a +comment. + +### nonegate + +Suppress the behavior of treating a leading `!` character as negation. + +### flipNegate + +Returns from negate expressions the same as if they were not negated. +(Ie, true on a hit, false on a miss.) + +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` + +### windowsPathsNoEscape + +Use `\\` as a path separator _only_, and _never_ as an escape +character. If set, all `\\` characters are replaced with `/` in +the pattern. Note that this makes it **impossible** to match +against paths containing literal glob pattern characters, but +allows matching with patterns constructed using `path.join()` and +`path.resolve()` on Windows platforms, mimicking the (buggy!) +behavior of earlier versions on Windows. Please use with +caution, and be mindful of [the caveat about Windows +paths](#windows). + +For legacy reasons, this is also set if +`options.allowWindowsEscape` is set to the exact value `false`. + +## Comparisons to other fnmatch/glob implementations + +While strict compliance with the existing standards is a worthwhile +goal, some discrepancies exist between minimatch and other +implementations, and are intentional. + +If the pattern starts with a `!` character, then it is negated. Set the +`nonegate` flag to suppress this behavior, and treat leading `!` +characters normally. This is perhaps relevant if you wish to start the +pattern with a negative extglob pattern like `!(a|B)`. Multiple `!` +characters at the start of a pattern will negate the pattern multiple +times. + +If a pattern starts with `#`, then it is treated as a comment, and +will not match anything. Use `\#` to match a literal `#` at the +start of a line, or set the `nocomment` flag to suppress this behavior. + +The double-star character `**` is supported by default, unless the +`noglobstar` flag is set. This is supported in the manner of bsdglob +and bash 4.1, where `**` only has special significance if it is the only +thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but +`a/**b` will not. + +If an escaped pattern has no matches, and the `nonull` flag is set, +then minimatch.match returns the pattern as-provided, rather than +interpreting the character escapes. For example, +`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than +`"*a?"`. This is akin to setting the `nullglob` option in bash, except +that it does not resolve escaped pattern characters. + +If brace expansion is not disabled, then it is performed before any +other interpretation of the glob pattern. Thus, a pattern like +`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded +**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are +checked for validity. Since those two are valid, matching proceeds. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/glob/node_modules/minimatch/lib/path.js b/node_modules/glob/node_modules/minimatch/lib/path.js new file mode 100644 index 0000000..ffe453d --- /dev/null +++ b/node_modules/glob/node_modules/minimatch/lib/path.js @@ -0,0 +1,4 @@ +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } diff --git a/node_modules/glob/node_modules/minimatch/minimatch.js b/node_modules/glob/node_modules/minimatch/minimatch.js new file mode 100644 index 0000000..6c8bfc3 --- /dev/null +++ b/node_modules/glob/node_modules/minimatch/minimatch.js @@ -0,0 +1,944 @@ +const minimatch = module.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern) + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + +module.exports = minimatch + +const path = require('./lib/path.js') +minimatch.sep = path.sep + +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = require('brace-expansion') + +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} + +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]' + +// * => any number of characters +const star = qmark + '*?' + +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' + +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) + +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!') + +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') + +// normalizes slashes. +const slashSplit = /\/+/ + +minimatch.filter = (pattern, options = {}) => + (p, i, list) => minimatch(p, pattern, options) + +const ext = (a, b = {}) => { + const t = {} + Object.keys(a).forEach(k => t[k] = a[k]) + Object.keys(b).forEach(k => t[k] = b[k]) + return t +} + +minimatch.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } + + const orig = minimatch + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)) + } + } + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) + m.defaults = options => orig.defaults(ext(def, options)) + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) + + return m +} + + + + + +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) + +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern) + + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } + + return expand(pattern) +} + +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } + + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} + +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse') + +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() + +minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options) + list = list.filter(f => mm.match(f)) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} + +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') + +class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern) + + if (!options) options = {} + + this.options = options + this.set = [] + this.pattern = pattern + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/') + } + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() + } + + debug () {} + + make () { + const pattern = this.pattern + const options = this.options + + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } + + // step 1: figure out negation, etc. + this.parseNegate() + + // step 2: expand braces + let set = this.globSet = this.braceExpand() + + if (options.debug) this.debug = (...args) => console.error(...args) + + this.debug(this.pattern, set) + + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)) + + this.debug(this.pattern, set) + + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) + + this.debug(this.pattern, set) + + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) + + this.debug(this.pattern, set) + + this.set = set + } + + parseNegate () { + if (this.options.nonegate) return + + const pattern = this.pattern + let negate = false + let negateOffset = 0 + + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ + } + + if (negateOffset) this.pattern = pattern.slice(negateOffset) + this.negate = negate + } + + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } + + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } + + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } + + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } + + if (!hit) return false + } + + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) + } + + parse (pattern, isSub) { + assertValidPattern(pattern) + + const options = this.options + + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + let re = '' + let hasMagic = false + let escaping = false + // ? => one single character + const patternListStack = [] + const negativeLists = [] + let stateChar + let inClass = false + let reClassStart = -1 + let classStart = -1 + let cs + let pl + let sp + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.' + let dotFileAllowed = options.dot || dotTravAllowed + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + + + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + this.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } + } + + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } + + if (reSpecials[c]) { + re += '\\' + } + re += c + escaping = false + continue + } + + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } + + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c + continue + } + + clearStateChar() + escaping = true + continue + + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } + + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': { + if (inClass) { + re += '(' + continue + } + + if (!stateChar) { + re += '\\(' + continue + } + + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + } + this.debug(this.pattern, '\t', plEntry) + patternListStack.push(plEntry) + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + } + + case ')': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\)' + continue + } + patternListStack.pop() + + // closing an extglob + clearStateChar() + hasMagic = true + pl = plEntry + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })) + } + continue + } + + case '|': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\|' + continue + } + + clearStateChar() + re += '|' + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + continue + } + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } + + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + continue + } + + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']') + // looks good, finish up the class. + re += c + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever + } + hasMagic = true + inClass = false + continue + + default: + // swallow any state char that wasn't consumed + clearStateChar() + + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } + + re += c + break + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substring(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } + + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail + tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } + + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)] + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n] + + const nlBefore = re.slice(0, nl.reStart) + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + let nlAfter = re.slice(nl.reEnd) + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length + const openParensBefore = nlBefore.split('(').length - closeParensBefore + let cleanAfter = nlAfter + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' + + re = nlBefore + nlFirst + nlAfter + dollar + nlLast + } + + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re + } + + if (addPatternStart) { + re = patternStart() + re + } + + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } + + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : '' + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } + } + + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp + + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set + + if (!set.length) { + this.regexp = false + return this.regexp + } + const options = this.options + + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' + + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set.push(p) + } + return set + }, []) + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] + } else { + pattern[i] = twoStar + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?' + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] + pattern[i+1] = GLOBSTAR + } + }) + return pattern.filter(p => p !== GLOBSTAR).join('/') + }).join('|') + + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp + } + + match (f, partial = this.partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' + + if (f === '/' && partial) return true + + const options = this.options + + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } + + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) + + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. + + const set = this.set + this.debug(this.pattern, 'set', set) + + // Find the basename of the path by looking for the last non-empty segment + let filename + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + + for (let i = 0; i < set.length; i++) { + const pattern = set[i] + let file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + const hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } + + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate + } + + static defaults (def) { + return minimatch.defaults(def).Minimatch + } +} + +minimatch.Minimatch = Minimatch diff --git a/node_modules/glob/node_modules/minimatch/package.json b/node_modules/glob/node_modules/minimatch/package.json new file mode 100644 index 0000000..c8809db --- /dev/null +++ b/node_modules/glob/node_modules/minimatch/package.json @@ -0,0 +1,35 @@ +{ + "author": "Isaac Z. Schlueter (http://blog.izs.me)", + "name": "minimatch", + "description": "a glob matcher in javascript", + "publishConfig": { + "tag": "legacy-v5" + }, + "version": "5.1.6", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/minimatch.git" + }, + "main": "minimatch.js", + "scripts": { + "test": "tap", + "snap": "tap", + "preversion": "npm test", + "postversion": "npm publish", + "prepublishOnly": "git push origin --follow-tags" + }, + "engines": { + "node": ">=10" + }, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "devDependencies": { + "tap": "^16.3.2" + }, + "license": "ISC", + "files": [ + "minimatch.js", + "lib" + ] +} diff --git a/node_modules/glob/package.json b/node_modules/glob/package.json index 6477c30..ca0fd91 100644 --- a/node_modules/glob/package.json +++ b/node_modules/glob/package.json @@ -2,7 +2,7 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me/)", "name": "glob", "description": "a little globber", - "version": "7.1.6", + "version": "8.1.0", "repository": { "type": "git", "url": "git://github.com/isaacs/node-glob.git" @@ -14,26 +14,35 @@ "common.js" ], "engines": { - "node": "*" + "node": ">=12" }, "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", - "minimatch": "^3.0.4", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "minimatch": "^5.0.1", + "once": "^1.3.0" }, "devDependencies": { + "memfs": "^3.2.0", "mkdirp": "0", "rimraf": "^2.2.8", - "tap": "^12.0.1", + "tap": "^16.0.1", "tick": "0.0.6" }, + "tap": { + "before": "test/00-setup.js", + "after": "test/zz-cleanup.js", + "statements": 90, + "branches": 90, + "functions": 90, + "lines": 90, + "jobs": 1 + }, "scripts": { "prepublish": "npm run benchclean", "profclean": "rm -f v8.log profile.txt", - "test": "tap test/*.js --cov", + "test": "tap", "test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js", "bench": "bash benchmark.sh", "prof": "bash prof.sh && cat profile.txt", diff --git a/node_modules/glob/sync.js b/node_modules/glob/sync.js index c952134..af4600d 100644 --- a/node_modules/glob/sync.js +++ b/node_modules/glob/sync.js @@ -1,7 +1,6 @@ module.exports = globSync globSync.GlobSync = GlobSync -var fs = require('fs') var rp = require('fs.realpath') var minimatch = require('minimatch') var Minimatch = minimatch.Minimatch @@ -9,10 +8,8 @@ var Glob = require('./glob.js').Glob var util = require('util') var path = require('path') var assert = require('assert') -var isAbsolute = require('path-is-absolute') +var isAbsolute = require('path').isAbsolute var common = require('./common.js') -var alphasort = common.alphasort -var alphasorti = common.alphasorti var setopts = common.setopts var ownProp = common.ownProp var childrenIgnored = common.childrenIgnored @@ -51,7 +48,7 @@ function GlobSync (pattern, options) { } GlobSync.prototype._finish = function () { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) if (this.realpath) { var self = this this.matches.forEach(function (matchset, index) { @@ -75,7 +72,7 @@ GlobSync.prototype._finish = function () { GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert(this instanceof GlobSync) + assert.ok(this instanceof GlobSync) // Get the first [n] parts of pattern that are all strings. var n = 0 @@ -112,7 +109,10 @@ GlobSync.prototype._process = function (pattern, index, inGlobStar) { var read if (prefix === null) read = '.' - else if (isAbsolute(prefix) || isAbsolute(pattern.join('/'))) { + else if (isAbsolute(prefix) || + isAbsolute(pattern.map(function (p) { + return typeof p === 'string' ? p : '[*]' + }).join('/'))) { if (!prefix || !isAbsolute(prefix)) prefix = '/' + prefix read = prefix @@ -248,7 +248,7 @@ GlobSync.prototype._readdirInGlobStar = function (abs) { var lstat var stat try { - lstat = fs.lstatSync(abs) + lstat = this.fs.lstatSync(abs) } catch (er) { if (er.code === 'ENOENT') { // lstat failed, doesn't exist @@ -285,7 +285,7 @@ GlobSync.prototype._readdir = function (abs, inGlobStar) { } try { - return this._readdirEntries(abs, fs.readdirSync(abs)) + return this._readdirEntries(abs, this.fs.readdirSync(abs)) } catch (er) { this._readdirError(abs, er) return null @@ -444,7 +444,7 @@ GlobSync.prototype._stat = function (f) { if (!stat) { var lstat try { - lstat = fs.lstatSync(abs) + lstat = this.fs.lstatSync(abs) } catch (er) { if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { this.statCache[abs] = false @@ -454,7 +454,7 @@ GlobSync.prototype._stat = function (f) { if (lstat && lstat.isSymbolicLink()) { try { - stat = fs.statSync(abs) + stat = this.fs.statSync(abs) } catch (er) { stat = lstat } diff --git a/node_modules/growl/.eslintrc.json b/node_modules/growl/.eslintrc.json deleted file mode 100644 index f067e89..0000000 --- a/node_modules/growl/.eslintrc.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "extends": ["airbnb-base", "eslint:recommended", "plugin:node/recommended"], - "plugins": [ - "import", - "node" - ], - "rules": { - "no-console": ["error", { "allow": ["warn", "error"] }] - }, - "env": { - "node": true, - "es6": true - } -} diff --git a/node_modules/growl/.tags b/node_modules/growl/.tags deleted file mode 100644 index ce68994..0000000 --- a/node_modules/growl/.tags +++ /dev/null @@ -1,195 +0,0 @@ -name /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "name": "growl",$/;" function line:2 -version /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "version": "1.10.1",$/;" function line:3 -description /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "description": "Growl unobtrusive notifications",$/;" function line:4 -author /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "author": "TJ Holowaychuk ",$/;" function line:5 -maintainers /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "maintainers": [$/;" function line:6 -repository /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "repository": {$/;" function line:10 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "type": "git",$/;" function line:11 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "url": "git:\/\/github.com\/tj\/node-growl.git"$/;" function line:12 -main /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "main": ".\/lib\/growl.js",$/;" function line:14 -license /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "license": "MIT",$/;" function line:15 -devDependencies /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "devDependencies": {$/;" function line:16 -eslint /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "eslint": "^4.2.0",$/;" function line:17 -eslint-config-airbnb-base /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "eslint-config-airbnb-base": "^11.2.0",$/;" function line:18 -eslint-plugin-import /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "eslint-plugin-import": "^2.7.0"$/;" function line:19 -scripts /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "scripts": {$/;" function line:21 -test /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "test": "node test.js",$/;" function line:22 -lint /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "lint": "eslint --ext js lib "$/;" function line:23 -engines /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "engines": {$/;" function line:25 -node /Users/timosand/Dropbox/Documents/Projects/node-growl/package.json /^ "node": ">=4.x"$/;" function line:26 -extends /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "extends": ["airbnb-base", "eslint:recommended", "plugin:node\/recommended"],$/;" function line:2 -plugins /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "plugins": [$/;" function line:3 -rules /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "rules": {$/;" function line:7 -no-console /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "no-console": ["error", { "allow": ["warn", "error"] }]$/;" function line:8 -env /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "env": {$/;" function line:10 -node /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "node": true,$/;" function line:11 -es6 /Users/timosand/Dropbox/Documents/Projects/node-growl/.eslintrc.json /^ "es6": true$/;" function line:12 -language /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^language: node_js$/;" function line:1 -dist /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^dist: trusty$/;" function line:2 -os /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^os:$/;" function line:3 -node_js /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^node_js:$/;" function line:6 -before_install /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^before_install:$/;" function line:12 -jobs /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^jobs:$/;" function line:14 -include /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^ include:$/;" function line:15 -script /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^ script: npm run lint$/;" function line:17 -script /Users/timosand/Dropbox/Documents/Projects/node-growl/.travis.yml /^ script: npm test$/;" function line:19 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^let cmd;$/;" variable line:15 -which /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function which(name) {$/;" function line:17 -loc /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let loc;$/;" variable line:19 -len /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ for (let i = 0, len = paths.length; i < len; i += 1) {$/;" variable line:21 -loc /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ loc = path.join(paths[i], name);$/;" variable line:22 -setupCmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function setupCmd() {$/;" function line:28 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:32 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:32 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-NotificationCenter',$/;" string line:33 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-NotificationCenter',$/;" variable line:33 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'terminal-notifier',$/;" string line:34 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'terminal-notifier',$/;" variable line:34 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-message',$/;" string line:35 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-message',$/;" variable line:35 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" string line:36 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" variable line:36 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" string line:37 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" variable line:37 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-appIcon',$/;" string line:38 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-appIcon',$/;" variable line:38 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sound: '-sound',$/;" string line:39 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sound: '-sound',$/;" variable line:39 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '-open',$/;" string line:40 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '-open',$/;" variable line:40 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:41 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:41 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-execute',$/;" string line:42 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-execute',$/;" variable line:42 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" array line:43 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" variable line:43 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:47 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:47 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-Growl',$/;" string line:48 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-Growl',$/;" variable line:48 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" string line:49 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" variable line:49 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" string line:50 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" variable line:50 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '--sticky',$/;" string line:51 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '--sticky',$/;" variable line:51 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '--url',$/;" string line:52 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '--url',$/;" variable line:52 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:53 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:53 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '--priority',$/;" string line:54 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '--priority',$/;" variable line:54 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:55 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:55 -0 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 0,$/;" variable line:58 -1 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 1,$/;" variable line:59 -2 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 2,$/;" variable line:60 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:70 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:73 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:73 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux-Growl',$/;" string line:74 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux-Growl',$/;" variable line:74 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growl',$/;" string line:75 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growl',$/;" variable line:75 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" string line:76 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" variable line:76 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" string line:77 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" variable line:77 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" string line:78 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" variable line:78 -host /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ host: {$/;" object line:79 -host /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ host: {$/;" variable line:79 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-H',$/;" string line:80 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-H',$/;" variable line:80 -hostname /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ hostname: '192.168.33.1',$/;" string line:81 -hostname /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ hostname: '192.168.33.1',$/;" variable line:81 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:85 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:85 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux',$/;" string line:86 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux',$/;" variable line:86 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'notify-send',$/;" string line:87 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'notify-send',$/;" variable line:87 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" string line:88 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" variable line:88 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '-t 0',$/;" string line:89 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '-t 0',$/;" variable line:89 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-i',$/;" string line:90 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-i',$/;" variable line:90 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:91 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:91 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-u',$/;" string line:92 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-u',$/;" variable line:92 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:93 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:93 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:101 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:103 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:103 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Windows',$/;" string line:104 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Windows',$/;" variable line:104 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" string line:105 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" variable line:105 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" string line:106 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" variable line:106 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '\/s:true',$/;" string line:107 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '\/s:true',$/;" variable line:107 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '\/t:',$/;" string line:108 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '\/t:',$/;" variable line:108 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '\/i:',$/;" string line:109 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '\/i:',$/;" variable line:109 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '\/cu:',$/;" string line:110 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '\/cu:',$/;" variable line:110 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:111 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:111 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '\/p:',$/;" string line:112 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '\/p:',$/;" variable line:112 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:113 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:113 -0 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 0,$/;" variable line:116 -1 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 1,$/;" variable line:117 -2 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 2,$/;" variable line:118 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:122 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:124 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;" string line:151 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;" variable line:151 -opts /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function growl(msg, opts, callback) {$/;" variable line:162 -growl /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function growl(msg, opts, callback) {$/;" function line:162 -image /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let image;$/;" variable line:163 -noop /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ const fn = callback || function noop() {};$/;" function line:165 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:170 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:170 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Custom',$/;" string line:171 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Custom',$/;" variable line:171 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: options.exec,$/;" variable line:172 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" array line:173 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" variable line:173 -return /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ return;$/;" variable line:180 -image /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ image = options.image;$/;" variable line:186 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let flag;$/;" variable line:189 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = ext === 'icns' && 'iconpath';$/;" variable line:191 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (\/^[A-Z]\/.test(image) && 'appIcon');$/;" variable line:192 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (\/^png|gif|jpe?g$\/.test(ext) && 'image');$/;" variable line:193 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (ext && (image = ext) && 'icon');$/;" variable line:194 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || 'icon';$/;" variable line:195 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:197 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:201 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:206 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:209 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:211 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:246 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:264 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:273 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:282 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:287 -command /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let command = customCmd.replace(\/(^|[^%])%s\/g, `$1${message}`);$/;" variable line:293 -command /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ command = splitCmd.shift();$/;" variable line:296 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:303 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:306 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stdout = '';$/;" string line:311 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stdout = '';$/;" variable line:311 -stderr /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stderr = '';$/;" string line:312 -stderr /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stderr = '';$/;" variable line:312 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let error;$/;" variable line:313 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ error = err;$/;" variable line:317 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ error = error || code === 0 ? null : code;$/;" variable line:329 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ fn(error, stdout, stderr);$/;" variable line:331 -exports /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^module.exports = growl;$/;" variable line:341 diff --git a/node_modules/growl/.tags1 b/node_modules/growl/.tags1 deleted file mode 100644 index b68beb3..0000000 --- a/node_modules/growl/.tags1 +++ /dev/null @@ -1,166 +0,0 @@ -!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ -!_TAG_FILE_SORTED 0 /0=unsorted, 1=sorted, 2=foldcase/ -!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ -!_TAG_PROGRAM_NAME Exuberant Ctags // -!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ -!_TAG_PROGRAM_VERSION 5.8 // -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^let cmd;$/;" variable line:15 -which /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function which(name) {$/;" function line:17 -loc /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let loc;$/;" variable line:19 -len /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ for (let i = 0, len = paths.length; i < len; i += 1) {$/;" variable line:21 -loc /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ loc = path.join(paths[i], name);$/;" variable line:22 -setupCmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function setupCmd() {$/;" function line:28 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:32 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:32 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-NotificationCenter',$/;" string line:33 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-NotificationCenter',$/;" variable line:33 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'terminal-notifier',$/;" string line:34 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'terminal-notifier',$/;" variable line:34 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-message',$/;" string line:35 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-message',$/;" variable line:35 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" string line:36 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" variable line:36 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" string line:37 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" variable line:37 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-appIcon',$/;" string line:38 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-appIcon',$/;" variable line:38 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sound: '-sound',$/;" string line:39 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sound: '-sound',$/;" variable line:39 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '-open',$/;" string line:40 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '-open',$/;" variable line:40 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:41 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:41 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-execute',$/;" string line:42 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-execute',$/;" variable line:42 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" array line:43 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" variable line:43 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:47 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:47 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-Growl',$/;" string line:48 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Darwin-Growl',$/;" variable line:48 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" string line:49 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" variable line:49 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" string line:50 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" variable line:50 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '--sticky',$/;" string line:51 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '--sticky',$/;" variable line:51 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '--url',$/;" string line:52 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '--url',$/;" variable line:52 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:53 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:53 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '--priority',$/;" string line:54 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '--priority',$/;" variable line:54 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:55 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:55 -0 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 0,$/;" variable line:58 -1 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 1,$/;" variable line:59 -2 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 2,$/;" variable line:60 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:70 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:73 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:73 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux-Growl',$/;" string line:74 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux-Growl',$/;" variable line:74 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growl',$/;" string line:75 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growl',$/;" variable line:75 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" string line:76 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '-m',$/;" variable line:76 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" string line:77 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '-title',$/;" variable line:77 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" string line:78 -subtitle /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ subtitle: '-subtitle',$/;" variable line:78 -host /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ host: {$/;" object line:79 -host /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ host: {$/;" variable line:79 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-H',$/;" string line:80 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-H',$/;" variable line:80 -hostname /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ hostname: '192.168.33.1',$/;" string line:81 -hostname /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ hostname: '192.168.33.1',$/;" variable line:81 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:85 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:85 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux',$/;" string line:86 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Linux',$/;" variable line:86 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'notify-send',$/;" string line:87 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'notify-send',$/;" variable line:87 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" string line:88 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" variable line:88 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '-t 0',$/;" string line:89 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '-t 0',$/;" variable line:89 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-i',$/;" string line:90 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '-i',$/;" variable line:90 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:91 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:91 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-u',$/;" string line:92 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '-u',$/;" variable line:92 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:93 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:93 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:101 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:103 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:103 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Windows',$/;" string line:104 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Windows',$/;" variable line:104 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" string line:105 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: 'growlnotify',$/;" variable line:105 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" string line:106 -msg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ msg: '',$/;" variable line:106 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '\/s:true',$/;" string line:107 -sticky /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ sticky: '\/s:true',$/;" variable line:107 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '\/t:',$/;" string line:108 -title /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ title: '\/t:',$/;" variable line:108 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '\/i:',$/;" string line:109 -icon /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ icon: '\/i:',$/;" variable line:109 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '\/cu:',$/;" string line:110 -url /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ url: '\/cu:',$/;" variable line:110 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" object line:111 -priority /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ priority: {$/;" variable line:111 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '\/p:',$/;" string line:112 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd: '\/p:',$/;" variable line:112 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" array line:113 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [$/;" variable line:113 -0 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 0,$/;" variable line:116 -1 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 1,$/;" variable line:117 -2 /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ 2,$/;" variable line:118 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:122 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:124 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;" string line:151 -sound /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })$/;" variable line:151 -opts /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function growl(msg, opts, callback) {$/;" variable line:162 -growl /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^function growl(msg, opts, callback) {$/;" function line:162 -image /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let image;$/;" variable line:163 -noop /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ const fn = callback || function noop() {};$/;" function line:165 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" object line:170 -cmd /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ cmd = {$/;" variable line:170 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Custom',$/;" string line:171 -type /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ type: 'Custom',$/;" variable line:171 -pkg /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ pkg: options.exec,$/;" variable line:172 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" array line:173 -range /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ range: [],$/;" variable line:173 -return /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ return;$/;" variable line:180 -image /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ image = options.image;$/;" variable line:186 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let flag;$/;" variable line:189 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = ext === 'icns' && 'iconpath';$/;" variable line:191 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (\/^[A-Z]\/.test(image) && 'appIcon');$/;" variable line:192 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (\/^png|gif|jpe?g$\/.test(ext) && 'image');$/;" variable line:193 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || (ext && (image = ext) && 'icon');$/;" variable line:194 -flag /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ flag = flag || 'icon';$/;" variable line:195 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:197 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:201 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:206 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:209 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:211 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:246 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:264 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:273 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:282 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:287 -command /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let command = customCmd.replace(\/(^|[^%])%s\/g, `$1${message}`);$/;" variable line:293 -command /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ command = splitCmd.shift();$/;" variable line:296 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:303 -break /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ break;$/;" variable line:306 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stdout = '';$/;" string line:311 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stdout = '';$/;" variable line:311 -stderr /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stderr = '';$/;" string line:312 -stderr /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let stderr = '';$/;" variable line:312 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ let error;$/;" variable line:313 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ error = err;$/;" variable line:317 -error /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ error = error || code === 0 ? null : code;$/;" variable line:329 -stdout /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^ fn(error, stdout, stderr);$/;" variable line:331 -exports /Users/timosand/Dropbox/Documents/Projects/node-growl/lib/growl.js /^module.exports = growl;$/;" variable line:341 diff --git a/node_modules/growl/.travis.yml b/node_modules/growl/.travis.yml deleted file mode 100644 index 072adfc..0000000 --- a/node_modules/growl/.travis.yml +++ /dev/null @@ -1,21 +0,0 @@ -language: node_js -dist: trusty -os: - - linux - - osx -node_js: -- '4' -- '5' -- '6' -- '7' -- 'node' -before_install: - - npm i -g npm@latest - - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get -qq update; fi - - if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then sudo apt-get install -y libnotify-bin; fi -jobs: - include: - - stage: lint - script: npm run lint - - stage: test - script: npm test diff --git a/node_modules/growl/History.md b/node_modules/growl/History.md deleted file mode 100644 index dfbc2e4..0000000 --- a/node_modules/growl/History.md +++ /dev/null @@ -1,77 +0,0 @@ -1.10.5 / 2018-04-04 -================== - -* Fix callbacks not receiving errors (#72) [chadrickman] - -1.10.4 / 2018-01-29 -================== - -* Fix notifications on linux when using notify-send (#70) [hmshwt] - -1.9.3 / 2016-09-05 -================== - - * fixed command injection vulnerability - -1.7.0 / 2012-12-30 -================== - - * support transient notifications in Gnome - -1.6.1 / 2012-09-25 -================== - - * restore compatibility with node < 0.8 [fgnass] - -1.6.0 / 2012-09-06 -================== - - * add notification center support [drudge] - -1.5.1 / 2012-04-08 -================== - - * Merge pull request #16 from KyleAMathews/patch-1 - * Fixes #15 - -1.5.0 / 2012-02-08 -================== - - * Added windows support [perfusorius] - -1.4.1 / 2011-12-28 -================== - - * Fixed: dont exit(). Closes #9 - -1.4.0 / 2011-12-17 -================== - - * Changed API: `growl.notify()` -> `growl()` - -1.3.0 / 2011-12-17 -================== - - * Added support for Ubuntu/Debian/Linux users [niftylettuce] - * Fixed: send notifications even if title not specified [alessioalex] - -1.2.0 / 2011-10-06 -================== - - * Add support for priority. - -1.1.0 / 2011-03-15 -================== - - * Added optional callbacks - * Added parsing of version - -1.0.1 / 2010-03-26 -================== - - * Fixed; sys.exec -> child_process.exec to support latest node - -1.0.0 / 2010-03-19 -================== - - * Initial release diff --git a/node_modules/growl/Readme.md b/node_modules/growl/Readme.md deleted file mode 100644 index 54128b4..0000000 --- a/node_modules/growl/Readme.md +++ /dev/null @@ -1,109 +0,0 @@ -# Growl for nodejs -[![Build Status](https://travis-ci.org/tj/node-growl.svg?branch=master)](https://travis-ci.org/tj/node-growl) - -Growl support for Nodejs. This is essentially a port of my [Ruby Growl Library](http://github.com/visionmedia/growl). Ubuntu/Linux support added thanks to [@niftylettuce](http://github.com/niftylettuce). - -## Installation - -### Install - -### Mac OS X (Darwin): - - Install [growlnotify(1)](http://growl.info/extras.php#growlnotify). On OS X 10.8, Notification Center is supported using [terminal-notifier](https://github.com/alloy/terminal-notifier). To install: - - $ sudo gem install terminal-notifier - - Install [npm](http://npmjs.org/) and run: - - $ npm install growl - -### Ubuntu (Linux): - - Install `notify-send` through the [libnotify-bin](http://packages.ubuntu.com/libnotify-bin) package: - - $ sudo apt-get install libnotify-bin - - Install [npm](http://npmjs.org/) and run: - - $ npm install growl - -### Windows: - - Download and install [Growl for Windows](http://www.growlforwindows.com/gfw/default.aspx) - - Download [growlnotify](http://www.growlforwindows.com/gfw/help/growlnotify.aspx) - **IMPORTANT :** Unpack growlnotify to a folder that is present in your path! - - Install [npm](http://npmjs.org/) and run: - - $ npm install growl - -## Examples - -Callback functions are optional - -```javascript -var growl = require('growl') -growl('You have mail!') -growl('5 new messages', { sticky: true }) -growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true }) -growl('Message with title', { title: 'Title'}) -growl('Set priority', { priority: 2 }) -growl('Show Safari icon', { image: 'Safari' }) -growl('Show icon', { image: 'path/to/icon.icns' }) -growl('Show image', { image: 'path/to/my.image.png' }) -growl('Show png filesystem icon', { image: 'png' }) -growl('Show pdf filesystem icon', { image: 'article.pdf' }) -growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(err){ - // ... notified -}) -``` - -## Options - - - title - - notification title - - name - - application name - - priority - - priority for the notification (default is 0) - - sticky - - weither or not the notification should remainin until closed - - image - - Auto-detects the context: - - path to an icon sets --iconpath - - path to an image sets --image - - capitalized word sets --appIcon - - filename uses extname as --icon - - otherwise treated as --icon - - exec - - manually specify a shell command instead - - appends message to end of shell command - - or, replaces `%s` with message - - optionally prepends title (example: `title: message`) - - examples: `{exec: 'tmux display-message'}`, `{exec: 'echo "%s" > messages.log}` - -## License - -(The MIT License) - -Copyright (c) 2009 TJ Holowaychuk -Copyright (c) 2016 Joshua Boy Nicolai Appelman - -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. diff --git a/node_modules/growl/lib/growl.js b/node_modules/growl/lib/growl.js deleted file mode 100644 index eb4efa8..0000000 --- a/node_modules/growl/lib/growl.js +++ /dev/null @@ -1,340 +0,0 @@ -'use strict'; - -// Growl - Copyright TJ Holowaychuk (MIT Licensed) - -/** - * Module dependencies. - */ - -const spawn = require('child_process').spawn; -const fs = require('fs'); -const path = require('path'); -const os = require('os'); - -const exists = fs.existsSync || path.existsSync; -let cmd; - -function which(name) { - const paths = process.env.PATH.split(':'); - let loc; - - for (let i = 0, len = paths.length; i < len; i += 1) { - loc = path.join(paths[i], name); - if (exists(loc)) return loc; - } - return false; -} - -function setupCmd() { - switch (os.type()) { - case 'Darwin': - if (which('terminal-notifier')) { - cmd = { - type: 'Darwin-NotificationCenter', - pkg: 'terminal-notifier', - msg: '-message', - title: '-title', - subtitle: '-subtitle', - icon: '-appIcon', - sound: '-sound', - url: '-open', - priority: { - cmd: '-execute', - range: [], - }, - }; - } else { - cmd = { - type: 'Darwin-Growl', - pkg: 'growlnotify', - msg: '-m', - sticky: '--sticky', - url: '--url', - priority: { - cmd: '--priority', - range: [ - -2, - -1, - 0, - 1, - 2, - 'Very Low', - 'Moderate', - 'Normal', - 'High', - 'Emergency', - ], - }, - }; - } - break; - case 'Linux': - if (which('growl')) { - cmd = { - type: 'Linux-Growl', - pkg: 'growl', - msg: '-m', - title: '-title', - subtitle: '-subtitle', - host: { - cmd: '-H', - hostname: '192.168.33.1', - }, - }; - } else { - cmd = { - type: 'Linux', - pkg: 'notify-send', - msg: '', - sticky: '-t', - icon: '-i', - priority: { - cmd: '-u', - range: [ - 'low', - 'normal', - 'critical', - ], - }, - }; - } - break; - case 'Windows_NT': - cmd = { - type: 'Windows', - pkg: 'growlnotify', - msg: '', - sticky: '/s:true', - title: '/t:', - icon: '/i:', - url: '/cu:', - priority: { - cmd: '/p:', - range: [ - -2, - -1, - 0, - 1, - 2, - ], - }, - }; - break; - default: - break; - } -} - - -/** - * Send growl notification _msg_ with _options_. - * - * Options: - * - * - title Notification title - * - sticky Make the notification stick (defaults to false) - * - priority Specify an int or named key (default is 0) - * - name Application name (defaults to growlnotify) - * - sound Sound efect ( in OSx defined in preferences -> sound -> effects) - * works only in OSX > 10.8x - * - image - * - path to an icon sets --iconpath - * - path to an image sets --image - * - capitalized word sets --appIcon - * - filename uses extname as --icon - * - otherwise treated as --icon - * - * Examples: - * - * growl('New email') - * growl('5 new emails', { title: 'Thunderbird' }) - * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' }) - * growl('Email sent', function(){ - * // ... notification sent - * }) - * - * @param {string} msg - * @param {object} opts - * @param {function} callback - * @api public - */ - -function growl(msg, opts, callback) { - let image; - const options = opts || {}; - const fn = callback || function noop() {}; - - setupCmd(); - - if (options.exec) { - cmd = { - type: 'Custom', - pkg: options.exec, - range: [], - }; - } - - // noop - if (!cmd) { - fn(new Error('growl not supported on this platform')); - return; - } - const args = [cmd.pkg]; - - // image - if (image || options.image) { - image = options.image; - switch (cmd.type) { - case 'Darwin-Growl': { - let flag; - const ext = path.extname(image).substr(1); - flag = ext === 'icns' && 'iconpath'; - flag = flag || (/^[A-Z]/.test(image) && 'appIcon'); - flag = flag || (/^png|gif|jpe?g$/.test(ext) && 'image'); - flag = flag || (ext && (image = ext) && 'icon'); - flag = flag || 'icon'; - args.push(`--${flag}`, image); - break; - } - case 'Darwin-NotificationCenter': - args.push(cmd.icon, image); - break; - case 'Linux': - args.push(cmd.icon, image); - // libnotify defaults to sticky, set a hint for transient notifications - if (!options.sticky) args.push('--hint=int:transient:1'); - break; - case 'Windows': - args.push(cmd.icon + image); - break; - default: - break; - } - } - - // sticky - if (options.sticky) args.push(cmd.sticky); - if (options.sticky && cmd.type === 'Linux') args.push('0'); - - // priority - if (options.priority) { - const priority = `${options.priority}`; - const checkindexOf = cmd.priority.range.indexOf(priority); - if (checkindexOf > -1) { - args.push(cmd.priority, options.priority); - } - } - - // sound - if (options.sound && cmd.type === 'Darwin-NotificationCenter') { - args.push(cmd.sound, options.sound); - } - - // name - if (options.name && cmd.type === 'Darwin-Growl') { - args.push('--name', options.name); - } - - switch (cmd.type) { - case 'Darwin-Growl': - args.push(cmd.msg); - args.push(msg.replace(/\\n/g, '\n')); - if (options.title) args.push(options.title); - if (options.url) { - args.push(cmd.url); - args.push(options.url); - } - break; - case 'Darwin-NotificationCenter': { - args.push(cmd.msg); - const stringifiedMsg = msg; - const escapedMsg = stringifiedMsg.replace(/\\n/g, '\n'); - args.push(escapedMsg); - if (options.title) { - args.push(cmd.title); - args.push(options.title); - } - if (options.subtitle) { - args.push(cmd.subtitle); - args.push(options.subtitle); - } - if (options.url) { - args.push(cmd.url); - args.push(options.url); - } - break; - } - case 'Linux-Growl': - args.push(cmd.msg); - args.push(msg.replace(/\\n/g, '\n')); - if (options.title) args.push(options.title); - if (cmd.host) { - args.push(cmd.host.cmd, cmd.host.hostname); - } - break; - case 'Linux': - if (options.title) args.push(options.title); - args.push(msg.replace(/\\n/g, '\n')); - break; - case 'Windows': - args.push(msg.replace(/\\n/g, '\n')); - if (options.title) args.push(cmd.title + options.title); - if (options.url) args.push(cmd.url + options.url); - break; - case 'Custom': { - const customCmd = args[0]; - const message = options.title - ? `${options.title}: ${msg}` - : msg; - let command = customCmd.replace(/(^|[^%])%s/g, `$1${message}`); - const splitCmd = command.split(' '); - if (splitCmd.length > 1) { - command = splitCmd.shift(); - Array.prototype.push.apply(args, splitCmd); - } - if (customCmd.indexOf('%s') < 0) { - args.push(message); - } - args[0] = command; - break; - } - default: - break; - } - const cmdToExec = args.shift(); - - const child = spawn(cmdToExec, args); - let stdout = ''; - let stderr = ''; - let error; - - const now = new Date(); - const timestamp = `${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}.${now.getMilliseconds()}` - - stderr += `[${timestamp}][node-growl] : Executed command '${cmdToExec}' with arguments '${args}'\n[stderr] : `; - - child.on('error', (err) => { - console.error('An error occured.', err); - error = err; - }); - - child.stdout.on('data', (data) => { - stdout += data; - }); - - child.stderr.on('data', (data) => { - stderr += data; - }); - - child.on('close', () => { - if (typeof fn === 'function') { - fn(error, stdout, stderr); - } - }); -} - -/** - * Expose `growl`. - */ - -module.exports = growl; diff --git a/node_modules/growl/package.json b/node_modules/growl/package.json deleted file mode 100644 index 377a0c3..0000000 --- a/node_modules/growl/package.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "name": "growl", - "version": "1.10.5", - "description": "Growl unobtrusive notifications", - "author": "TJ Holowaychuk ", - "maintainers": [ - "Joshua Boy Nicolai Appelman ", - "Timo Sand " - ], - "repository": { - "type": "git", - "url": "git://github.com/tj/node-growl.git" - }, - "main": "./lib/growl.js", - "license": "MIT", - "devDependencies": { - "eslint": "^4.8.0", - "eslint-config-airbnb-base": "^12.0.1", - "eslint-plugin-import": "^2.7.0", - "eslint-plugin-node": "^5.2.0" - }, - "scripts": { - "test": "node test.js", - "lint": "eslint --ext js lib " - }, - "engines": { - "node": ">=4.x" - } -} diff --git a/node_modules/growl/test.js b/node_modules/growl/test.js deleted file mode 100644 index 3b1d229..0000000 --- a/node_modules/growl/test.js +++ /dev/null @@ -1,31 +0,0 @@ - -var growl = require('./lib/growl') - -growl('Support sound notifications', {title: 'Make a sound', sound: 'purr'}); -growl('You have mail!') -growl('5 new messages', { sticky: true }) -growl('5 new emails', { title: 'Email Client', image: 'Safari', sticky: true }) -growl('Message with title', { title: 'Title'}) -growl('Set priority', { priority: 2 }) -growl('Show Safari icon', { image: 'Safari' }) -growl('Show icon', { image: 'path/to/icon.icns' }) -growl('Show image', { image: 'path/to/my.image.png' }) -growl('Show png filesystem icon', { image: 'png' }) -growl('Show pdf filesystem icon', { image: 'article.pdf' }) -growl('Show pdf filesystem icon', { image: 'article.pdf' }, function(){ - console.log('callback'); -}) -growl('Show pdf filesystem icon', { title: 'Use show()', image: 'article.pdf' }) -growl('here \' are \n some \\ characters that " need escaping', {}, function(error, stdout, stderr) { - if (error) throw new Error('escaping failed:\n' + stdout + stderr); -}) -growl('Allow custom notifiers', { exec: 'echo XXX %s' }, function(error, stdout, stderr) { - console.log(stdout); -}) -growl('Allow custom notifiers', { title: 'test', exec: 'echo YYY' }, function(error, stdout, stderr) { - console.log(stdout); -}) -growl('Allow custom notifiers', { title: 'test', exec: 'echo ZZZ %s' }, function(error, stdout, stderr) { - console.log(stdout); -}) -growl('Open a URL', { url: 'https://npmjs.org/package/growl' }); diff --git a/node_modules/he/bin/he b/node_modules/he/bin/he old mode 100755 new mode 100644 diff --git a/node_modules/cliui/node_modules/is-fullwidth-code-point/index.d.ts b/node_modules/is-fullwidth-code-point/index.d.ts similarity index 100% rename from node_modules/cliui/node_modules/is-fullwidth-code-point/index.d.ts rename to node_modules/is-fullwidth-code-point/index.d.ts diff --git a/node_modules/is-fullwidth-code-point/index.js b/node_modules/is-fullwidth-code-point/index.js index d506327..671f97f 100644 --- a/node_modules/is-fullwidth-code-point/index.js +++ b/node_modules/is-fullwidth-code-point/index.js @@ -1,42 +1,43 @@ -'use strict'; /* eslint-disable yoda */ -module.exports = x => { - if (Number.isNaN(x)) { +'use strict'; + +const isFullwidthCodePoint = codePoint => { + if (Number.isNaN(codePoint)) { return false; } - // code points are derived from: + // Code points are derived from: // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt if ( - x >= 0x1100 && ( - x <= 0x115f || // Hangul Jamo - x === 0x2329 || // LEFT-POINTING ANGLE BRACKET - x === 0x232a || // RIGHT-POINTING ANGLE BRACKET + codePoint >= 0x1100 && ( + codePoint <= 0x115F || // Hangul Jamo + codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET + codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2e80 <= x && x <= 0x3247 && x !== 0x303f) || + (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= x && x <= 0x4dbf) || + (0x3250 <= codePoint && codePoint <= 0x4DBF) || // CJK Unified Ideographs .. Yi Radicals - (0x4e00 <= x && x <= 0xa4c6) || + (0x4E00 <= codePoint && codePoint <= 0xA4C6) || // Hangul Jamo Extended-A - (0xa960 <= x && x <= 0xa97c) || + (0xA960 <= codePoint && codePoint <= 0xA97C) || // Hangul Syllables - (0xac00 <= x && x <= 0xd7a3) || + (0xAC00 <= codePoint && codePoint <= 0xD7A3) || // CJK Compatibility Ideographs - (0xf900 <= x && x <= 0xfaff) || + (0xF900 <= codePoint && codePoint <= 0xFAFF) || // Vertical Forms - (0xfe10 <= x && x <= 0xfe19) || + (0xFE10 <= codePoint && codePoint <= 0xFE19) || // CJK Compatibility Forms .. Small Form Variants - (0xfe30 <= x && x <= 0xfe6b) || + (0xFE30 <= codePoint && codePoint <= 0xFE6B) || // Halfwidth and Fullwidth Forms - (0xff01 <= x && x <= 0xff60) || - (0xffe0 <= x && x <= 0xffe6) || + (0xFF01 <= codePoint && codePoint <= 0xFF60) || + (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || // Kana Supplement - (0x1b000 <= x && x <= 0x1b001) || + (0x1B000 <= codePoint && codePoint <= 0x1B001) || // Enclosed Ideographic Supplement - (0x1f200 <= x && x <= 0x1f251) || + (0x1F200 <= codePoint && codePoint <= 0x1F251) || // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= x && x <= 0x3fffd) + (0x20000 <= codePoint && codePoint <= 0x3FFFD) ) ) { return true; @@ -44,3 +45,6 @@ module.exports = x => { return false; }; + +module.exports = isFullwidthCodePoint; +module.exports.default = isFullwidthCodePoint; diff --git a/node_modules/is-fullwidth-code-point/license b/node_modules/is-fullwidth-code-point/license index 654d0bf..e7af2f7 100644 --- a/node_modules/is-fullwidth-code-point/license +++ b/node_modules/is-fullwidth-code-point/license @@ -1,21 +1,9 @@ -The MIT License (MIT) +MIT License Copyright (c) Sindre Sorhus (sindresorhus.com) -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: +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 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. +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. diff --git a/node_modules/is-fullwidth-code-point/package.json b/node_modules/is-fullwidth-code-point/package.json index 3049d9e..2137e88 100644 --- a/node_modules/is-fullwidth-code-point/package.json +++ b/node_modules/is-fullwidth-code-point/package.json @@ -1,45 +1,42 @@ { - "name": "is-fullwidth-code-point", - "version": "2.0.0", - "description": "Check if the character represented by a given Unicode code point is fullwidth", - "license": "MIT", - "repository": "sindresorhus/is-fullwidth-code-point", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "fullwidth", - "full-width", - "full", - "width", - "unicode", - "character", - "char", - "string", - "str", - "codepoint", - "code", - "point", - "is", - "detect", - "check" - ], - "devDependencies": { - "ava": "*", - "xo": "*" - }, - "xo": { - "esnext": true - } + "name": "is-fullwidth-code-point", + "version": "3.0.0", + "description": "Check if the character represented by a given Unicode code point is fullwidth", + "license": "MIT", + "repository": "sindresorhus/is-fullwidth-code-point", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd-check" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "fullwidth", + "full-width", + "full", + "width", + "unicode", + "character", + "string", + "codepoint", + "code", + "point", + "is", + "detect", + "check" + ], + "devDependencies": { + "ava": "^1.3.1", + "tsd-check": "^0.5.0", + "xo": "^0.24.0" + } } diff --git a/node_modules/is-fullwidth-code-point/readme.md b/node_modules/is-fullwidth-code-point/readme.md index 093b028..4236bba 100644 --- a/node_modules/is-fullwidth-code-point/readme.md +++ b/node_modules/is-fullwidth-code-point/readme.md @@ -6,7 +6,7 @@ ## Install ``` -$ npm install --save is-fullwidth-code-point +$ npm install is-fullwidth-code-point ``` @@ -15,23 +15,23 @@ $ npm install --save is-fullwidth-code-point ```js const isFullwidthCodePoint = require('is-fullwidth-code-point'); -isFullwidthCodePoint('谢'.codePointAt()); +isFullwidthCodePoint('谢'.codePointAt(0)); //=> true -isFullwidthCodePoint('a'.codePointAt()); +isFullwidthCodePoint('a'.codePointAt(0)); //=> false ``` ## API -### isFullwidthCodePoint(input) +### isFullwidthCodePoint(codePoint) -#### input +#### codePoint Type: `number` -[Code point](https://en.wikipedia.org/wiki/Code_point) of a character. +The [code point](https://en.wikipedia.org/wiki/Code_point) of a character. ## License diff --git a/node_modules/is-unicode-supported/index.d.ts b/node_modules/is-unicode-supported/index.d.ts new file mode 100644 index 0000000..275b37b --- /dev/null +++ b/node_modules/is-unicode-supported/index.d.ts @@ -0,0 +1,14 @@ +/** +Detect whether the terminal supports Unicode. + +@example +``` +import isUnicodeSupported = require('is-unicode-supported'); + +isUnicodeSupported(); +//=> true +``` +*/ +declare function isUnicodeSupported(): boolean; + +export = isUnicodeSupported; diff --git a/node_modules/is-unicode-supported/index.js b/node_modules/is-unicode-supported/index.js new file mode 100644 index 0000000..b5a11be --- /dev/null +++ b/node_modules/is-unicode-supported/index.js @@ -0,0 +1,13 @@ +'use strict'; + +module.exports = () => { + if (process.platform !== 'win32') { + return true; + } + + return Boolean(process.env.CI) || + Boolean(process.env.WT_SESSION) || // Windows Terminal + process.env.TERM_PROGRAM === 'vscode' || + process.env.TERM === 'xterm-256color' || + process.env.TERM === 'alacritty'; +}; diff --git a/node_modules/cliui/node_modules/is-fullwidth-code-point/license b/node_modules/is-unicode-supported/license similarity index 92% rename from node_modules/cliui/node_modules/is-fullwidth-code-point/license rename to node_modules/is-unicode-supported/license index e7af2f7..fa7ceba 100644 --- a/node_modules/cliui/node_modules/is-fullwidth-code-point/license +++ b/node_modules/is-unicode-supported/license @@ -1,6 +1,6 @@ MIT License -Copyright (c) Sindre Sorhus (sindresorhus.com) +Copyright (c) Sindre Sorhus (https://sindresorhus.com) 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: diff --git a/node_modules/is-unicode-supported/package.json b/node_modules/is-unicode-supported/package.json new file mode 100644 index 0000000..17e4035 --- /dev/null +++ b/node_modules/is-unicode-supported/package.json @@ -0,0 +1,41 @@ +{ + "name": "is-unicode-supported", + "version": "0.1.0", + "description": "Detect whether the terminal supports Unicode", + "license": "MIT", + "repository": "sindresorhus/is-unicode-supported", + "funding": "https://github.com/sponsors/sindresorhus", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "terminal", + "unicode", + "detect", + "utf8", + "console", + "shell", + "support", + "supports", + "supported", + "check", + "detection" + ], + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.14.0", + "xo": "^0.38.2" + } +} diff --git a/node_modules/is-unicode-supported/readme.md b/node_modules/is-unicode-supported/readme.md new file mode 100644 index 0000000..a82e34d --- /dev/null +++ b/node_modules/is-unicode-supported/readme.md @@ -0,0 +1,35 @@ +# is-unicode-supported + +> Detect whether the terminal supports Unicode + +This can be useful to decide whether to use Unicode characters or fallback ASCII characters in command-line output. + +Note that the check is quite naive. It just assumes all non-Windows terminals support Unicode and hard-codes which Windows terminals that do support Unicode. However, I have been using this logic in some popular packages for years without problems. + +## Install + +``` +$ npm install is-unicode-supported +``` + +## Usage + +```js +const isUnicodeSupported = require('is-unicode-supported'); + +isUnicodeSupported(); +//=> true +``` + +## API + +### isUnicodeSupported() + +Returns a `boolean` for whether the terminal supports Unicode. + +## Related + +- [is-interactive](https://github.com/sindresorhus/is-interactive) - Check if stdout or stderr is interactive +- [supports-color](https://github.com/chalk/supports-color) - Detect whether a terminal supports color +- [figures](https://github.com/sindresorhus/figures) - Unicode symbols with Windows fallbacks +- [log-symbols](https://github.com/sindresorhus/log-symbols) - Colored symbols for various log levels diff --git a/node_modules/isexe/.npmignore b/node_modules/isexe/.npmignore deleted file mode 100644 index c1cb757..0000000 --- a/node_modules/isexe/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -.nyc_output/ -coverage/ diff --git a/node_modules/isexe/README.md b/node_modules/isexe/README.md deleted file mode 100644 index 35769e8..0000000 --- a/node_modules/isexe/README.md +++ /dev/null @@ -1,51 +0,0 @@ -# isexe - -Minimal module to check if a file is executable, and a normal file. - -Uses `fs.stat` and tests against the `PATHEXT` environment variable on -Windows. - -## USAGE - -```javascript -var isexe = require('isexe') -isexe('some-file-name', function (err, isExe) { - if (err) { - console.error('probably file does not exist or something', err) - } else if (isExe) { - console.error('this thing can be run') - } else { - console.error('cannot be run') - } -}) - -// same thing but synchronous, throws errors -var isExe = isexe.sync('some-file-name') - -// treat errors as just "not executable" -isexe('maybe-missing-file', { ignoreErrors: true }, callback) -var isExe = isexe.sync('maybe-missing-file', { ignoreErrors: true }) -``` - -## API - -### `isexe(path, [options], [callback])` - -Check if the path is executable. If no callback provided, and a -global `Promise` object is available, then a Promise will be returned. - -Will raise whatever errors may be raised by `fs.stat`, unless -`options.ignoreErrors` is set to true. - -### `isexe.sync(path, [options])` - -Same as `isexe` but returns the value and throws any errors raised. - -### Options - -* `ignoreErrors` Treat all errors as "no, this is not executable", but - don't raise them. -* `uid` Number to use as the user id -* `gid` Number to use as the group id -* `pathExt` List of path extensions to use instead of `PATHEXT` - environment variable on Windows. diff --git a/node_modules/isexe/index.js b/node_modules/isexe/index.js deleted file mode 100644 index 553fb32..0000000 --- a/node_modules/isexe/index.js +++ /dev/null @@ -1,57 +0,0 @@ -var fs = require('fs') -var core -if (process.platform === 'win32' || global.TESTING_WINDOWS) { - core = require('./windows.js') -} else { - core = require('./mode.js') -} - -module.exports = isexe -isexe.sync = sync - -function isexe (path, options, cb) { - if (typeof options === 'function') { - cb = options - options = {} - } - - if (!cb) { - if (typeof Promise !== 'function') { - throw new TypeError('callback not provided') - } - - return new Promise(function (resolve, reject) { - isexe(path, options || {}, function (er, is) { - if (er) { - reject(er) - } else { - resolve(is) - } - }) - }) - } - - core(path, options || {}, function (er, is) { - // ignore EACCES because that just means we aren't allowed to run it - if (er) { - if (er.code === 'EACCES' || options && options.ignoreErrors) { - er = null - is = false - } - } - cb(er, is) - }) -} - -function sync (path, options) { - // my kingdom for a filtered catch - try { - return core.sync(path, options || {}) - } catch (er) { - if (options && options.ignoreErrors || er.code === 'EACCES') { - return false - } else { - throw er - } - } -} diff --git a/node_modules/isexe/mode.js b/node_modules/isexe/mode.js deleted file mode 100644 index 1995ea4..0000000 --- a/node_modules/isexe/mode.js +++ /dev/null @@ -1,41 +0,0 @@ -module.exports = isexe -isexe.sync = sync - -var fs = require('fs') - -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, options)) - }) -} - -function sync (path, options) { - return checkStat(fs.statSync(path), options) -} - -function checkStat (stat, options) { - return stat.isFile() && checkMode(stat, options) -} - -function checkMode (stat, options) { - var mod = stat.mode - var uid = stat.uid - var gid = stat.gid - - var myUid = options.uid !== undefined ? - options.uid : process.getuid && process.getuid() - var myGid = options.gid !== undefined ? - options.gid : process.getgid && process.getgid() - - var u = parseInt('100', 8) - var g = parseInt('010', 8) - var o = parseInt('001', 8) - var ug = u | g - - var ret = (mod & o) || - (mod & g) && gid === myGid || - (mod & u) && uid === myUid || - (mod & ug) && myUid === 0 - - return ret -} diff --git a/node_modules/isexe/package.json b/node_modules/isexe/package.json deleted file mode 100644 index e452689..0000000 --- a/node_modules/isexe/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "isexe", - "version": "2.0.0", - "description": "Minimal module to check if a file is executable.", - "main": "index.js", - "directories": { - "test": "test" - }, - "devDependencies": { - "mkdirp": "^0.5.1", - "rimraf": "^2.5.0", - "tap": "^10.3.0" - }, - "scripts": { - "test": "tap test/*.js --100", - "preversion": "npm test", - "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" - }, - "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "license": "ISC", - "repository": { - "type": "git", - "url": "git+https://github.com/isaacs/isexe.git" - }, - "keywords": [], - "bugs": { - "url": "https://github.com/isaacs/isexe/issues" - }, - "homepage": "https://github.com/isaacs/isexe#readme" -} diff --git a/node_modules/isexe/test/basic.js b/node_modules/isexe/test/basic.js deleted file mode 100644 index d926df6..0000000 --- a/node_modules/isexe/test/basic.js +++ /dev/null @@ -1,221 +0,0 @@ -var t = require('tap') -var fs = require('fs') -var path = require('path') -var fixture = path.resolve(__dirname, 'fixtures') -var meow = fixture + '/meow.cat' -var mine = fixture + '/mine.cat' -var ours = fixture + '/ours.cat' -var fail = fixture + '/fail.false' -var noent = fixture + '/enoent.exe' -var mkdirp = require('mkdirp') -var rimraf = require('rimraf') - -var isWindows = process.platform === 'win32' -var hasAccess = typeof fs.access === 'function' -var winSkip = isWindows && 'windows' -var accessSkip = !hasAccess && 'no fs.access function' -var hasPromise = typeof Promise === 'function' -var promiseSkip = !hasPromise && 'no global Promise' - -function reset () { - delete require.cache[require.resolve('../')] - return require('../') -} - -t.test('setup fixtures', function (t) { - rimraf.sync(fixture) - mkdirp.sync(fixture) - fs.writeFileSync(meow, '#!/usr/bin/env cat\nmeow\n') - fs.chmodSync(meow, parseInt('0755', 8)) - fs.writeFileSync(fail, '#!/usr/bin/env false\n') - fs.chmodSync(fail, parseInt('0644', 8)) - fs.writeFileSync(mine, '#!/usr/bin/env cat\nmine\n') - fs.chmodSync(mine, parseInt('0744', 8)) - fs.writeFileSync(ours, '#!/usr/bin/env cat\nours\n') - fs.chmodSync(ours, parseInt('0754', 8)) - t.end() -}) - -t.test('promise', { skip: promiseSkip }, function (t) { - var isexe = reset() - t.test('meow async', function (t) { - isexe(meow).then(function (is) { - t.ok(is) - t.end() - }) - }) - t.test('fail async', function (t) { - isexe(fail).then(function (is) { - t.notOk(is) - t.end() - }) - }) - t.test('noent async', function (t) { - isexe(noent).catch(function (er) { - t.ok(er) - t.end() - }) - }) - t.test('noent ignore async', function (t) { - isexe(noent, { ignoreErrors: true }).then(function (is) { - t.notOk(is) - t.end() - }) - }) - t.end() -}) - -t.test('no promise', function (t) { - global.Promise = null - var isexe = reset() - t.throws('try to meow a promise', function () { - isexe(meow) - }) - t.end() -}) - -t.test('access', { skip: accessSkip || winSkip }, function (t) { - runTest(t) -}) - -t.test('mode', { skip: winSkip }, function (t) { - delete fs.access - delete fs.accessSync - var isexe = reset() - t.ok(isexe.sync(ours, { uid: 0, gid: 0 })) - t.ok(isexe.sync(mine, { uid: 0, gid: 0 })) - runTest(t) -}) - -t.test('windows', function (t) { - global.TESTING_WINDOWS = true - var pathExt = '.EXE;.CAT;.CMD;.COM' - t.test('pathExt option', function (t) { - runTest(t, { pathExt: '.EXE;.CAT;.CMD;.COM' }) - }) - t.test('pathExt env', function (t) { - process.env.PATHEXT = pathExt - runTest(t) - }) - t.test('no pathExt', function (t) { - // with a pathExt of '', any filename is fine. - // so the "fail" one would still pass. - runTest(t, { pathExt: '', skipFail: true }) - }) - t.test('pathext with empty entry', function (t) { - // with a pathExt of '', any filename is fine. - // so the "fail" one would still pass. - runTest(t, { pathExt: ';' + pathExt, skipFail: true }) - }) - t.end() -}) - -t.test('cleanup', function (t) { - rimraf.sync(fixture) - t.end() -}) - -function runTest (t, options) { - var isexe = reset() - - var optionsIgnore = Object.create(options || {}) - optionsIgnore.ignoreErrors = true - - if (!options || !options.skipFail) { - t.notOk(isexe.sync(fail, options)) - } - t.notOk(isexe.sync(noent, optionsIgnore)) - if (!options) { - t.ok(isexe.sync(meow)) - } else { - t.ok(isexe.sync(meow, options)) - } - - t.ok(isexe.sync(mine, options)) - t.ok(isexe.sync(ours, options)) - t.throws(function () { - isexe.sync(noent, options) - }) - - t.test('meow async', function (t) { - if (!options) { - isexe(meow, function (er, is) { - if (er) { - throw er - } - t.ok(is) - t.end() - }) - } else { - isexe(meow, options, function (er, is) { - if (er) { - throw er - } - t.ok(is) - t.end() - }) - } - }) - - t.test('mine async', function (t) { - isexe(mine, options, function (er, is) { - if (er) { - throw er - } - t.ok(is) - t.end() - }) - }) - - t.test('ours async', function (t) { - isexe(ours, options, function (er, is) { - if (er) { - throw er - } - t.ok(is) - t.end() - }) - }) - - if (!options || !options.skipFail) { - t.test('fail async', function (t) { - isexe(fail, options, function (er, is) { - if (er) { - throw er - } - t.notOk(is) - t.end() - }) - }) - } - - t.test('noent async', function (t) { - isexe(noent, options, function (er, is) { - t.ok(er) - t.notOk(is) - t.end() - }) - }) - - t.test('noent ignore async', function (t) { - isexe(noent, optionsIgnore, function (er, is) { - if (er) { - throw er - } - t.notOk(is) - t.end() - }) - }) - - t.test('directory is not executable', function (t) { - isexe(__dirname, options, function (er, is) { - if (er) { - throw er - } - t.notOk(is) - t.end() - }) - }) - - t.end() -} diff --git a/node_modules/isexe/windows.js b/node_modules/isexe/windows.js deleted file mode 100644 index 3499673..0000000 --- a/node_modules/isexe/windows.js +++ /dev/null @@ -1,42 +0,0 @@ -module.exports = isexe -isexe.sync = sync - -var fs = require('fs') - -function checkPathExt (path, options) { - var pathext = options.pathExt !== undefined ? - options.pathExt : process.env.PATHEXT - - if (!pathext) { - return true - } - - pathext = pathext.split(';') - if (pathext.indexOf('') !== -1) { - return true - } - for (var i = 0; i < pathext.length; i++) { - var p = pathext[i].toLowerCase() - if (p && path.substr(-p.length).toLowerCase() === p) { - return true - } - } - return false -} - -function checkStat (stat, path, options) { - if (!stat.isSymbolicLink() && !stat.isFile()) { - return false - } - return checkPathExt(path, options) -} - -function isexe (path, options, cb) { - fs.stat(path, function (er, stat) { - cb(er, er ? false : checkStat(stat, path, options)) - }) -} - -function sync (path, options) { - return checkStat(fs.statSync(path), path, options) -} diff --git a/node_modules/jake/bin/bash_completion.sh b/node_modules/jake/bin/bash_completion.sh old mode 100755 new mode 100644 diff --git a/node_modules/jake/bin/cli.js b/node_modules/jake/bin/cli.js old mode 100755 new mode 100644 diff --git a/node_modules/jake/jakefile.js b/node_modules/jake/jakefile.js index 8bcd75c..5a5a55e 100644 --- a/node_modules/jake/jakefile.js +++ b/node_modules/jake/jakefile.js @@ -1,5 +1,3 @@ -let fs = require('fs') -let path = require('path'); let proc = require('child_process'); const PROJECT_DIR = process.cwd(); @@ -92,3 +90,23 @@ namespace('test', function () { desc('Runs all tests'); task('test', ['test:unit', 'test:integration', 'test:integrationClobber']); + +desc('Runs eslint for both lib and test directories'); +task('lint', function (doFix) { + + let cmd = 'eslint --format codeframe "lib/**/*.js" "test/**/*.js"'; + if (doFix) { + cmd += ' --fix'; + } + try { + proc.execSync(cmd); + } + catch (err) { + console.log(err.message); + console.log(err.stderr.toString()); + console.log(err.stdout.toString()); + fail('eslint failed'); + } +}); + + diff --git a/node_modules/jake/lib/jake.js b/node_modules/jake/lib/jake.js index 0bd439a..ec246ad 100644 --- a/node_modules/jake/lib/jake.js +++ b/node_modules/jake/lib/jake.js @@ -215,7 +215,7 @@ if (!global.jake) { switch (type) { case 'directory': - action = function () { + action = function action() { jake.mkdirP(name); }; task = new DirectoryTask(name, prereqs, action, opts); diff --git a/node_modules/jake/lib/parseargs.js b/node_modules/jake/lib/parseargs.js index 1bd24c9..1a00733 100644 --- a/node_modules/jake/lib/parseargs.js +++ b/node_modules/jake/lib/parseargs.js @@ -17,8 +17,8 @@ */ let parseargs = {}; -let isOpt = function (arg) { return arg.indexOf('-') === 0 }; -let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, '') }; +let isOpt = function (arg) { return arg.indexOf('-') === 0; }; +let removeOptPrefix = function (opt) { return opt.replace(/^--/, '').replace(/^-/, ''); }; /** * @constructor diff --git a/node_modules/jake/lib/task/file_task.js b/node_modules/jake/lib/task/file_task.js index 6fad84b..d23aba8 100644 --- a/node_modules/jake/lib/task/file_task.js +++ b/node_modules/jake/lib/task/file_task.js @@ -91,6 +91,8 @@ class FileTask extends Task { } } } + this.taskStatus = Task.runStatuses.DONE; + return false; } // File/dir has no prereqs, and exists -- no need to run else { diff --git a/node_modules/jake/lib/task/task.js b/node_modules/jake/lib/task/task.js index c433982..c9992bc 100644 --- a/node_modules/jake/lib/task/task.js +++ b/node_modules/jake/lib/task/task.js @@ -122,7 +122,7 @@ class Task extends EventEmitter { this._initInvocationChain(); this.args = Array.prototype.slice.call(arguments); - this.reenabled = false + this.reenabled = false; this.runPrereqs(); } @@ -137,7 +137,7 @@ class Task extends EventEmitter { this.args = Array.prototype.slice.call(arguments); this.reenable(); - this.reenabled = true + this.reenabled = true; this.run(); } @@ -420,7 +420,7 @@ class Task extends EventEmitter { _getParams() { if (!this.action) return ""; - let params = new RegExp('(?:'+this.action.name+'\\s*|^)\\s*\\((.*?)\\)').exec(this.action.toString().replace(/\n/g, ''))[1].replace(/\/\*.*?\*\//g, '').replace(/ /g, ''); + let params = (new RegExp('(?:'+this.action.name+'\\s*|^)\\s*\\((.*?)\\)').exec(this.action.toString().replace(/\n/g, '')) || [''])[1].replace(/\/\*.*?\*\//g, '').replace(/ /g, ''); return params; } diff --git a/node_modules/jake/lib/utils/file.js b/node_modules/jake/lib/utils/file.js index a436def..d7163f3 100644 --- a/node_modules/jake/lib/utils/file.js +++ b/node_modules/jake/lib/utils/file.js @@ -28,9 +28,9 @@ let fileUtils = new (function () { // Recursively copy files and directories let _copyFile = function (fromPath, toPath, opts) { - let from = path.normalize(fromPath) - let to = path.normalize(toPath) - let options = opts || {} + let from = path.normalize(fromPath); + let to = path.normalize(toPath); + let options = opts || {}; let fromStat; let toStat; let destExists; diff --git a/node_modules/jake/package.json b/node_modules/jake/package.json index dce34ef..2eb5726 100644 --- a/node_modules/jake/package.json +++ b/node_modules/jake/package.json @@ -7,7 +7,7 @@ "make", "rake" ], - "version": "10.8.5", + "version": "10.8.7", "author": "Matthew Eernisse (http://fleegix.org)", "license": "Apache-2.0", "bin": { @@ -28,12 +28,12 @@ "dependencies": { "async": "^3.2.3", "chalk": "^4.0.2", - "filelist": "^1.0.1", - "minimatch": "^3.0.4" + "filelist": "^1.0.4", + "minimatch": "^3.1.2" }, "devDependencies": { "eslint": "^6.8.0", - "mocha": "^7.1.1", + "mocha": "^10.2.0", "q": "^1.5.1" }, "engines": { diff --git a/node_modules/jake/test/integration/concurrent.js b/node_modules/jake/test/integration/concurrent.js index 8c63133..ab649b9 100644 --- a/node_modules/jake/test/integration/concurrent.js +++ b/node_modules/jake/test/integration/concurrent.js @@ -9,27 +9,27 @@ suite('concurrent', function () { this.timeout(7000); test(' simple concurrent prerequisites 1', function () { - let out = exec(`${JAKE_CMD} -q concurrent:simple1`).toString().trim() + let out = exec(`${JAKE_CMD} -q concurrent:simple1`).toString().trim(); assert.equal('Started A\nStarted B\nFinished B\nFinished A', out); }); test(' simple concurrent prerequisites 2', function () { - let out = exec(`${JAKE_CMD} -q concurrent:simple2`).toString().trim() + let out = exec(`${JAKE_CMD} -q concurrent:simple2`).toString().trim(); assert.equal('Started C\nStarted D\nFinished C\nFinished D', out); }); test(' sequential concurrent prerequisites', function () { - let out = exec(`${JAKE_CMD} -q concurrent:seqconcurrent`).toString().trim() + let out = exec(`${JAKE_CMD} -q concurrent:seqconcurrent`).toString().trim(); assert.equal('Started A\nStarted B\nFinished B\nFinished A\nStarted C\nStarted D\nFinished C\nFinished D', out); }); test(' concurrent concurrent prerequisites', function () { - let out = exec(`${JAKE_CMD} -q concurrent:concurrentconcurrent`).toString().trim() + let out = exec(`${JAKE_CMD} -q concurrent:concurrentconcurrent`).toString().trim(); assert.equal('Started A\nStarted B\nStarted C\nStarted D\nFinished B\nFinished C\nFinished A\nFinished D', out); }); test(' concurrent prerequisites with subdependency', function () { - let out = exec(`${JAKE_CMD} -q concurrent:subdep`).toString().trim() + let out = exec(`${JAKE_CMD} -q concurrent:subdep`).toString().trim(); assert.equal('Started A\nFinished A\nStarted Ba\nFinished Ba', out); }); diff --git a/node_modules/jake/test/integration/file_task.js b/node_modules/jake/test/integration/file_task.js index a320ea2..4b5608e 100644 --- a/node_modules/jake/test/integration/file_task.js +++ b/node_modules/jake/test/integration/file_task.js @@ -122,5 +122,20 @@ suite('fileTask', function () { cleanUpAndNext(); }); + test('partially existing prereqs', function () { + /* + dependency graph: + /-- foo/output2a.txt --\ + foo -- foo/output1.txt --+ +-- output3.txt + \-- foo/output2b.txt --/ + */ + // build part of the prereqs + exec(`${JAKE_CMD} -q fileTest:foo/output2a.txt`); + // verify the final target gets built + exec(`${JAKE_CMD} -q fileTest:foo/output3.txt`); + let data = fs.readFileSync(process.cwd() + '/foo/output3.txt'); + assert.equal('w00t', data); + cleanUpAndNext(); + }); }); diff --git a/node_modules/jake/test/integration/jakefile.js b/node_modules/jake/test/integration/jakefile.js index f3b7d1a..9d57d0a 100644 --- a/node_modules/jake/test/integration/jakefile.js +++ b/node_modules/jake/test/integration/jakefile.js @@ -14,7 +14,7 @@ task('noActionNoPrereqs'); desc('Top-level zerbofrangazoomy task'); task('zerbofrangazoomy', function () { - console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!') + console.log('Whaaaaaaaa? Ran the zerbofrangazoomy task!'); }); desc('Task that throws'); @@ -237,7 +237,7 @@ namespace('fileTest', function () { desc('File task, run if the prereq file changes'); task('touch-prereq', function () { fs.writeFileSync('foo/prereq.txt', 'UPDATED'); - }) + }); desc('File task, has a preexisting file (with no associated task) as a prereq'); file('foo/from-prereq.txt', ['fileTest:foo', 'foo/prereq.txt'], function () { @@ -253,6 +253,21 @@ namespace('fileTest', function () { fs.writeFileSync('foo/bar/baz/bamf.txt', 'w00t'); }); + file('foo/output1.txt', ['foo'], () => { + fs.writeFileSync('foo/output1.txt', 'Contents of foo/output1.txt'); + }); + + file('foo/output2a.txt', ['foo/output1.txt'], () => { + fs.writeFileSync('foo/output2a.txt', 'Contents of foo/output2a.txt'); + }); + + file('foo/output2b.txt', ['foo/output1.txt'], () => { + fs.writeFileSync('foo/output2b.txt', 'Contents of foo/output2b.txt'); + }); + + file('foo/output3.txt', [ 'foo/output2a.txt', 'foo/output2b.txt'], () => { + fs.writeFileSync('foo/output3.txt', 'w00t'); + }); }); task('blammo'); @@ -332,6 +347,6 @@ namespace("large", function () { desc("Task with a large number of different prereqs"); task("different", different, { concurrency: 2 } , function () { - console.log("large:different") - }) + console.log("large:different"); + }); }); diff --git a/node_modules/jake/test/integration/jakelib/publish.jake.js b/node_modules/jake/test/integration/jakelib/publish.jake.js index 52dd04a..f8485d1 100644 --- a/node_modules/jake/test/integration/jakelib/publish.jake.js +++ b/node_modules/jake/test/integration/jakelib/publish.jake.js @@ -31,12 +31,12 @@ publishTask('zerb', function () { , 'tmp_publish/**' ]); this.publishCmd = 'node -p -e "\'%filename\'"'; - this.gitCmd = 'echo' + this.gitCmd = 'echo'; this.scheduleDelay = 0; this._ensureRepoClean = function () {}; this._getCurrentBranch = function () { - return 'v0.0' + return 'v0.0'; }; }); diff --git a/node_modules/jake/test/integration/list_tasks.js b/node_modules/jake/test/integration/list_tasks.js new file mode 100644 index 0000000..c21d030 --- /dev/null +++ b/node_modules/jake/test/integration/list_tasks.js @@ -0,0 +1,15 @@ +const PROJECT_DIR = process.env.PROJECT_DIR; +const JAKE_CMD = `${PROJECT_DIR}/bin/cli.js`; + +let assert = require('assert'); +let proc = require('child_process'); + +suite('listTasks', function () { + test('execute "jake -T" without any errors', function () { + let message = 'cannot run "jake -T" command'; + let listTasks = function () { + proc.execFileSync(JAKE_CMD, ['-T']); + }; + assert.doesNotThrow(listTasks, TypeError, message); + }); +}); diff --git a/node_modules/jake/test/integration/selfdep.js b/node_modules/jake/test/integration/selfdep.js index 9ee7674..3195d08 100644 --- a/node_modules/jake/test/integration/selfdep.js +++ b/node_modules/jake/test/integration/selfdep.js @@ -24,7 +24,7 @@ suite('selfDep', function () { exec(`${JAKE_CMD} selfdepconst`); } catch(e) { - assert(e.message.indexOf('dependency of itself') > -1) + assert(e.message.indexOf('dependency of itself') > -1); } }); @@ -33,7 +33,7 @@ suite('selfDep', function () { exec(`${JAKE_CMD} selfdepdyn`); } catch(e) { - assert(e.message.indexOf('dependency of itself') > -1) + assert(e.message.indexOf('dependency of itself') > -1); } }); diff --git a/node_modules/jake/usage.txt b/node_modules/jake/usage.txt index ea5f255..40395c5 100644 --- a/node_modules/jake/usage.txt +++ b/node_modules/jake/usage.txt @@ -5,12 +5,13 @@ If no flags are given, Jake looks for a Jakefile or Jakefile.js in the current d {Usage}: jake [options ...] [env variables ...] target {Options}: - -f, --jakefile FILE Use FILE as the Jakefile. - -C, --directory DIRECTORY Change to DIRECTORY before running tasks. - -B, --always-make Unconditionally make all targets. - -T/-ls, --tasks Display the tasks (matching optional PATTERN) with descriptions, then exit. - -J, --jakelibdir JAKELIBDIR Auto-import any .jake files in JAKELIBDIR. (default is \'jakelib\') - -h, --help Display this help message. - -V/-v, --version Display the Jake version. - -ar, --allow-rejection Keep running even after unhandled promise rejection + -f, --jakefile FILE Use FILE as the Jakefile. + -C, --directory DIRECTORY Change to DIRECTORY before running tasks. + -q, --quiet Do not log messages to standard output. + -B, --always-make Unconditionally make all targets. + -T/-ls, --tasks Display the tasks (matching optional PATTERN) with descriptions, then exit. + -J, --jakelibdir JAKELIBDIR Auto-import any .jake files in JAKELIBDIR. (default is \'jakelib\') + -h, --help Display this help message. + -V/-v, --version Display the Jake version. + -ar, --allow-rejection Keep running even after unhandled promise rejection. diff --git a/node_modules/js-yaml/CHANGELOG.md b/node_modules/js-yaml/CHANGELOG.md index 1bb7c65..ff2375e 100644 --- a/node_modules/js-yaml/CHANGELOG.md +++ b/node_modules/js-yaml/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [4.1.0] - 2021-04-15 +### Added +- Types are now exported as `yaml.types.XXX`. +- Every type now has `options` property with original arguments kept as they were + (see `yaml.types.int.options` as an example). + +### Changed +- `Schema.extend()` now keeps old type order in case of conflicts + (e.g. Schema.extend([ a, b, c ]).extend([ b, a, d ]) is now ordered as `abcd` instead of `cbad`). + + ## [4.0.0] - 2021-01-03 ### Changed - Check [migration guide](migrate_v3_to_v4.md) to see details for all breaking changes. @@ -530,6 +542,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - First public release +[4.1.0]: https://github.com/nodeca/js-yaml/compare/4.0.0...4.1.0 [4.0.0]: https://github.com/nodeca/js-yaml/compare/3.14.0...4.0.0 [3.14.0]: https://github.com/nodeca/js-yaml/compare/3.13.1...3.14.0 [3.13.1]: https://github.com/nodeca/js-yaml/compare/3.13.0...3.13.1 diff --git a/node_modules/js-yaml/README.md b/node_modules/js-yaml/README.md index 90a8fe1..3cbc4bd 100644 --- a/node_modules/js-yaml/README.md +++ b/node_modules/js-yaml/README.md @@ -130,7 +130,7 @@ options: - `schema` _(default: `DEFAULT_SCHEMA`)_ specifies a schema to use. - `sortKeys` _(default: `false`)_ - if `true`, sort keys when dumping YAML. If a function, use the function to sort the keys. -- `lineWidth` _(default: `80`)_ - set max line width. +- `lineWidth` _(default: `80`)_ - set max line width. Set `-1` for unlimited width. - `noRefs` _(default: `false`)_ - if `true`, don't convert duplicate objects into references - `noCompatMode` _(default: `false`)_ - if `true` don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 diff --git a/node_modules/js-yaml/bin/js-yaml.js b/node_modules/js-yaml/bin/js-yaml.js old mode 100755 new mode 100644 diff --git a/node_modules/js-yaml/dist/js-yaml.js b/node_modules/js-yaml/dist/js-yaml.js index 228bdd2..4cc0ddf 100644 --- a/node_modules/js-yaml/dist/js-yaml.js +++ b/node_modules/js-yaml/dist/js-yaml.js @@ -1,5 +1,5 @@ -/*! js-yaml 4.0.0 https://github.com/nodeca/js-yaml @license MIT */ +/*! js-yaml 4.1.0 https://github.com/nodeca/js-yaml @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : @@ -94,7 +94,7 @@ } - function YAMLException(reason, mark) { + function YAMLException$1(reason, mark) { // Super constructor Error.call(this); @@ -115,16 +115,16 @@ // Inherit from Error - YAMLException.prototype = Object.create(Error.prototype); - YAMLException.prototype.constructor = YAMLException; + YAMLException$1.prototype = Object.create(Error.prototype); + YAMLException$1.prototype.constructor = YAMLException$1; - YAMLException.prototype.toString = function toString(compact) { + YAMLException$1.prototype.toString = function toString(compact) { return this.name + ': ' + formatError(this, compact); }; - var exception = YAMLException; + var exception = YAMLException$1; // get snippet for a single line, respecting maxLength function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { @@ -255,7 +255,7 @@ return result; } - function Type(tag, options) { + function Type$1(tag, options) { options = options || {}; Object.keys(options).forEach(function (name) { @@ -265,6 +265,7 @@ }); // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; @@ -282,7 +283,7 @@ } } - var type = Type; + var type = Type$1; /*eslint-disable max-len*/ @@ -290,25 +291,25 @@ - function compileList(schema, name, result) { - var exclude = []; + function compileList(schema, name) { + var result = []; schema[name].forEach(function (currentType) { + var newIndex = result.length; + result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { - exclude.push(previousIndex); + newIndex = previousIndex; } }); - result.push(currentType); + result[newIndex] = currentType; }); - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); + return result; } @@ -342,12 +343,12 @@ } - function Schema(definition) { + function Schema$1(definition) { return this.extend(definition); } - Schema.prototype.extend = function extend(definition) { + Schema$1.prototype.extend = function extend(definition) { var implicit = []; var explicit = []; @@ -389,20 +390,20 @@ } }); - var result = Object.create(Schema.prototype); + var result = Object.create(Schema$1.prototype); result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); - result.compiledImplicit = compileList(result, 'implicit', []); - result.compiledExplicit = compileList(result, 'explicit', []); + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; }; - var schema = Schema; + var schema = Schema$1; var str = new type('tag:yaml.org,2002:str', { kind: 'scalar', @@ -965,8 +966,8 @@ represent: representYamlBinary }); - var _hasOwnProperty = Object.prototype.hasOwnProperty; - var _toString = Object.prototype.toString; + var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + var _toString$2 = Object.prototype.toString; function resolveYamlOmap(data) { if (data === null) return true; @@ -978,10 +979,10 @@ pair = object[index]; pairHasKey = false; - if (_toString.call(pair) !== '[object Object]') return false; + if (_toString$2.call(pair) !== '[object Object]') return false; for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { + if (_hasOwnProperty$3.call(pair, pairKey)) { if (!pairHasKey) pairHasKey = true; else return false; } @@ -1056,7 +1057,7 @@ construct: constructYamlPairs }); - var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; + var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; function resolveYamlSet(data) { if (data === null) return true; @@ -1064,7 +1065,7 @@ var key, object = data; for (key in object) { - if (_hasOwnProperty$1.call(object, key)) { + if (_hasOwnProperty$2.call(object, key)) { if (object[key] !== null) return false; } } @@ -1103,7 +1104,7 @@ - var _hasOwnProperty$2 = Object.prototype.hasOwnProperty; + var _hasOwnProperty$1 = Object.prototype.hasOwnProperty; var CONTEXT_FLOW_IN = 1; @@ -1223,7 +1224,7 @@ } - function State(input, options) { + function State$1(input, options) { this.input = input; this.filename = options['filename'] || null; @@ -1339,7 +1340,7 @@ throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); } - if (_hasOwnProperty$2.call(state.tagMap, handle)) { + if (_hasOwnProperty$1.call(state.tagMap, handle)) { throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); } @@ -1392,7 +1393,7 @@ for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { key = sourceKeys[index]; - if (!_hasOwnProperty$2.call(destination, key)) { + if (!_hasOwnProperty$1.call(destination, key)) { destination[key] = source[key]; overridableKeys[key] = true; } @@ -1445,8 +1446,8 @@ } } else { if (!state.json && - !_hasOwnProperty$2.call(overridableKeys, keyNode) && - _hasOwnProperty$2.call(_result, keyNode)) { + !_hasOwnProperty$1.call(overridableKeys, keyNode) && + _hasOwnProperty$1.call(_result, keyNode)) { state.line = startLine || state.line; state.lineStart = startLineStart || state.lineStart; state.position = startPos || state.position; @@ -2384,7 +2385,7 @@ if (isVerbatim) { state.tag = tagName; - } else if (_hasOwnProperty$2.call(state.tagMap, tagHandle)) { + } else if (_hasOwnProperty$1.call(state.tagMap, tagHandle)) { state.tag = state.tagMap[tagHandle] + tagName; } else if (tagHandle === '!') { @@ -2448,7 +2449,7 @@ alias = state.input.slice(_position, state.position); - if (!_hasOwnProperty$2.call(state.anchorMap, alias)) { + if (!_hasOwnProperty$1.call(state.anchorMap, alias)) { throwError(state, 'unidentified alias "' + alias + '"'); } @@ -2597,7 +2598,7 @@ } } } else if (state.tag !== '!') { - if (_hasOwnProperty$2.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + if (_hasOwnProperty$1.call(state.typeMap[state.kind || 'fallback'], state.tag)) { type = state.typeMap[state.kind || 'fallback'][state.tag]; } else { // looking for multi type @@ -2697,7 +2698,7 @@ if (ch !== 0) readLineBreak(state); - if (_hasOwnProperty$2.call(directiveHandlers, directiveName)) { + if (_hasOwnProperty$1.call(directiveHandlers, directiveName)) { directiveHandlers[directiveName](state, directiveName, directiveArgs); } else { throwWarning(state, 'unknown document directive "' + directiveName + '"'); @@ -2762,7 +2763,7 @@ } } - var state = new State(input, options); + var state = new State$1(input, options); var nullpos = input.indexOf('\0'); @@ -2787,7 +2788,7 @@ } - function loadAll(input, iterator, options) { + function loadAll$1(input, iterator, options) { if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { options = iterator; iterator = null; @@ -2805,7 +2806,7 @@ } - function load(input, options) { + function load$1(input, options) { var documents = loadDocuments(input, options); if (documents.length === 0) { @@ -2818,8 +2819,8 @@ } - var loadAll_1 = loadAll; - var load_1 = load; + var loadAll_1 = loadAll$1; + var load_1 = load$1; var loader = { loadAll: loadAll_1, @@ -2832,8 +2833,8 @@ - var _toString$2 = Object.prototype.toString; - var _hasOwnProperty$3 = Object.prototype.hasOwnProperty; + var _toString = Object.prototype.toString; + var _hasOwnProperty = Object.prototype.hasOwnProperty; var CHAR_BOM = 0xFEFF; var CHAR_TAB = 0x09; /* Tab */ @@ -2903,7 +2904,7 @@ } type = schema.compiledTypeMap['fallback'][tag]; - if (type && _hasOwnProperty$3.call(type.styleAliases, style)) { + if (type && _hasOwnProperty.call(type.styleAliases, style)) { style = type.styleAliases[style]; } @@ -2938,7 +2939,7 @@ var QUOTING_TYPE_SINGLE = 1, QUOTING_TYPE_DOUBLE = 2; - function State$1(options) { + function State(options) { this.schema = options['schema'] || _default; this.indent = Math.max(1, (options['indent'] || 2)); this.noArrayIndent = options['noArrayIndent'] || false; @@ -3599,9 +3600,9 @@ if (type.represent) { style = state.styleMap[type.tag] || type.defaultStyle; - if (_toString$2.call(type.represent) === '[object Function]') { + if (_toString.call(type.represent) === '[object Function]') { _result = type.represent(object, style); - } else if (_hasOwnProperty$3.call(type.represent, style)) { + } else if (_hasOwnProperty.call(type.represent, style)) { _result = type.represent[style](object, style); } else { throw new exception('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); @@ -3628,7 +3629,7 @@ detectType(state, object, true); } - var type = _toString$2.call(state.dump); + var type = _toString.call(state.dump); var inblock = block; var tagStr; @@ -3770,10 +3771,10 @@ } } - function dump(input, options) { + function dump$1(input, options) { options = options || {}; - var state = new State$1(options); + var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); @@ -3788,7 +3789,7 @@ return ''; } - var dump_1 = dump; + var dump_1 = dump$1; var dumper = { dump: dump_1 @@ -3802,16 +3803,33 @@ } - var Type$1 = type; - var Schema$1 = schema; + var Type = type; + var Schema = schema; var FAILSAFE_SCHEMA = failsafe; var JSON_SCHEMA = json; var CORE_SCHEMA = core; var DEFAULT_SCHEMA = _default; - var load$1 = loader.load; - var loadAll$1 = loader.loadAll; - var dump$1 = dumper.dump; - var YAMLException$1 = exception; + var load = loader.load; + var loadAll = loader.loadAll; + var dump = dumper.dump; + var YAMLException = exception; + + // Re-export all types in case user wants to create custom schema + var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str + }; // Removed functions from JS-YAML 3.0.x var safeLoad = renamed('safeLoad', 'load'); @@ -3819,16 +3837,17 @@ var safeDump = renamed('safeDump', 'dump'); var jsYaml = { - Type: Type$1, - Schema: Schema$1, + Type: Type, + Schema: Schema, FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, JSON_SCHEMA: JSON_SCHEMA, CORE_SCHEMA: CORE_SCHEMA, DEFAULT_SCHEMA: DEFAULT_SCHEMA, - load: load$1, - loadAll: loadAll$1, - dump: dump$1, - YAMLException: YAMLException$1, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, safeLoad: safeLoad, safeLoadAll: safeLoadAll, safeDump: safeDump @@ -3838,16 +3857,17 @@ exports.DEFAULT_SCHEMA = DEFAULT_SCHEMA; exports.FAILSAFE_SCHEMA = FAILSAFE_SCHEMA; exports.JSON_SCHEMA = JSON_SCHEMA; - exports.Schema = Schema$1; - exports.Type = Type$1; - exports.YAMLException = YAMLException$1; + exports.Schema = Schema; + exports.Type = Type; + exports.YAMLException = YAMLException; exports.default = jsYaml; - exports.dump = dump$1; - exports.load = load$1; - exports.loadAll = loadAll$1; + exports.dump = dump; + exports.load = load; + exports.loadAll = loadAll; exports.safeDump = safeDump; exports.safeLoad = safeLoad; exports.safeLoadAll = safeLoadAll; + exports.types = types; Object.defineProperty(exports, '__esModule', { value: true }); diff --git a/node_modules/js-yaml/dist/js-yaml.min.js b/node_modules/js-yaml/dist/js-yaml.min.js index 6a46952..bdd8eef 100644 --- a/node_modules/js-yaml/dist/js-yaml.min.js +++ b/node_modules/js-yaml/dist/js-yaml.min.js @@ -1,2 +1,2 @@ -/*! js-yaml 4.0.0 https://github.com/nodeca/js-yaml @license MIT */ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).jsyaml={})}(this,(function(e){"use strict";function t(e){return null==e}var n={isNothing:t,isObject:function(e){return"object"==typeof e&&null!==e},toArray:function(e){return Array.isArray(e)?e:t(e)?[]:[e]},repeat:function(e,t){var n,i="";for(n=0;nl&&(t=i-l+(o=" ... ").length),n-i>l&&(n=i+l-(a=" ...").length),{str:o+e.slice(t,n).replace(/\t/g,"→")+a,pos:i-t+o.length}}function l(e,t){return n.repeat(" ",t-e.length)+e}var c=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var i,r=/\r?\n|\r|\0/g,o=[0],c=[],s=-1;i=r.exec(e.buffer);)c.push(i.index),o.push(i.index+i[0].length),e.position<=i.index&&s<0&&(s=o.length-2);s<0&&(s=o.length-1);var u,p,f="",d=Math.min(e.line+t.linesAfter,c.length).toString().length,h=t.maxLength-(t.indent+d+3);for(u=1;u<=t.linesBefore&&!(s-u<0);u++)p=a(e.buffer,o[s-u],c[s-u],e.position-(o[s]-o[s-u]),h),f=n.repeat(" ",t.indent)+l((e.line-u+1).toString(),d)+" | "+p.str+"\n"+f;for(p=a(e.buffer,o[s],c[s],e.position,h),f+=n.repeat(" ",t.indent)+l((e.line+1).toString(),d)+" | "+p.str+"\n",f+=n.repeat("-",t.indent+d+3+p.pos)+"^\n",u=1;u<=t.linesAfter&&!(s+u>=c.length);u++)p=a(e.buffer,o[s+u],c[s+u],e.position-(o[s]-o[s+u]),h),f+=n.repeat(" ",t.indent)+l((e.line+u+1).toString(),d)+" | "+p.str+"\n";return f.replace(/\n$/,"")},s=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],u=["scalar","sequence","mapping"];var p=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===s.indexOf(t))throw new o('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(n){e[n].forEach((function(e){t[String(e)]=n}))})),t}(t.styleAliases||null),-1===u.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function f(e,t,n){var i=[];return e[t].forEach((function(e){n.forEach((function(t,n){t.tag===e.tag&&t.kind===e.kind&&t.multi===e.multi&&i.push(n)})),n.push(e)})),n.filter((function(e,t){return-1===i.indexOf(t)}))}function d(e){return this.extend(e)}d.prototype.extend=function(e){var t=[],n=[];if(e instanceof p)n.push(e);else if(Array.isArray(e))n=n.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new o("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new o("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),n.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var i=Object.create(d.prototype);return i.implicit=(this.implicit||[]).concat(t),i.explicit=(this.explicit||[]).concat(n),i.compiledImplicit=f(i,"implicit",[]),i.compiledExplicit=f(i,"explicit",[]),i.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function i(e){e.multi?(n.multi[e.kind].push(e),n.multi.fallback.push(e)):n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),w=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var k=/^[-+]?[0-9]+e/;var C=new p("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!w.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||n.isNegativeZero(e))},represent:function(e,t){var i;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(n.isNegativeZero(e))return"-0.0";return i=e.toString(10),k.test(i)?i.replace("e",".e"):i},defaultStyle:"lowercase"}),x=g.extend({implicit:[m,y,v,C]}),I=x,S=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),O=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var j=new p("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==S.exec(e)||null!==O.exec(e))},construct:function(e){var t,n,i,r,o,a,l,c,s=0,u=null;if(null===(t=S.exec(e))&&(t=O.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],i=+t[2]-1,r=+t[3],!t[4])return new Date(Date.UTC(n,i,r));if(o=+t[4],a=+t[5],l=+t[6],t[7]){for(s=t[7].slice(0,3);s.length<3;)s+="0";s=+s}return t[9]&&(u=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(u=-u)),c=new Date(Date.UTC(n,i,r,o,a,l,s)),u&&c.setTime(c.getTime()-u),c},instanceOf:Date,represent:function(e){return e.toISOString()}});var T=new p("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),N="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var F=new p("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i=0,r=e.length,o=N;for(n=0;n64)){if(t<0)return!1;i+=6}return i%8==0},construct:function(e){var t,n,i=e.replace(/[\r\n=]/g,""),r=i.length,o=N,a=0,l=[];for(t=0;t>16&255),l.push(a>>8&255),l.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0===(n=r%4*6)?(l.push(a>>16&255),l.push(a>>8&255),l.push(255&a)):18===n?(l.push(a>>10&255),l.push(a>>2&255)):12===n&&l.push(a>>4&255),new Uint8Array(l)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=N;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0===(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2===n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1===n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}}),E=Object.prototype.hasOwnProperty,M=Object.prototype.toString;var L=new p("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,n,i,r,o,a=[],l=e;for(t=0,n=l.length;t>10),56320+(e-65536&1023))}for(var ee=new Array(256),te=new Array(256),ne=0;ne<256;ne++)ee[ne]=z(ne)?1:0,te[ne]=z(ne);function ie(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||q,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function re(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=c(n),new o(t,n)}function oe(e,t){throw re(e,t)}function ae(e,t){e.onWarning&&e.onWarning.call(null,re(e,t))}var le={YAML:function(e,t,n){var i,r,o;null!==e.version&&oe(e,"duplication of %YAML directive"),1!==n.length&&oe(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&oe(e,"ill-formed argument of the YAML directive"),r=parseInt(i[1],10),o=parseInt(i[2],10),1!==r&&oe(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&ae(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,r;2!==n.length&&oe(e,"TAG directive accepts exactly two arguments"),i=n[0],r=n[1],W.test(i)||oe(e,"ill-formed tag handle (first argument) of the TAG directive"),R.call(e.tagMap,i)&&oe(e,'there is a previously declared suffix for "'+i+'" tag handle'),H.test(r)||oe(e,"ill-formed tag prefix (second argument) of the TAG directive");try{r=decodeURIComponent(r)}catch(t){oe(e,"tag prefix is malformed: "+r)}e.tagMap[i]=r}};function ce(e,t,n,i){var r,o,a,l;if(t1&&(e.result+=n.repeat("\n",t-1))}function ge(e,t){var n,i,r=e.tag,o=e.anchor,a=[],l=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,oe(e,"tab characters must not be used in indentation")),45===i)&&Z(e.input.charCodeAt(e.position+1));)if(l=!0,e.position++,fe(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,be(e,t,3,!1,!0),a.push(e.result),fe(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)oe(e,"bad indentation of a sequence entry");else if(e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt)&&(y&&(a=e.line,l=e.lineStart,c=e.position),be(e,t,4,!0,r)&&(y?g=e.result:m=e.result),y||(ue(e,f,d,h,g,m,a,l,c),h=g=m=null),fe(e,!0,-1),s=e.input.charCodeAt(e.position)),(e.line===o||e.lineIndent>t)&&0!==s)oe(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===o?oe(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):u?oe(e,"repeat of an indentation width identifier"):(p=t+o-1,u=!0)}if(V(a)){do{a=e.input.charCodeAt(++e.position)}while(V(a));if(35===a)do{a=e.input.charCodeAt(++e.position)}while(!G(a)&&0!==a)}for(;0!==a;){for(pe(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!u||e.lineIndentp&&(p=e.lineIndent),G(a))f++;else{if(e.lineIndent0){for(r=a,o=0;r>0;r--)(a=Q(l=e.input.charCodeAt(++e.position)))>=0?o=(o<<4)+a:oe(e,"expected hexadecimal character");e.result+=X(o),e.position++}else oe(e,"unknown escape sequence");n=i=e.position}else G(l)?(ce(e,n,i,!0),he(e,fe(e,!1,t)),n=i=e.position):e.position===e.lineStart&&de(e)?oe(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}oe(e,"unexpected end of the stream within a double quoted scalar")}(e,d)?y=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!Z(i)&&!J(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&oe(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),R.call(e.anchorMap,n)||oe(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],fe(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,l,c,s,u,p=e.kind,f=e.result;if(Z(u=e.input.charCodeAt(e.position))||J(u)||35===u||38===u||42===u||33===u||124===u||62===u||39===u||34===u||37===u||64===u||96===u)return!1;if((63===u||45===u)&&(Z(i=e.input.charCodeAt(e.position+1))||n&&J(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==u;){if(58===u){if(Z(i=e.input.charCodeAt(e.position+1))||n&&J(i))break}else if(35===u){if(Z(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&de(e)||n&&J(u))break;if(G(u)){if(l=e.line,c=e.lineStart,s=e.lineIndent,fe(e,!1,-1),e.lineIndent>=t){a=!0,u=e.input.charCodeAt(e.position);continue}e.position=o,e.line=l,e.lineStart=c,e.lineIndent=s;break}}a&&(ce(e,r,o,!1),he(e,e.line-l),r=o=e.position,a=!1),V(u)||(o=e.position+1),u=e.input.charCodeAt(++e.position)}return ce(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,d,1===i)&&(y=!0,null===e.tag&&(e.tag="?")):(y=!0,null===e.tag&&null===e.anchor||oe(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===g&&(y=c&&ge(e,h))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&oe(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),s=0,u=e.implicitTypes.length;s"),null!==e.result&&f.kind!==e.kind&&oe(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+f.kind+'", not "'+e.kind+'"'),f.resolve(e.result,e.tag)?(e.result=f.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):oe(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||y}function Ae(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(r=e.input.charCodeAt(e.position))&&(fe(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==r));){for(a=!0,r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!Z(r);)r=e.input.charCodeAt(++e.position);for(i=[],(n=e.input.slice(t,e.position)).length<1&&oe(e,"directive name must not be less than one character in length");0!==r;){for(;V(r);)r=e.input.charCodeAt(++e.position);if(35===r){do{r=e.input.charCodeAt(++e.position)}while(0!==r&&!G(r));break}if(G(r))break;for(t=e.position;0!==r&&!Z(r);)r=e.input.charCodeAt(++e.position);i.push(e.input.slice(t,e.position))}0!==r&&pe(e),R.call(le,n)?le[n](e,n,i):ae(e,'unknown document directive "'+n+'"')}fe(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,fe(e,!0,-1)):a&&oe(e,"directives end mark is expected"),be(e,e.lineIndent-1,4,!1,!0),fe(e,!0,-1),e.checkLineBreaks&&K.test(e.input.slice(o,e.position))&&ae(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&de(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,fe(e,!0,-1)):e.position=55296&&i<=56319&&t+1=56320&&n<=57343?1024*(i-55296)+n-56320+65536:i}function Ue(e){return/^\n* /.test(e)}function Ye(e,t,n,i,r,o,a,l){var c,s,u=0,p=null,f=!1,d=!1,h=-1!==i,g=-1,m=Me(s=De(e,0))&&s!==xe&&!Ee(s)&&45!==s&&63!==s&&58!==s&&44!==s&&91!==s&&93!==s&&123!==s&&125!==s&&35!==s&&38!==s&&42!==s&&33!==s&&124!==s&&61!==s&&62!==s&&39!==s&&34!==s&&37!==s&&64!==s&&96!==s&&function(e){return!Ee(e)&&58!==e}(De(e,e.length-1));if(t||a)for(c=0;c=65536?c+=2:c++){if(!Me(u=De(e,c)))return 5;m=m&&_e(u,p,l),p=u}else{for(c=0;c=65536?c+=2:c++){if(10===(u=De(e,c)))f=!0,h&&(d=d||c-g-1>i&&" "!==e[g+1],g=c);else if(!Me(u))return 5;m=m&&_e(u,p,l),p=u}d=d||h&&c-g-1>i&&" "!==e[g+1]}return f||d?n>9&&Ue(e)?5:a?2===o?5:2:d?4:3:!m||a||r(e)?2===o?5:2:1}function qe(e,t,n,i,r){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Se.indexOf(t)||Oe.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var a=e.indent*Math.max(1,n),l=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-a),c=i||e.flowLevel>-1&&n>=e.flowLevel;switch(Ye(t,c,e.indent,l,(function(t){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+Re(t,e.indent)+Be(Ne(function(e,t){var n,i,r=/(\n+)([^\n]*)/g,o=(l=e.indexOf("\n"),l=-1!==l?l:e.length,r.lastIndex=l,Ke(e.slice(0,l),t)),a="\n"===e[0]||" "===e[0];var l;for(;i=r.exec(e);){var c=i[1],s=i[2];n=" "===s[0],o+=c+(a||n||""===s?"":"\n")+Ke(s,t),a=n}return o}(t,l),a));case 5:return'"'+function(e){for(var t,n="",i=0,r=0;r=65536?r+=2:r++)i=De(e,r),!(t=Ie[i])&&Me(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=t||je(i);return n}(t)+'"';default:throw new o("impossible error: invalid scalar style")}}()}function Re(e,t){var n=Ue(e)?String(t):"",i="\n"===e[e.length-1];return n+(i&&("\n"===e[e.length-2]||"\n"===e)?"+":i?"":"-")+"\n"}function Be(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function Ke(e,t){if(""===e||" "===e[0])return e;for(var n,i,r=/ [^ ]/g,o=0,a=0,l=0,c="";n=r.exec(e);)(l=n.index)-o>t&&(i=a>o?a:l,c+="\n"+e.slice(o,i),o=i+1),a=l;return c+="\n",e.length-o>t&&a>o?c+=e.slice(o,a)+"\n"+e.slice(a+1):c+=e.slice(o),c.slice(1)}function Pe(e,t,n,i){var r,o,a,l="",c=e.tag;for(r=0,o=n.length;r tag resolver accepts not "'+s+'" style');i=c.represent[s](t,s)}e.dump=i}return!0}return!1}function He(e,t,n,i,r,a,l){e.tag=null,e.dump=n,We(e,n,!1)||We(e,n,!0);var c,s=ke.call(e.dump),u=i;i&&(i=e.flowLevel<0||e.flowLevel>t);var p,f,d="[object Object]"===s||"[object Array]"===s;if(d&&(f=-1!==(p=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||f||2!==e.indent&&t>0)&&(r=!1),f&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(d&&f&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),"[object Object]"===s)i&&0!==Object.keys(e.dump).length?(!function(e,t,n,i){var r,a,l,c,s,u,p="",f=e.tag,d=Object.keys(n);if(!0===e.sortKeys)d.sort();else if("function"==typeof e.sortKeys)d.sort(e.sortKeys);else if(e.sortKeys)throw new o("sortKeys must be a boolean or a function");for(r=0,a=d.length;r1024)&&(e.dump&&10===e.dump.charCodeAt(0)?u+="?":u+="? "),u+=e.dump,s&&(u+=Fe(e,t)),He(e,t+1,c,!0,s)&&(e.dump&&10===e.dump.charCodeAt(0)?u+=":":u+=": ",p+=u+=e.dump));e.tag=f,e.dump=p||"{}"}(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a,l,c="",s=e.tag,u=Object.keys(n);for(i=0,r=u.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),He(e,t,a,!1,!1)&&(c+=l+=e.dump));e.tag=s,e.dump="{"+c+"}"}(e,t,e.dump),f&&(e.dump="&ref_"+p+" "+e.dump));else if("[object Array]"===s)i&&0!==e.dump.length?(e.noArrayIndent&&!l&&t>0?Pe(e,t-1,e.dump,r):Pe(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a="",l=e.tag;for(i=0,r=n.length;i",e.dump=c+" "+e.dump)}return!0}function $e(e,t){var n,i,r=[],o=[];for(Ge(e,r,o),n=0,i=o.length;nl&&(t=i-l+(o=" ... ").length),n-i>l&&(n=i+l-(a=" ...").length),{str:o+e.slice(t,n).replace(/\t/g,"→")+a,pos:i-t+o.length}}function l(e,t){return n.repeat(" ",t-e.length)+e}var c=function(e,t){if(t=Object.create(t||null),!e.buffer)return null;t.maxLength||(t.maxLength=79),"number"!=typeof t.indent&&(t.indent=1),"number"!=typeof t.linesBefore&&(t.linesBefore=3),"number"!=typeof t.linesAfter&&(t.linesAfter=2);for(var i,r=/\r?\n|\r|\0/g,o=[0],c=[],s=-1;i=r.exec(e.buffer);)c.push(i.index),o.push(i.index+i[0].length),e.position<=i.index&&s<0&&(s=o.length-2);s<0&&(s=o.length-1);var u,p,f="",d=Math.min(e.line+t.linesAfter,c.length).toString().length,h=t.maxLength-(t.indent+d+3);for(u=1;u<=t.linesBefore&&!(s-u<0);u++)p=a(e.buffer,o[s-u],c[s-u],e.position-(o[s]-o[s-u]),h),f=n.repeat(" ",t.indent)+l((e.line-u+1).toString(),d)+" | "+p.str+"\n"+f;for(p=a(e.buffer,o[s],c[s],e.position,h),f+=n.repeat(" ",t.indent)+l((e.line+1).toString(),d)+" | "+p.str+"\n",f+=n.repeat("-",t.indent+d+3+p.pos)+"^\n",u=1;u<=t.linesAfter&&!(s+u>=c.length);u++)p=a(e.buffer,o[s+u],c[s+u],e.position-(o[s]-o[s+u]),h),f+=n.repeat(" ",t.indent)+l((e.line+u+1).toString(),d)+" | "+p.str+"\n";return f.replace(/\n$/,"")},s=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],u=["scalar","sequence","mapping"];var p=function(e,t){if(t=t||{},Object.keys(t).forEach((function(t){if(-1===s.indexOf(t))throw new o('Unknown option "'+t+'" is met in definition of "'+e+'" YAML type.')})),this.options=t,this.tag=e,this.kind=t.kind||null,this.resolve=t.resolve||function(){return!0},this.construct=t.construct||function(e){return e},this.instanceOf=t.instanceOf||null,this.predicate=t.predicate||null,this.represent=t.represent||null,this.representName=t.representName||null,this.defaultStyle=t.defaultStyle||null,this.multi=t.multi||!1,this.styleAliases=function(e){var t={};return null!==e&&Object.keys(e).forEach((function(n){e[n].forEach((function(e){t[String(e)]=n}))})),t}(t.styleAliases||null),-1===u.indexOf(this.kind))throw new o('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')};function f(e,t){var n=[];return e[t].forEach((function(e){var t=n.length;n.forEach((function(n,i){n.tag===e.tag&&n.kind===e.kind&&n.multi===e.multi&&(t=i)})),n[t]=e})),n}function d(e){return this.extend(e)}d.prototype.extend=function(e){var t=[],n=[];if(e instanceof p)n.push(e);else if(Array.isArray(e))n=n.concat(e);else{if(!e||!Array.isArray(e.implicit)&&!Array.isArray(e.explicit))throw new o("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");e.implicit&&(t=t.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit))}t.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(e.loadKind&&"scalar"!==e.loadKind)throw new o("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(e.multi)throw new o("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")})),n.forEach((function(e){if(!(e instanceof p))throw new o("Specified list of YAML types (or a single Type object) contains a non-Type object.")}));var i=Object.create(d.prototype);return i.implicit=(this.implicit||[]).concat(t),i.explicit=(this.explicit||[]).concat(n),i.compiledImplicit=f(i,"implicit"),i.compiledExplicit=f(i,"explicit"),i.compiledTypeMap=function(){var e,t,n={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}};function i(e){e.multi?(n.multi[e.kind].push(e),n.multi.fallback.push(e)):n[e.kind][e.tag]=n.fallback[e.tag]=e}for(e=0,t=arguments.length;e=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),x=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");var I=/^[-+]?[0-9]+e/;var S=new p("tag:yaml.org,2002:float",{kind:"scalar",resolve:function(e){return null!==e&&!(!x.test(e)||"_"===e[e.length-1])},construct:function(e){var t,n;return n="-"===(t=e.replace(/_/g,"").toLowerCase())[0]?-1:1,"+-".indexOf(t[0])>=0&&(t=t.slice(1)),".inf"===t?1===n?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:".nan"===t?NaN:n*parseFloat(t,10)},predicate:function(e){return"[object Number]"===Object.prototype.toString.call(e)&&(e%1!=0||n.isNegativeZero(e))},represent:function(e,t){var i;if(isNaN(e))switch(t){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(t){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(t){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(n.isNegativeZero(e))return"-0.0";return i=e.toString(10),I.test(i)?i.replace("e",".e"):i},defaultStyle:"lowercase"}),O=b.extend({implicit:[A,v,C,S]}),j=O,T=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),N=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");var F=new p("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:function(e){return null!==e&&(null!==T.exec(e)||null!==N.exec(e))},construct:function(e){var t,n,i,r,o,a,l,c,s=0,u=null;if(null===(t=T.exec(e))&&(t=N.exec(e)),null===t)throw new Error("Date resolve error");if(n=+t[1],i=+t[2]-1,r=+t[3],!t[4])return new Date(Date.UTC(n,i,r));if(o=+t[4],a=+t[5],l=+t[6],t[7]){for(s=t[7].slice(0,3);s.length<3;)s+="0";s=+s}return t[9]&&(u=6e4*(60*+t[10]+ +(t[11]||0)),"-"===t[9]&&(u=-u)),c=new Date(Date.UTC(n,i,r,o,a,l,s)),u&&c.setTime(c.getTime()-u),c},instanceOf:Date,represent:function(e){return e.toISOString()}});var E=new p("tag:yaml.org,2002:merge",{kind:"scalar",resolve:function(e){return"<<"===e||null===e}}),M="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r";var L=new p("tag:yaml.org,2002:binary",{kind:"scalar",resolve:function(e){if(null===e)return!1;var t,n,i=0,r=e.length,o=M;for(n=0;n64)){if(t<0)return!1;i+=6}return i%8==0},construct:function(e){var t,n,i=e.replace(/[\r\n=]/g,""),r=i.length,o=M,a=0,l=[];for(t=0;t>16&255),l.push(a>>8&255),l.push(255&a)),a=a<<6|o.indexOf(i.charAt(t));return 0===(n=r%4*6)?(l.push(a>>16&255),l.push(a>>8&255),l.push(255&a)):18===n?(l.push(a>>10&255),l.push(a>>2&255)):12===n&&l.push(a>>4&255),new Uint8Array(l)},predicate:function(e){return"[object Uint8Array]"===Object.prototype.toString.call(e)},represent:function(e){var t,n,i="",r=0,o=e.length,a=M;for(t=0;t>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]),r=(r<<8)+e[t];return 0===(n=o%3)?(i+=a[r>>18&63],i+=a[r>>12&63],i+=a[r>>6&63],i+=a[63&r]):2===n?(i+=a[r>>10&63],i+=a[r>>4&63],i+=a[r<<2&63],i+=a[64]):1===n&&(i+=a[r>>2&63],i+=a[r<<4&63],i+=a[64],i+=a[64]),i}}),_=Object.prototype.hasOwnProperty,D=Object.prototype.toString;var U=new p("tag:yaml.org,2002:omap",{kind:"sequence",resolve:function(e){if(null===e)return!0;var t,n,i,r,o,a=[],l=e;for(t=0,n=l.length;t>10),56320+(e-65536&1023))}for(var ie=new Array(256),re=new Array(256),oe=0;oe<256;oe++)ie[oe]=te(oe)?1:0,re[oe]=te(oe);function ae(e,t){this.input=e,this.filename=t.filename||null,this.schema=t.schema||K,this.onWarning=t.onWarning||null,this.legacy=t.legacy||!1,this.json=t.json||!1,this.listener=t.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function le(e,t){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=c(n),new o(t,n)}function ce(e,t){throw le(e,t)}function se(e,t){e.onWarning&&e.onWarning.call(null,le(e,t))}var ue={YAML:function(e,t,n){var i,r,o;null!==e.version&&ce(e,"duplication of %YAML directive"),1!==n.length&&ce(e,"YAML directive accepts exactly one argument"),null===(i=/^([0-9]+)\.([0-9]+)$/.exec(n[0]))&&ce(e,"ill-formed argument of the YAML directive"),r=parseInt(i[1],10),o=parseInt(i[2],10),1!==r&&ce(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=o<2,1!==o&&2!==o&&se(e,"unsupported YAML version of the document")},TAG:function(e,t,n){var i,r;2!==n.length&&ce(e,"TAG directive accepts exactly two arguments"),i=n[0],r=n[1],G.test(i)||ce(e,"ill-formed tag handle (first argument) of the TAG directive"),P.call(e.tagMap,i)&&ce(e,'there is a previously declared suffix for "'+i+'" tag handle'),V.test(r)||ce(e,"ill-formed tag prefix (second argument) of the TAG directive");try{r=decodeURIComponent(r)}catch(t){ce(e,"tag prefix is malformed: "+r)}e.tagMap[i]=r}};function pe(e,t,n,i){var r,o,a,l;if(t1&&(e.result+=n.repeat("\n",t-1))}function be(e,t){var n,i,r=e.tag,o=e.anchor,a=[],l=!1;if(-1!==e.firstTabInLine)return!1;for(null!==e.anchor&&(e.anchorMap[e.anchor]=a),i=e.input.charCodeAt(e.position);0!==i&&(-1!==e.firstTabInLine&&(e.position=e.firstTabInLine,ce(e,"tab characters must not be used in indentation")),45===i)&&z(e.input.charCodeAt(e.position+1));)if(l=!0,e.position++,ge(e,!0,-1)&&e.lineIndent<=t)a.push(null),i=e.input.charCodeAt(e.position);else if(n=e.line,we(e,t,3,!1,!0),a.push(e.result),ge(e,!0,-1),i=e.input.charCodeAt(e.position),(e.line===n||e.lineIndent>t)&&0!==i)ce(e,"bad indentation of a sequence entry");else if(e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt?g=1:e.lineIndent===t?g=0:e.lineIndentt)&&(y&&(a=e.line,l=e.lineStart,c=e.position),we(e,t,4,!0,r)&&(y?g=e.result:m=e.result),y||(de(e,f,d,h,g,m,a,l,c),h=g=m=null),ge(e,!0,-1),s=e.input.charCodeAt(e.position)),(e.line===o||e.lineIndent>t)&&0!==s)ce(e,"bad indentation of a mapping entry");else if(e.lineIndent=0))break;0===o?ce(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):u?ce(e,"repeat of an indentation width identifier"):(p=t+o-1,u=!0)}if(Q(a)){do{a=e.input.charCodeAt(++e.position)}while(Q(a));if(35===a)do{a=e.input.charCodeAt(++e.position)}while(!J(a)&&0!==a)}for(;0!==a;){for(he(e),e.lineIndent=0,a=e.input.charCodeAt(e.position);(!u||e.lineIndentp&&(p=e.lineIndent),J(a))f++;else{if(e.lineIndent0){for(r=a,o=0;r>0;r--)(a=ee(l=e.input.charCodeAt(++e.position)))>=0?o=(o<<4)+a:ce(e,"expected hexadecimal character");e.result+=ne(o),e.position++}else ce(e,"unknown escape sequence");n=i=e.position}else J(l)?(pe(e,n,i,!0),ye(e,ge(e,!1,t)),n=i=e.position):e.position===e.lineStart&&me(e)?ce(e,"unexpected end of the document within a double quoted scalar"):(e.position++,i=e.position)}ce(e,"unexpected end of the stream within a double quoted scalar")}(e,d)?y=!0:!function(e){var t,n,i;if(42!==(i=e.input.charCodeAt(e.position)))return!1;for(i=e.input.charCodeAt(++e.position),t=e.position;0!==i&&!z(i)&&!X(i);)i=e.input.charCodeAt(++e.position);return e.position===t&&ce(e,"name of an alias node must contain at least one character"),n=e.input.slice(t,e.position),P.call(e.anchorMap,n)||ce(e,'unidentified alias "'+n+'"'),e.result=e.anchorMap[n],ge(e,!0,-1),!0}(e)?function(e,t,n){var i,r,o,a,l,c,s,u,p=e.kind,f=e.result;if(z(u=e.input.charCodeAt(e.position))||X(u)||35===u||38===u||42===u||33===u||124===u||62===u||39===u||34===u||37===u||64===u||96===u)return!1;if((63===u||45===u)&&(z(i=e.input.charCodeAt(e.position+1))||n&&X(i)))return!1;for(e.kind="scalar",e.result="",r=o=e.position,a=!1;0!==u;){if(58===u){if(z(i=e.input.charCodeAt(e.position+1))||n&&X(i))break}else if(35===u){if(z(e.input.charCodeAt(e.position-1)))break}else{if(e.position===e.lineStart&&me(e)||n&&X(u))break;if(J(u)){if(l=e.line,c=e.lineStart,s=e.lineIndent,ge(e,!1,-1),e.lineIndent>=t){a=!0,u=e.input.charCodeAt(e.position);continue}e.position=o,e.line=l,e.lineStart=c,e.lineIndent=s;break}}a&&(pe(e,r,o,!1),ye(e,e.line-l),r=o=e.position,a=!1),Q(u)||(o=e.position+1),u=e.input.charCodeAt(++e.position)}return pe(e,r,o,!1),!!e.result||(e.kind=p,e.result=f,!1)}(e,d,1===i)&&(y=!0,null===e.tag&&(e.tag="?")):(y=!0,null===e.tag&&null===e.anchor||ce(e,"alias node should not have any properties")),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):0===g&&(y=c&&be(e,h))),null===e.tag)null!==e.anchor&&(e.anchorMap[e.anchor]=e.result);else if("?"===e.tag){for(null!==e.result&&"scalar"!==e.kind&&ce(e,'unacceptable node kind for ! tag; it should be "scalar", not "'+e.kind+'"'),s=0,u=e.implicitTypes.length;s"),null!==e.result&&f.kind!==e.kind&&ce(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+f.kind+'", not "'+e.kind+'"'),f.resolve(e.result,e.tag)?(e.result=f.construct(e.result,e.tag),null!==e.anchor&&(e.anchorMap[e.anchor]=e.result)):ce(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return null!==e.listener&&e.listener("close",e),null!==e.tag||null!==e.anchor||y}function ke(e){var t,n,i,r,o=e.position,a=!1;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);0!==(r=e.input.charCodeAt(e.position))&&(ge(e,!0,-1),r=e.input.charCodeAt(e.position),!(e.lineIndent>0||37!==r));){for(a=!0,r=e.input.charCodeAt(++e.position),t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);for(i=[],(n=e.input.slice(t,e.position)).length<1&&ce(e,"directive name must not be less than one character in length");0!==r;){for(;Q(r);)r=e.input.charCodeAt(++e.position);if(35===r){do{r=e.input.charCodeAt(++e.position)}while(0!==r&&!J(r));break}if(J(r))break;for(t=e.position;0!==r&&!z(r);)r=e.input.charCodeAt(++e.position);i.push(e.input.slice(t,e.position))}0!==r&&he(e),P.call(ue,n)?ue[n](e,n,i):se(e,'unknown document directive "'+n+'"')}ge(e,!0,-1),0===e.lineIndent&&45===e.input.charCodeAt(e.position)&&45===e.input.charCodeAt(e.position+1)&&45===e.input.charCodeAt(e.position+2)?(e.position+=3,ge(e,!0,-1)):a&&ce(e,"directives end mark is expected"),we(e,e.lineIndent-1,4,!1,!0),ge(e,!0,-1),e.checkLineBreaks&&H.test(e.input.slice(o,e.position))&&se(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&me(e)?46===e.input.charCodeAt(e.position)&&(e.position+=3,ge(e,!0,-1)):e.position=55296&&i<=56319&&t+1=56320&&n<=57343?1024*(i-55296)+n-56320+65536:i}function Re(e){return/^\n* /.test(e)}function Be(e,t,n,i,r,o,a,l){var c,s,u=0,p=null,f=!1,d=!1,h=-1!==i,g=-1,m=De(s=Ye(e,0))&&s!==Oe&&!_e(s)&&45!==s&&63!==s&&58!==s&&44!==s&&91!==s&&93!==s&&123!==s&&125!==s&&35!==s&&38!==s&&42!==s&&33!==s&&124!==s&&61!==s&&62!==s&&39!==s&&34!==s&&37!==s&&64!==s&&96!==s&&function(e){return!_e(e)&&58!==e}(Ye(e,e.length-1));if(t||a)for(c=0;c=65536?c+=2:c++){if(!De(u=Ye(e,c)))return 5;m=m&&qe(u,p,l),p=u}else{for(c=0;c=65536?c+=2:c++){if(10===(u=Ye(e,c)))f=!0,h&&(d=d||c-g-1>i&&" "!==e[g+1],g=c);else if(!De(u))return 5;m=m&&qe(u,p,l),p=u}d=d||h&&c-g-1>i&&" "!==e[g+1]}return f||d?n>9&&Re(e)?5:a?2===o?5:2:d?4:3:!m||a||r(e)?2===o?5:2:1}function Ke(e,t,n,i,r){e.dump=function(){if(0===t.length)return 2===e.quotingType?'""':"''";if(!e.noCompatMode&&(-1!==Te.indexOf(t)||Ne.test(t)))return 2===e.quotingType?'"'+t+'"':"'"+t+"'";var a=e.indent*Math.max(1,n),l=-1===e.lineWidth?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-a),c=i||e.flowLevel>-1&&n>=e.flowLevel;switch(Be(t,c,e.indent,l,(function(t){return function(e,t){var n,i;for(n=0,i=e.implicitTypes.length;n"+Pe(t,e.indent)+We(Me(function(e,t){var n,i,r=/(\n+)([^\n]*)/g,o=(l=e.indexOf("\n"),l=-1!==l?l:e.length,r.lastIndex=l,He(e.slice(0,l),t)),a="\n"===e[0]||" "===e[0];var l;for(;i=r.exec(e);){var c=i[1],s=i[2];n=" "===s[0],o+=c+(a||n||""===s?"":"\n")+He(s,t),a=n}return o}(t,l),a));case 5:return'"'+function(e){for(var t,n="",i=0,r=0;r=65536?r+=2:r++)i=Ye(e,r),!(t=je[i])&&De(i)?(n+=e[r],i>=65536&&(n+=e[r+1])):n+=t||Fe(i);return n}(t)+'"';default:throw new o("impossible error: invalid scalar style")}}()}function Pe(e,t){var n=Re(e)?String(t):"",i="\n"===e[e.length-1];return n+(i&&("\n"===e[e.length-2]||"\n"===e)?"+":i?"":"-")+"\n"}function We(e){return"\n"===e[e.length-1]?e.slice(0,-1):e}function He(e,t){if(""===e||" "===e[0])return e;for(var n,i,r=/ [^ ]/g,o=0,a=0,l=0,c="";n=r.exec(e);)(l=n.index)-o>t&&(i=a>o?a:l,c+="\n"+e.slice(o,i),o=i+1),a=l;return c+="\n",e.length-o>t&&a>o?c+=e.slice(o,a)+"\n"+e.slice(a+1):c+=e.slice(o),c.slice(1)}function $e(e,t,n,i){var r,o,a,l="",c=e.tag;for(r=0,o=n.length;r tag resolver accepts not "'+s+'" style');i=c.represent[s](t,s)}e.dump=i}return!0}return!1}function Ve(e,t,n,i,r,a,l){e.tag=null,e.dump=n,Ge(e,n,!1)||Ge(e,n,!0);var c,s=Ie.call(e.dump),u=i;i&&(i=e.flowLevel<0||e.flowLevel>t);var p,f,d="[object Object]"===s||"[object Array]"===s;if(d&&(f=-1!==(p=e.duplicates.indexOf(n))),(null!==e.tag&&"?"!==e.tag||f||2!==e.indent&&t>0)&&(r=!1),f&&e.usedDuplicates[p])e.dump="*ref_"+p;else{if(d&&f&&!e.usedDuplicates[p]&&(e.usedDuplicates[p]=!0),"[object Object]"===s)i&&0!==Object.keys(e.dump).length?(!function(e,t,n,i){var r,a,l,c,s,u,p="",f=e.tag,d=Object.keys(n);if(!0===e.sortKeys)d.sort();else if("function"==typeof e.sortKeys)d.sort(e.sortKeys);else if(e.sortKeys)throw new o("sortKeys must be a boolean or a function");for(r=0,a=d.length;r1024)&&(e.dump&&10===e.dump.charCodeAt(0)?u+="?":u+="? "),u+=e.dump,s&&(u+=Le(e,t)),Ve(e,t+1,c,!0,s)&&(e.dump&&10===e.dump.charCodeAt(0)?u+=":":u+=": ",p+=u+=e.dump));e.tag=f,e.dump=p||"{}"}(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a,l,c="",s=e.tag,u=Object.keys(n);for(i=0,r=u.length;i1024&&(l+="? "),l+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),Ve(e,t,a,!1,!1)&&(c+=l+=e.dump));e.tag=s,e.dump="{"+c+"}"}(e,t,e.dump),f&&(e.dump="&ref_"+p+" "+e.dump));else if("[object Array]"===s)i&&0!==e.dump.length?(e.noArrayIndent&&!l&&t>0?$e(e,t-1,e.dump,r):$e(e,t,e.dump,r),f&&(e.dump="&ref_"+p+e.dump)):(!function(e,t,n){var i,r,o,a="",l=e.tag;for(i=0,r=n.length;i",e.dump=c+" "+e.dump)}return!0}function Ze(e,t){var n,i,r=[],o=[];for(Je(e,r,o),n=0,i=o.length;n tag resolver accepts not "' + style + '" style'); @@ -3622,7 +3623,7 @@ function writeNode(state, level, object, block, compact, iskey, isblockseq) { detectType(state, object, true); } - var type = _toString$2.call(state.dump); + var type = _toString.call(state.dump); var inblock = block; var tagStr; @@ -3764,10 +3765,10 @@ function inspectNode(object, objects, duplicatesIndexes) { } } -function dump(input, options) { +function dump$1(input, options) { options = options || {}; - var state = new State$1(options); + var state = new State(options); if (!state.noRefs) getDuplicateReferences(input, state); @@ -3782,7 +3783,7 @@ function dump(input, options) { return ''; } -var dump_1 = dump; +var dump_1 = dump$1; var dumper = { dump: dump_1 @@ -3796,16 +3797,33 @@ function renamed(from, to) { } -var Type$1 = type; -var Schema$1 = schema; +var Type = type; +var Schema = schema; var FAILSAFE_SCHEMA = failsafe; var JSON_SCHEMA = json; var CORE_SCHEMA = core; var DEFAULT_SCHEMA = _default; -var load$1 = loader.load; -var loadAll$1 = loader.loadAll; -var dump$1 = dumper.dump; -var YAMLException$1 = exception; +var load = loader.load; +var loadAll = loader.loadAll; +var dump = dumper.dump; +var YAMLException = exception; + +// Re-export all types in case user wants to create custom schema +var types = { + binary: binary, + float: float, + map: map, + null: _null, + pairs: pairs, + set: set, + timestamp: timestamp, + bool: bool, + int: int, + merge: merge, + omap: omap, + seq: seq, + str: str +}; // Removed functions from JS-YAML 3.0.x var safeLoad = renamed('safeLoad', 'load'); @@ -3813,20 +3831,21 @@ var safeLoadAll = renamed('safeLoadAll', 'loadAll'); var safeDump = renamed('safeDump', 'dump'); var jsYaml = { - Type: Type$1, - Schema: Schema$1, + Type: Type, + Schema: Schema, FAILSAFE_SCHEMA: FAILSAFE_SCHEMA, JSON_SCHEMA: JSON_SCHEMA, CORE_SCHEMA: CORE_SCHEMA, DEFAULT_SCHEMA: DEFAULT_SCHEMA, - load: load$1, - loadAll: loadAll$1, - dump: dump$1, - YAMLException: YAMLException$1, + load: load, + loadAll: loadAll, + dump: dump, + YAMLException: YAMLException, + types: types, safeLoad: safeLoad, safeLoadAll: safeLoadAll, safeDump: safeDump }; export default jsYaml; -export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema$1 as Schema, Type$1 as Type, YAMLException$1 as YAMLException, dump$1 as dump, load$1 as load, loadAll$1 as loadAll, safeDump, safeLoad, safeLoadAll }; +export { CORE_SCHEMA, DEFAULT_SCHEMA, FAILSAFE_SCHEMA, JSON_SCHEMA, Schema, Type, YAMLException, dump, load, loadAll, safeDump, safeLoad, safeLoadAll, types }; diff --git a/node_modules/js-yaml/index.js b/node_modules/js-yaml/index.js index 486f6af..bcb7eba 100644 --- a/node_modules/js-yaml/index.js +++ b/node_modules/js-yaml/index.js @@ -24,6 +24,23 @@ module.exports.loadAll = loader.loadAll; module.exports.dump = dumper.dump; module.exports.YAMLException = require('./lib/exception'); +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: require('./lib/type/binary'), + float: require('./lib/type/float'), + map: require('./lib/type/map'), + null: require('./lib/type/null'), + pairs: require('./lib/type/pairs'), + set: require('./lib/type/set'), + timestamp: require('./lib/type/timestamp'), + bool: require('./lib/type/bool'), + int: require('./lib/type/int'), + merge: require('./lib/type/merge'), + omap: require('./lib/type/omap'), + seq: require('./lib/type/seq'), + str: require('./lib/type/str') +}; + // Removed functions from JS-YAML 3.0.x module.exports.safeLoad = renamed('safeLoad', 'load'); module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); diff --git a/node_modules/js-yaml/lib/schema.js b/node_modules/js-yaml/lib/schema.js index ae19356..65b41f4 100644 --- a/node_modules/js-yaml/lib/schema.js +++ b/node_modules/js-yaml/lib/schema.js @@ -6,25 +6,25 @@ var YAMLException = require('./exception'); var Type = require('./type'); -function compileList(schema, name, result) { - var exclude = []; +function compileList(schema, name) { + var result = []; schema[name].forEach(function (currentType) { + var newIndex = result.length; + result.forEach(function (previousType, previousIndex) { if (previousType.tag === currentType.tag && previousType.kind === currentType.kind && previousType.multi === currentType.multi) { - exclude.push(previousIndex); + newIndex = previousIndex; } }); - result.push(currentType); + result[newIndex] = currentType; }); - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); + return result; } @@ -110,8 +110,8 @@ Schema.prototype.extend = function extend(definition) { result.implicit = (this.implicit || []).concat(implicit); result.explicit = (this.explicit || []).concat(explicit); - result.compiledImplicit = compileList(result, 'implicit', []); - result.compiledExplicit = compileList(result, 'explicit', []); + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); return result; diff --git a/node_modules/js-yaml/lib/type.js b/node_modules/js-yaml/lib/type.js index 5928702..5e57877 100644 --- a/node_modules/js-yaml/lib/type.js +++ b/node_modules/js-yaml/lib/type.js @@ -45,6 +45,7 @@ function Type(tag, options) { }); // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later this.tag = tag; this.kind = options['kind'] || null; this.resolve = options['resolve'] || function () { return true; }; diff --git a/node_modules/js-yaml/package.json b/node_modules/js-yaml/package.json index ea84b6d..17574da 100644 --- a/node_modules/js-yaml/package.json +++ b/node_modules/js-yaml/package.json @@ -1,6 +1,6 @@ { "name": "js-yaml", - "version": "4.0.0", + "version": "4.1.0", "description": "YAML 1.2 parser and serializer", "keywords": [ "yaml", diff --git a/node_modules/log-symbols/index.d.ts b/node_modules/log-symbols/index.d.ts index 4d3b7d1..8e4bdc5 100644 --- a/node_modules/log-symbols/index.d.ts +++ b/node_modules/log-symbols/index.d.ts @@ -8,8 +8,8 @@ Includes fallbacks for Windows CMD which only supports a [limited character set] import logSymbols = require('log-symbols'); console.log(logSymbols.success, 'Finished successfully!'); -// On good OSes: ✔ Finished successfully! -// On Windows: √ Finished successfully! +// Terminals with Unicode support: ✔ Finished successfully! +// Terminals without Unicode support: √ Finished successfully! ``` */ declare const logSymbols: { diff --git a/node_modules/log-symbols/index.js b/node_modules/log-symbols/index.js index 247bb59..12347e0 100644 --- a/node_modules/log-symbols/index.js +++ b/node_modules/log-symbols/index.js @@ -1,7 +1,6 @@ 'use strict'; const chalk = require('chalk'); - -const isSupported = process.platform !== 'win32' || process.env.CI || process.env.TERM === 'xterm-256color'; +const isUnicodeSupported = require('is-unicode-supported'); const main = { info: chalk.blue('ℹ'), @@ -10,11 +9,11 @@ const main = { error: chalk.red('✖') }; -const fallbacks = { +const fallback = { info: chalk.blue('i'), success: chalk.green('√'), warning: chalk.yellow('‼'), error: chalk.red('×') }; -module.exports = isSupported ? main : fallbacks; +module.exports = isUnicodeSupported() ? main : fallback; diff --git a/node_modules/log-symbols/package.json b/node_modules/log-symbols/package.json index 3a331d7..b9886e4 100644 --- a/node_modules/log-symbols/package.json +++ b/node_modules/log-symbols/package.json @@ -1,9 +1,10 @@ { "name": "log-symbols", - "version": "4.0.0", + "version": "4.1.0", "description": "Colored symbols for various log levels. Example: `✔︎ Success`", "license": "MIT", "repository": "sindresorhus/log-symbols", + "funding": "https://github.com/sponsors/sindresorhus", "author": { "name": "Sindre Sorhus", "email": "sindresorhus@gmail.com", @@ -38,13 +39,14 @@ "stdout" ], "dependencies": { - "chalk": "^4.0.0" + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" }, "devDependencies": { - "ava": "^3.7.1", + "ava": "^2.4.0", "strip-ansi": "^6.0.0", - "tsd": "^0.11.0", - "xo": "^0.30.0" + "tsd": "^0.14.0", + "xo": "^0.38.2" }, "browser": "browser.js" } diff --git a/node_modules/log-symbols/readme.md b/node_modules/log-symbols/readme.md index 9c34cc8..d464eae 100644 --- a/node_modules/log-symbols/readme.md +++ b/node_modules/log-symbols/readme.md @@ -1,4 +1,4 @@ -# log-symbols [![Build Status](https://travis-ci.com/sindresorhus/log-symbols.svg?branch=master)](https://travis-ci.com/sindresorhus/log-symbols) +# log-symbols @@ -18,8 +18,8 @@ $ npm install log-symbols const logSymbols = require('log-symbols'); console.log(logSymbols.success, 'Finished successfully!'); -// On good OSes: ✔ Finished successfully! -// On Windows: √ Finished successfully! +// Terminals with Unicode support: ✔ Finished successfully! +// Terminals without Unicode support: √ Finished successfully! ``` ## API diff --git a/node_modules/mixme/CHANGELOG.md b/node_modules/mixme/CHANGELOG.md deleted file mode 100644 index b9b123b..0000000 --- a/node_modules/mixme/CHANGELOG.md +++ /dev/null @@ -1,75 +0,0 @@ -# Changelog - -All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. - -### [0.5.4](https://github.com/adaltas/node-mixme/compare/v0.5.3...v0.5.4) (2021-09-21) - - -### Bug Fixes - -* remove constructor from excluded properties ([cf6af53](https://github.com/adaltas/node-mixme/commit/cf6af53c51ada2d3189dea5a25b8a9ee793d8197)) - -## [0.5.3](https://github.com/adaltas/node-mixme/compare/v0.5.2...v0.5.3) (2021-09-21) - - -### Bug Fixes - -* relax properties excluded from copy ([d22c51a](https://github.com/adaltas/node-mixme/commit/d22c51a16e9da10d34ac52ea9189ef75d951c980)) - -## Version 0.5.2 - -* fix: prevent code injection in copying properties - -## Version 0.5.1 - -* fix: dont pollute object proto #1 -* chore: latest dependencies - -## Version 0.5.0 - -* feat: support object with null prototype - -## Version 0.4.0 - -* compare: new function - -## Version 0.3.5 - -* readme: fix examples - -## Version 0.3.3 - -* package: update adaltas url - -## Version 0.3.2 - -* package: use files instead of npmignore - -## Version 0.3.1 - -* mutate: immutable deep copy of object in arrays - -## Version 0.3.0 - -* project: csj, esm and umd generation -* project: ignore lock files - -## Version 0.2.0 - -* snake_case: clone object with converted properties -* merge: fix array and object merge -* is_object_literal: new function - -## Version 0.1.0 - -* clone: new function -* readme: add author company - -## Version 0.1.0 - -* package: support node version above 6 -* readme: update sample - -## Version 0.0.1 - -* package: original commit diff --git a/node_modules/mixme/README.md b/node_modules/mixme/README.md deleted file mode 100644 index 49a5649..0000000 --- a/node_modules/mixme/README.md +++ /dev/null @@ -1,115 +0,0 @@ - -# Node.js mixme - -[![Build Status](https://secure.travis-ci.org/adaltas/node-mixme.png)](http://travis-ci.org/adaltas/node-mixme) - -Merge multiple object recursively. The last object takes precedence over the -previous ones. Only objects are merged. Arrays are overwritten. - -## API - -### Function `merge(...data)` - -The API is minimalist, pass as many literal objects as you wish, they will all be -merged. This function is immutable, the source objects won't be altered. - -```js -const {merge} = require('mixme') -const target = merge({a: '1'}, {b: '2'}); -// target is {a: '1', b: '2'} -``` - -### Function `mutate(...data)` - -Use the `mutate` function to enrich an object. The first argument will be mutated: - -```js -const {mutate} = require('mixme') -const source = {a: '1'}; -const target = mutate(source, {b: '2'}); -// target is the same as source -// source and target are now {a: '1', b: '2'} -``` - -### Function `clone(data)` - -It is possible to clone a literal object by simply calling `mixme` with this object as the first argument. Use the `clone` function in case you wish to clone any type of argument including arrays: - -```js -const {clone} = require('mixme') -const target = clone(['a', 'b']) -// target is now a copy of source -``` - -### Function `is_object_literal(object)` - -Use the `is_object_literal` function to ensure an object is literate. - -```js -const {is_object_literal} = require('mixme') -// {} is literate -is_object_literal({}) -// error is not literate -is_object_literal(new Error('Catch me')) -// Array is not literate -is_object_literal([]) -``` - -### Function `snake_case(object)` - -Clone a object and convert its properties into snake case. - -```js -const {snake_case} = require('mixme') -snake_case({aA: '1', bB: cC: '2'}) -// Return {a_a: '1', b_b: c_c: '2'} -``` - -### Function `compare(item_1, item_2)` - -Compare two items and return true if their values match. - -```js -const {compare} = require('mixme') -compare([{a: 1}], [{a: 1}]) -// Return true -compare({a: 1}, {a: 2}) -// Return false -``` - -## Example - -Create a new object from two objects: - -``` -obj1 = { a_key: 'a value', b_key: 'b value'} -obj2 = { b_key: 'new b value'} -result = misc.merge obj1, obj2 -assert.eql result.b_key, 'new b value' -``` - -Merge an existing object with a second one: - -``` -obj1 = { a_key: 'a value', b_key: 'b value'}; -obj2 = { b_key: 'new b value'}; -result = mixme.mutate obj1, obj2 -assert.eql result, obj1 -assert.eql obj1.b_key, 'new b value' -``` - -## Testing - -Clone the repo, install the development dependencies and run the tests: - -```bash -git clone http://github.com/wdavidw/node-mixme.git . -npm install -make test -``` - -## Contributors - -* David Worms: - -This package is developed by [Adaltas](http://www.adaltas.com). diff --git a/node_modules/mixme/dist/mixme.cjs.js b/node_modules/mixme/dist/mixme.cjs.js deleted file mode 100644 index f7bd484..0000000 --- a/node_modules/mixme/dist/mixme.cjs.js +++ /dev/null @@ -1,187 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, '__esModule', { value: true }); - -function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -// Generated by CoffeeScript 2.6.0 -var _snake_case; exports.clone = void 0; exports.compare = void 0; exports.is_object = void 0; exports.is_object_literal = void 0; exports.merge = void 0; exports.mutate = void 0; exports.snake_case = void 0; - -exports.merge = function merge() { - return exports.mutate.apply(void 0, [{}].concat(Array.prototype.slice.call(arguments))); -}; - -exports.clone = function clone(target) { - if (Array.isArray(target)) { - return target.map(function (element) { - return exports.clone(element); - }); - } else if (target && _typeof(target) === 'object') { - return exports.mutate({}, target); - } else { - return target; - } -}; - -exports.mutate = function mutate() { - var i, j, name, ref, source, target, v; - target = arguments[0]; - - for (i = j = 1, ref = arguments.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (/__proto__|prototype/.test(name)) { - // See - // https://github.com/adaltas/node-mixme/issues/1 - // https://github.com/adaltas/node-mixme/issues/2 - // continue if /__proto__|constructor|prototype|eval|function|\*|\+|;|\s|\(|\)|!/.test name - // Unless proven wrong, I consider ok to copy any properties named eval - // or function, we are not executing those, only copying. - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; -}; - -exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; diff --git a/node_modules/mixme/dist/mixme.esm.js b/node_modules/mixme/dist/mixme.esm.js deleted file mode 100644 index 8d2adbe..0000000 --- a/node_modules/mixme/dist/mixme.esm.js +++ /dev/null @@ -1,185 +0,0 @@ -function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); -} - -// Generated by CoffeeScript 2.6.0 -var _snake_case, _clone, _compare, is_object, is_object_literal, merge, _mutate, _snake_case2; - -merge = function merge() { - return _mutate.apply(void 0, [{}].concat(Array.prototype.slice.call(arguments))); -}; - -_clone = function clone(target) { - if (Array.isArray(target)) { - return target.map(function (element) { - return _clone(element); - }); - } else if (target && _typeof(target) === 'object') { - return _mutate({}, target); - } else { - return target; - } -}; - -_mutate = function mutate() { - var i, j, name, ref, source, target, v; - target = arguments[0]; - - for (i = j = 1, ref = arguments.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (is_object_literal(source)) { - if (!is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (/__proto__|prototype/.test(name)) { - // See - // https://github.com/adaltas/node-mixme/issues/1 - // https://github.com/adaltas/node-mixme/issues/2 - // continue if /__proto__|constructor|prototype|eval|function|\*|\+|;|\s|\(|\)|!/.test name - // Unless proven wrong, I consider ok to copy any properties named eval - // or function, we are not executing those, only copying. - continue; - } - - target[name] = _mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(_mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -_snake_case2 = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = _snake_case2(src, u); - } - } else { - target = source; - } - - return target; -}; - -_compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (is_object_literal(el1)) { - if (!is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!_compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!_compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; - -export { _clone as clone, _compare as compare, is_object, is_object_literal, merge, _mutate as mutate, _snake_case2 as snake_case }; diff --git a/node_modules/mixme/dist/mixme.umd.js b/node_modules/mixme/dist/mixme.umd.js deleted file mode 100644 index aa6a7ba..0000000 --- a/node_modules/mixme/dist/mixme.umd.js +++ /dev/null @@ -1,193 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.mixme = {})); -}(this, (function (exports) { 'use strict'; - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - // Generated by CoffeeScript 2.6.0 - var _snake_case; exports.clone = void 0; exports.compare = void 0; exports.is_object = void 0; exports.is_object_literal = void 0; exports.merge = void 0; exports.mutate = void 0; exports.snake_case = void 0; - - exports.merge = function merge() { - return exports.mutate.apply(void 0, [{}].concat(Array.prototype.slice.call(arguments))); - }; - - exports.clone = function clone(target) { - if (Array.isArray(target)) { - return target.map(function (element) { - return exports.clone(element); - }); - } else if (target && _typeof(target) === 'object') { - return exports.mutate({}, target); - } else { - return target; - } - }; - - exports.mutate = function mutate() { - var i, j, name, ref, source, target, v; - target = arguments[0]; - - for (i = j = 1, ref = arguments.length; 1 <= ref ? j < ref : j > ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (/__proto__|prototype/.test(name)) { - // See - // https://github.com/adaltas/node-mixme/issues/1 - // https://github.com/adaltas/node-mixme/issues/2 - // continue if /__proto__|constructor|prototype|eval|function|\*|\+|;|\s|\(|\)|!/.test name - // Unless proven wrong, I consider ok to copy any properties named eval - // or function, we are not executing those, only copying. - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; - }; - - exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; - }; - - exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; - }; - - _snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); - }; - - exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); - }; - - exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } - }; - - Object.defineProperty(exports, '__esModule', { value: true }); - -}))); diff --git a/node_modules/mixme/package.json b/node_modules/mixme/package.json deleted file mode 100644 index 7893dc9..0000000 --- a/node_modules/mixme/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "mixme", - "description": "A library for recursive merging of Javascript objects", - "version": "0.5.4", - "author": "David Worms (https://www.adaltas.com)", - "contributors": [], - "devDependencies": { - "@commitlint/cli": "^13.1.0", - "@commitlint/config-conventional": "^13.1.0", - "@babel/core": "^7.15.5", - "@babel/preset-env": "^7.15.6", - "coffeescript": "^2.6.0", - "husky": "^7.0.2", - "mocha": "^9.1.1", - "pinst": "^2.1.6", - "rollup": "^2.56.3", - "rollup-plugin-babel": "^4.4.0", - "should": "^13.2.3", - "standard-version": "^9.3.1" - }, - "engines": { - "node": ">= 8.0.0" - }, - "homepage": "https://github.com/adaltas/node-mixme", - "bugs": { - "url": "https://github.com/adaltas/node-mixme/issues" - }, - "keywords": [ - "merge", - "deep", - "extend", - "copy", - "clone", - "recursive" - ], - "files": [ - "/dist" - ], - "license": "MIT", - "main": "dist/mixme.cjs.js", - "module": "dist/mixme.esm.js", - "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "./coffee.config.js" - ], - "inline-diffs": true, - "timeout": 40000, - "reporter": "spec", - "recursive": true - }, - "repository": { - "type": "git", - "url": "https://github.com/adaltas/node-mixme.git" - }, - "scripts": { - "_postinstall": "husky install", - "prepublishOnly": "pinst --disable", - "postpublish": "pinst --enable", - "build": "coffee -b -o lib src src && rollup -c", - "pretest": "npm run build", - "test": "mocha 'test/**/*.coffee'", - "release": "standard-version", - "release:minor": "standard-version --release-as minor", - "release:patch": "standard-version --release-as patch", - "release:major": "standard-version --release-as major" - } -} diff --git a/node_modules/mocha/CHANGELOG.md b/node_modules/mocha/CHANGELOG.md deleted file mode 100644 index 3628f2e..0000000 --- a/node_modules/mocha/CHANGELOG.md +++ /dev/null @@ -1,931 +0,0 @@ -# 8.4.0 / 2021-05-07 - -## :tada: Enhancements - -- [#4502](https://github.com/mochajs/mocha/issues/4502): CLI file parsing errors now have error codes ([**@evaline-ju**](https://github.com/evaline-ju)) - -## :bug: Fixes - -- [#4614](https://github.com/mochajs/mocha/issues/4614): Watch: fix crash when reloading files ([**@outsideris**](https://github.com/outsideris)) - -## :book: Documentation - -- [#4630](https://github.com/mochajs/mocha/issues/4630): Add `options.require` to Mocha constructor for `root hook` plugins on parallel runs ([**@juergba**](https://github.com/juergba)) -- [#4617](https://github.com/mochajs/mocha/issues/4617): Dynamically generating tests with `top-level await` and ESM test files ([**@juergba**](https://github.com/juergba)) -- [#4608](https://github.com/mochajs/mocha/issues/4608): Update default file extensions ([**@outsideris**](https://github.com/outsideris)) - -Also thanks to [**@outsideris**](https://github.com/outsideris) for various improvements on our GH actions workflows. - -# 8.3.2 / 2021-03-12 - -## :bug: Fixes - -- [#4599](https://github.com/mochajs/mocha/issues/4599): Fix regression in `require` interface ([**@alexander-fenster**](https://github.com/alexander-fenster)) - -## :book: Documentation - -- [#4601](https://github.com/mochajs/mocha/issues/4601): Add build to GH actions run ([**@christian-bromann**](https://github.com/christian-bromann)) -- [#4596](https://github.com/mochajs/mocha/issues/4596): Filter active sponsors/backers ([**@juergba**](https://github.com/juergba)) -- [#4225](https://github.com/mochajs/mocha/issues/4225): Update config file examples ([**@pkuczynski**](https://github.com/pkuczynski)) - -# 8.3.1 / 2021-03-06 - -## :bug: Fixes - -- [#4577](https://github.com/mochajs/mocha/issues/4577): Browser: fix `EvalError` caused by regenerator-runtime ([**@snoack**](https://github.com/snoack)) -- [#4574](https://github.com/mochajs/mocha/issues/4574): ESM: allow `import` from mocha in parallel mode ([**@nicojs**](https://github.com/nicojs)) - -# 8.3.0 / 2021-02-11 - -## :tada: Enhancements - -- [#4506](https://github.com/mochajs/mocha/issues/4506): Add error code for test timeout errors ([**@boneskull**](https://github.com/boneskull)) -- [#4112](https://github.com/mochajs/mocha/issues/4112): Add BigInt support to stringify util function ([**@JosejeSinohui**](https://github.com/JosejeSinohui)) - -## :bug: Fixes - -- [#4557](https://github.com/mochajs/mocha/issues/4557): Add file location when SyntaxError happens in ESM ([**@giltayar**](https://github.com/giltayar)) -- [#4521](https://github.com/mochajs/mocha/issues/4521): Fix `require` error when bundling Mocha with Webpack ([**@devhazem**](https://github.com/devhazem)) - -## :book: Documentation - -- [#4507](https://github.com/mochajs/mocha/issues/4507): Add support for typescript-style docstrings ([**@boneskull**](https://github.com/boneskull)) -- [#4503](https://github.com/mochajs/mocha/issues/4503): Add GH Actions workflow status badge ([**@outsideris**](https://github.com/outsideris)) -- [#4494](https://github.com/mochajs/mocha/issues/4494): Add example of generating tests dynamically with a closure ([**@maxwellgerber**](https://github.com/maxwellgerber)) - -## :nut_and_bolt: Other - -- [#4556](https://github.com/mochajs/mocha/issues/4556): Upgrade all dependencies to latest stable ([**@AviVahl**](https://github.com/AviVahl)) -- [#4543](https://github.com/mochajs/mocha/issues/4543): Update dependencies yargs and yargs-parser ([**@juergba**](https://github.com/juergba)) - -Also thanks to [**@outsideris**](https://github.com/outsideris) and [**@HyunSangHan**](https://github.com/HyunSangHan) for various fixes to our website and documentation. - -# 8.2.1 / 2020-11-02 - -Fixed stuff. - -## :bug: Fixes - -- [#4489](https://github.com/mochajs/mocha/issues/4489): Fix problematic handling of otherwise-unhandled `Promise` rejections and erroneous "`done()` called twice" errors ([**@boneskull**](https://github.com/boneskull)) -- [#4496](https://github.com/mochajs/mocha/issues/4496): Avoid `MaxListenersExceededWarning` in watch mode ([**@boneskull**](https://github.com/boneskull)) - -Also thanks to [**@akeating**](https://github.com/akeating) for a documentation fix! - -# 8.2.0 / 2020-10-16 - -The major feature added in v8.2.0 is addition of support for [_global fixtures_](https://mochajs.org/#global-fixtures). - -While Mocha has always had the ability to run setup and teardown via a hook (e.g., a `before()` at the top level of a test file) when running tests in serial, Mocha v8.0.0 added support for parallel runs. Parallel runs are _incompatible_ with this strategy; e.g., a top-level `before()` would only run for the file in which it was defined. - -With [global fixtures](https://mochajs.org/#global-fixtures), Mocha can now perform user-defined setup and teardown _regardless_ of mode, and these fixtures are guaranteed to run _once and only once_. This holds for parallel mode, serial mode, and even "watch" mode (the teardown will run once you hit Ctrl-C, just before Mocha finally exits). Tasks such as starting and stopping servers are well-suited to global fixtures, but not sharing resources--global fixtures do _not_ share context with your test files (but they do share context with each other). - -Here's a short example of usage: - -```js -// fixtures.js - -// can be async or not -exports.mochaGlobalSetup = async function() { - this.server = await startSomeServer({port: process.env.TEST_PORT}); - console.log(`server running on port ${this.server.port}`); -}; - -exports.mochaGlobalTeardown = async function() { - // the context (`this`) is shared, but not with the test files - await this.server.stop(); - console.log(`server on port ${this.server.port} stopped`); -}; - -// this file can contain root hook plugins as well! -// exports.mochaHooks = { ... } -``` - -Fixtures are loaded with `--require`, e.g., `mocha --require fixtures.js`. - -For detailed information, please see the [documentation](https://mochajs.org/#global-fixtures) and this handy-dandy [flowchart](https://mochajs.org/#test-fixture-decision-tree-wizard-thing) to help understand the differences between hooks, root hook plugins, and global fixtures (and when you should use each). - -## :tada: Enhancements - -- [#4308](https://github.com/mochajs/mocha/issues/4308): Support run-once [global setup & teardown fixtures](https://mochajs.org/#global-fixtures) ([**@boneskull**](https://github.com/boneskull)) -- [#4442](https://github.com/mochajs/mocha/issues/4442): Multi-part extensions (e.g., `test.js`) now usable with `--extension` option ([**@jordanstephens**](https://github.com/jordanstephens)) -- [#4472](https://github.com/mochajs/mocha/issues/4472): Leading dots (e.g., `.js`, `.test.js`) now usable with `--extension` option ([**@boneskull**](https://github.com/boneskull)) -- [#4434](https://github.com/mochajs/mocha/issues/4434): Output of `json` reporter now contains `speed` ("fast"/"medium"/"slow") property ([**@wwhurin**](https://github.com/wwhurin)) -- [#4464](https://github.com/mochajs/mocha/issues/4464): Errors thrown by serializer in parallel mode now have error codes ([**@evaline-ju**](https://github.com/evaline-ju)) - -_For implementors of custom reporters:_ - -- [#4409](https://github.com/mochajs/mocha/issues/4409): Parallel mode and custom reporter improvements ([**@boneskull**](https://github.com/boneskull)): - - Support custom worker-process-only reporters (`Runner.prototype.workerReporter()`); reporters should subclass `ParallelBufferedReporter` in `mocha/lib/nodejs/reporters/parallel-buffered` - - Allow opt-in of object reference matching for "sufficiently advanced" custom reporters (`Runner.prototype.linkPartialObjects()`); use if strict object equality is needed when consuming `Runner` event data - - Enable detection of parallel mode (`Runner.prototype.isParallelMode()`) - -## :bug: Fixes - -- [#4476](https://github.com/mochajs/mocha/issues/4476): Workaround for profoundly bizarre issue affecting `npm` v6.x causing some of Mocha's deps to be installed when `mocha` is present in a package's `devDependencies` and `npm install --production` is run the package's working copy ([**@boneskull**](https://github.com/boneskull)) -- [#4465](https://github.com/mochajs/mocha/issues/4465): Worker processes guaranteed (as opposed to "very likely") to exit before Mocha does; fixes a problem when using `nyc` with Mocha in parallel mode ([**@boneskull**](https://github.com/boneskull)) -- [#4419](https://github.com/mochajs/mocha/issues/4419): Restore `lookupFiles()` in `mocha/lib/utils`, which was broken/missing in Mocha v8.1.0; it now prints a deprecation warning (use `const {lookupFiles} = require('mocha/lib/cli')` instead) ([**@boneskull**](https://github.com/boneskull)) - -Thanks to [**@AviVahl**](https://github.com/AviVahl), [**@donghoon-song**](https://github.com/donghoon-song), [**@ValeriaVG**](https://github.com/ValeriaVG), [**@znarf**](https://github.com/znarf), [**@sujin-park**](https://github.com/sujin-park), and [**@majecty**](https://github.com/majecty) for other helpful contributions! - -# 8.1.3 / 2020-08-28 - -## :bug: Fixes - -- [#4425](https://github.com/mochajs/mocha/issues/4425): Restore `Mocha.utils.lookupFiles()` and Webpack compatibility (both broken since v8.1.0); `Mocha.utils.lookupFiles()` is now **deprecated** and will be removed in the next major revision of Mocha; use `require('mocha/lib/cli').lookupFiles` instead ([**@boneskull**](https://github.com/boneskull)) - -# 8.1.2 / 2020-08-25 - -## :bug: Fixes - -- [#4418](https://github.com/mochajs/mocha/issues/4418): Fix command-line flag incompatibility in forthcoming Node.js v14.9.0 ([**@boneskull**](https://github.com/boneskull)) -- [#4401](https://github.com/mochajs/mocha/issues/4401): Fix missing global variable in browser ([**@irrationnelle**](https://github.com/irrationnelle)) - -## :lock: Security Fixes - -- [#4396](https://github.com/mochajs/mocha/issues/4396): Update many dependencies ([**@GChuf**](https://github.com/GChuf)) - -## :book: Documentation - -- Various fixes by [**@sujin-park**](https://github.com/sujin-park), [**@wwhurin**](https://github.com/wwhurin) & [**@Donghoon759**](https://github.com/Donghoon759) - -# 8.1.1 / 2020-08-04 - -## :bug: Fixes - -- [#4394](https://github.com/mochajs/mocha/issues/4394): Fix regression wherein certain reporters did not correctly detect terminal width ([**@boneskull**](https://github.com/boneskull)) - -# 8.1.0 / 2020-07-30 - -In this release, Mocha now builds its browser bundle with Rollup and Babel, which will provide the project's codebase more flexibility and consistency. - -While we've been diligent about backwards compatibility, it's _possible_ consumers of the browser bundle will encounter differences (other than an increase in the bundle size). If you _do_ encounter an issue with the build, please [report it here](https://github.com/mochajs/mocha/issues/new?labels=unconfirmed-bug&template=bug_report.md&title=). - -This release **does not** drop support for IE11. - -Other community contributions came from [**@Devjeel**](https://github.com/Devjeel), [**@Harsha509**](https://github.com/Harsha509) and [**@sharath2106**](https://github.com/sharath2106). _Thank you_ to everyone who contributed to this release! - -> Do you read Korean? See [this guide to running parallel tests in Mocha](https://blog.outsider.ne.kr/1489), translated by our maintainer, [**@outsideris**](https://github.com/outsideris). - -## :tada: Enhancements - -- [#4287](https://github.com/mochajs/mocha/issues/4287): Use background colors with inline diffs for better visual distinction ([**@michael-brade**](https://github.com/michael-brade)) - -## :bug: Fixes - -- [#4328](https://github.com/mochajs/mocha/issues/4328): Fix "watch" mode when Mocha run in parallel ([**@boneskull**](https://github.com/boneskull)) -- [#4382](https://github.com/mochajs/mocha/issues/4382): Fix root hook execution in "watch" mode ([**@indieisaconcept**](https://github.com/indieisaconcept)) -- [#4383](https://github.com/mochajs/mocha/issues/4383): Consistent auto-generated hook titles ([**@cspotcode**](https://github.com/cspotcode)) -- [#4359](https://github.com/mochajs/mocha/issues/4359): Better errors when running `mocha init` ([**@boneskull**](https://github.com/boneskull)) -- [#4341](https://github.com/mochajs/mocha/issues/4341): Fix weirdness when using `delay` option in browser ([**@craigtaub**](https://github.com/craigtaub)) - -## :lock: Security Fixes - -- [#4378](https://github.com/mochajs/mocha/issues/4378), [#4333](https://github.com/mochajs/mocha/issues/4333): Update [javascript-serialize](https://npm.im/javascript-serialize) ([**@martinoppitz**](https://github.com/martinoppitz), [**@wnghdcjfe**](https://github.com/wnghdcjfe)) -- [#4354](https://github.com/mochajs/mocha/issues/4354): Update [yargs-unparser](https://npm.im/yargs-unparser) ([**@martinoppitz**](https://github.com/martinoppitz)) - -## :book: Documentation & Website - -- [#4173](https://github.com/mochajs/mocha/issues/4173): Document how to use `--enable-source-maps` with Mocha ([**@bcoe**](https://github.com/bcoe)) -- [#4343](https://github.com/mochajs/mocha/issues/4343): Clean up some API docs ([**@craigtaub**](https://github.com/craigtaub)) -- [#4318](https://github.com/mochajs/mocha/issues/4318): Sponsor images are now self-hosted ([**@Munter**](https://github.com/Munter)) - -## :nut_and_bolt: Other - -- [#4293](https://github.com/mochajs/mocha/issues/4293): Use Rollup and Babel in build pipeline; add source map to published files ([**@Munter**](https://github.com/Munter)) - -# 8.0.1 / 2020-06-10 - -The obligatory patch after a major. - -## :bug: Fixes - -- [#4328](https://github.com/mochajs/mocha/issues/4328): Fix `--parallel` when combined with `--watch` ([**@boneskull**](https://github.com/boneskull)) - -# 8.0.0 / 2020-06-10 - -In this major release, Mocha adds the ability to _run tests in parallel_. Better late than never! Please note the **breaking changes** detailed below. - -Let's welcome [**@giltayar**](https://github.com/giltayar) and [**@nicojs**](https://github.com/nicojs) to the maintenance team! - -## :boom: Breaking Changes - -- [#4164](https://github.com/mochajs/mocha/issues/4164): **Mocha v8.0.0 now requires Node.js v10.12.0 or newer.** Mocha no longer supports the Node.js v8.x line ("Carbon"), which entered End-of-Life at the end of 2019 ([**@UlisesGascon**](https://github.com/UlisesGascon)) - -- [#4175](https://github.com/mochajs/mocha/issues/4175): Having been deprecated with a warning since v7.0.0, **`mocha.opts` is no longer supported** ([**@juergba**](https://github.com/juergba)) - - :sparkles: **WORKAROUND:** Replace `mocha.opts` with a [configuration file](https://mochajs.org/#configuring-mocha-nodejs). - -- [#4260](https://github.com/mochajs/mocha/issues/4260): Remove `enableTimeout()` (`this.enableTimeout()`) from the context object ([**@craigtaub**](https://github.com/craigtaub)) - - :sparkles: **WORKAROUND:** Replace usage of `this.enableTimeout(false)` in your tests with `this.timeout(0)`. - -- [#4315](https://github.com/mochajs/mocha/issues/4315): The `spec` option no longer supports a comma-delimited list of files ([**@juergba**](https://github.com/juergba)) - - :sparkles: **WORKAROUND**: Use an array instead (e.g., `"spec": "foo.js,bar.js"` becomes `"spec": ["foo.js", "bar.js"]`). - -- [#4309](https://github.com/mochajs/mocha/issues/4309): Drop support for Node.js v13.x line, which is now End-of-Life ([**@juergba**](https://github.com/juergba)) - -- [#4282](https://github.com/mochajs/mocha/issues/4282): `--forbid-only` will throw an error even if exclusive tests are avoided via `--grep` or other means ([**@arvidOtt**](https://github.com/arvidOtt)) - -- [#4223](https://github.com/mochajs/mocha/issues/4223): The context object's `skip()` (`this.skip()`) in a "before all" (`before()`) hook will no longer execute subsequent sibling hooks, in addition to hooks in child suites ([**@juergba**](https://github.com/juergba)) - -- [#4178](https://github.com/mochajs/mocha/issues/4178): Remove previously soft-deprecated APIs ([**@wnghdcjfe**](https://github.com/wnghdcjfe)): - - - `Mocha.prototype.ignoreLeaks()` - - `Mocha.prototype.useColors()` - - `Mocha.prototype.useInlineDiffs()` - - `Mocha.prototype.hideDiff()` - -## :tada: Enhancements - -- [#4245](https://github.com/mochajs/mocha/issues/4245): Add ability to run tests in parallel for Node.js (see [docs](https://mochajs.org/#parallel-tests)) ([**@boneskull**](https://github.com/boneskull)) - - :exclamation: See also [#4244](https://github.com/mochajs/mocha/issues/4244); [Root Hook Plugins (docs)](https://mochajs.org/#root-hook-plugins) -- _root hooks must be defined via Root Hook Plugins to work in parallel mode_ - -- [#4304](https://github.com/mochajs/mocha/issues/4304): `--require` now works with ES modules ([**@JacobLey**](https://github.com/JacobLey)) - -- [#4299](https://github.com/mochajs/mocha/issues/4299): In some circumstances, Mocha can run ES modules under Node.js v10 -- _use at your own risk!_ ([**@giltayar**](https://github.com/giltayar)) - -## :book: Documentation - -- [#4246](https://github.com/mochajs/mocha/issues/4246): Add documentation for parallel mode and Root Hook plugins ([**@boneskull**](https://github.com/boneskull)) - -## :nut_and_bolt: Other - -- [#4200](https://github.com/mochajs/mocha/issues/4200): Drop mkdirp and replace it with fs.mkdirSync ([**@HyunSangHan**](https://github.com/HyunSangHan)) - -## :bug: Fixes - -(All bug fixes in Mocha v8.0.0 are also breaking changes, and are listed above) - -# 7.2.0 / 2020-05-22 - -## :tada: Enhancements - -- [#4234](https://github.com/mochajs/mocha/issues/4234): Add ability to run tests in a mocha instance multiple times ([**@nicojs**](https://github.com/nicojs)) -- [#4219](https://github.com/mochajs/mocha/issues/4219): Exposing filename in JSON, doc, and json-stream reporters ([**@Daniel0113**](https://github.com/Daniel0113)) -- [#4244](https://github.com/mochajs/mocha/issues/4244): Add Root Hook Plugins ([**@boneskull**](https://github.com/boneskull)) - -## :bug: Fixes - -- [#4258](https://github.com/mochajs/mocha/issues/4258): Fix missing dot in name of configuration file ([**@sonicdoe**](https://github.com/sonicdoe)) -- [#4194](https://github.com/mochajs/mocha/issues/4194): Check if module.paths really exists ([**@ematipico**](https://github.com/ematipico)) -- [#4256](https://github.com/mochajs/mocha/issues/4256): `--forbid-only` does not recognize `it.only` when `before` crashes ([**@arvidOtt**](https://github.com/arvidOtt)) -- [#4152](https://github.com/mochajs/mocha/issues/4152): Bug with multiple async done() calls ([**@boneskull**](https://github.com/boneskull)) -- [#4275](https://github.com/mochajs/mocha/issues/4275): Improper warnings for invalid reporters ([**@boneskull**](https://github.com/boneskull)) -- [#4288](https://github.com/mochajs/mocha/issues/4288): Broken hook.spec.js test for IE11 ([**@boneskull**](https://github.com/boneskull)) - -## :book: Documentation - -- [#4081](https://github.com/mochajs/mocha/issues/4081): Insufficient white space for API docs in view on mobile ([**@HyunSangHan**](https://github.com/HyunSangHan)) -- [#4255](https://github.com/mochajs/mocha/issues/4255): Update mocha-docdash for UI fixes on API docs ([**@craigtaub**](https://github.com/craigtaub)) -- [#4235](https://github.com/mochajs/mocha/issues/4235): Enable emoji on website; enable normal ul elements ([**@boneskull**](https://github.com/boneskull)) -- [#4272](https://github.com/mochajs/mocha/issues/4272): Fetch sponsors at build time, show ALL non-skeevy sponsors ([**@boneskull**](https://github.com/boneskull)) - -## :nut_and_bolt: Other - -- [#4249](https://github.com/mochajs/mocha/issues/4249): Refactoring improving encapsulation ([**@arvidOtt**](https://github.com/arvidOtt)) -- [#4242](https://github.com/mochajs/mocha/issues/4242): CI add job names, add Node.js v14 to matrix ([**@boneskull**](https://github.com/boneskull)) -- [#4237](https://github.com/mochajs/mocha/issues/4237): Refactor validatePlugins to throw coded errors ([**@boneskull**](https://github.com/boneskull)) -- [#4236](https://github.com/mochajs/mocha/issues/4236): Better debug output ([**@boneskull**](https://github.com/boneskull)) - -# 7.1.2 / 2020-04-26 - -## :nut_and_bolt: Other - -- [#4251](https://github.com/mochajs/mocha/issues/4251): Prevent karma-mocha from stalling ([**@juergba**](https://github.com/juergba)) -- [#4222](https://github.com/mochajs/mocha/issues/4222): Update dependency mkdirp to v0.5.5 ([**@outsideris**](https://github.com/outsideris)) - -## :book: Documentation - -- [#4208](https://github.com/mochajs/mocha/issues/4208): Add Wallaby logo to site ([**@boneskull**](https://github.com/boneskull)) - -# 7.1.1 / 2020-03-18 - -## :lock: Security Fixes - -- [#4204](https://github.com/mochajs/mocha/issues/4204): Update dependencies mkdirp, yargs-parser and yargs ([**@juergba**](https://github.com/juergba)) - -## :bug: Fixes - -- [#3660](https://github.com/mochajs/mocha/issues/3660): Fix `runner` listening to `start` and `end` events ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#4190](https://github.com/mochajs/mocha/issues/4190): Show Netlify badge on footer ([**@outsideris**](https://github.com/outsideris)) - -# 7.1.0 / 2020-02-26 - -## :tada: Enhancements - -[#4038](https://github.com/mochajs/mocha/issues/4038): Add Node.js native ESM support ([**@giltayar**](https://github.com/giltayar)) - -Mocha supports writing your test files as ES modules: - -- Node.js only v12.11.0 and above -- Node.js below v13.2.0, you must set `--experimental-modules` option -- current limitations: please check our [documentation](https://mochajs.org/#nodejs-native-esm-support) -- for programmatic usage: see [API: loadFilesAsync()](https://mochajs.org/api/mocha#loadFilesAsync) - -**Note:** Node.JS native [ECMAScript Modules](https://nodejs.org/api/esm.html) implementation has status: **Stability: 1 - Experimental** - -## :bug: Fixes - -- [#4181](https://github.com/mochajs/mocha/issues/4181): Programmatic API cannot access retried test objects ([**@juergba**](https://github.com/juergba)) -- [#4174](https://github.com/mochajs/mocha/issues/4174): Browser: fix `allowUncaught` option ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#4058](https://github.com/mochajs/mocha/issues/4058): Manage author list in AUTHORS instead of `package.json` ([**@outsideris**](https://github.com/outsideris)) - -## :nut_and_bolt: Other - -- [#4138](https://github.com/mochajs/mocha/issues/4138): Upgrade ESLint v6.8 ([**@kaicataldo**](https://github.com/kaicataldo)) - -# 7.0.1 / 2020-01-25 - -## :bug: Fixes - -- [#4165](https://github.com/mochajs/mocha/issues/4165): Fix exception when skipping tests programmatically ([**@juergba**](https://github.com/juergba)) -- [#4153](https://github.com/mochajs/mocha/issues/4153): Restore backwards compatibility for `reporterOptions` ([**@holm**](https://github.com/holm)) -- [#4150](https://github.com/mochajs/mocha/issues/4150): Fix recovery of an open test upon uncaught exception ([**@juergba**](https://github.com/juergba)) -- [#4147](https://github.com/mochajs/mocha/issues/4147): Fix regression of leaking uncaught exception handler ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#4146](https://github.com/mochajs/mocha/issues/4146): Update copyright & trademark notices per OJSF ([**@boneskull**](https://github.com/boneskull)) -- [#4140](https://github.com/mochajs/mocha/issues/4140): Fix broken links ([**@KyoungWan**](https://github.com/KyoungWan)) - -## :nut_and_bolt: Other - -- [#4133](https://github.com/mochajs/mocha/issues/4133): Print more descriptive error message ([**@Zirak**](https://github.com/Zirak)) - -# 7.0.0 / 2020-01-05 - -## :boom: Breaking Changes - -- [#3885](https://github.com/mochajs/mocha/issues/3885): **Drop Node.js v6.x support** ([**@mojosoeun**](https://github.com/mojosoeun)) -- [#3890](https://github.com/mochajs/mocha/issues/3890): Remove Node.js debug-related flags `--debug`/`--debug-brk` and deprecate `debug` argument ([**@juergba**](https://github.com/juergba)) -- [#3962](https://github.com/mochajs/mocha/issues/3962): Changes to command-line options ([**@ParkSB**](https://github.com/ParkSB)): - - `--list-interfaces` replaces `--interfaces` - - `--list-reporters` replaces `--reporters` -- Hook pattern of `this.skip()` ([**@juergba**](https://github.com/juergba)): - - [#3859](https://github.com/mochajs/mocha/issues/3859): When conditionally skipping in a `it` test, related `afterEach` hooks are now executed - - [#3741](https://github.com/mochajs/mocha/issues/3741): When conditionally skipping in a `beforeEach` hook, subsequent inner `beforeEach` hooks are now skipped and related `afterEach` hooks are executed - - [#4136](https://github.com/mochajs/mocha/issues/4136): Disallow `this.skip()` within `after` hooks -- [#3967](https://github.com/mochajs/mocha/issues/3967): Remove deprecated `getOptions()` and `lib/cli/options.js` ([**@juergba**](https://github.com/juergba)) -- [#4083](https://github.com/mochajs/mocha/issues/4083): Uncaught exception in `pending` test: don't swallow, but retrospectively fail the test for correct exit code ([**@juergba**](https://github.com/juergba)) -- [#4004](https://github.com/mochajs/mocha/issues/4004): Align `Mocha` constructor's option names with command-line options ([**@juergba**](https://github.com/juergba)) - -## :tada: Enhancements - -- [#3980](https://github.com/mochajs/mocha/issues/3980): Refactor and improve `--watch` mode with chokidar ([**@geigerzaehler**](https://github.com/geigerzaehler)): - - adds command-line options `--watch-files` and `--watch-ignore` - - removes `--watch-extensions` -- [#3979](https://github.com/mochajs/mocha/issues/3979): Type "rs\\n" to restart tests ([**@broofa**](https://github.com/broofa)) - -## :fax: Deprecations - -These are _soft_-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha: - -- [#3968](https://github.com/mochajs/mocha/issues/3968): Deprecate legacy configuration via `mocha.opts` ([**@juergba**](https://github.com/juergba)) - -## :bug: Fixes - -- [#4125](https://github.com/mochajs/mocha/issues/4125): Fix timeout handling with `--inspect-brk`/`--inspect` ([**@juergba**](https://github.com/juergba)) -- [#4070](https://github.com/mochajs/mocha/issues/4070): `Mocha` constructor: improve browser setup ([**@juergba**](https://github.com/juergba)) -- [#4068](https://github.com/mochajs/mocha/issues/4068): XUnit reporter should handle exceptions during diff generation ([**@rgroothuijsen**](https://github.com/rgroothuijsen)) -- [#4030](https://github.com/mochajs/mocha/issues/4030): Fix `--allow-uncaught` with `this.skip()` ([**@juergba**](https://github.com/juergba)) - -## :mag: Coverage - -- [#4109](https://github.com/mochajs/mocha/issues/4109): Add Node.js v13.x to CI test matrix ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#4129](https://github.com/mochajs/mocha/issues/4129): Fix broken links ([**@SaeromB**](https://github.com/SaeromB)) -- [#4127](https://github.com/mochajs/mocha/issues/4127): Add reporter alias names to docs ([**@khg0712**](https://github.com/khg0712)) -- [#4101](https://github.com/mochajs/mocha/issues/4101): Clarify invalid usage of `done()` ([**@jgehrcke**](https://github.com/jgehrcke)) -- [#4092](https://github.com/mochajs/mocha/issues/4092): Replace `:coffee:` with emoji ☕️ ([**@pzrq**](https://github.com/pzrq)) -- [#4088](https://github.com/mochajs/mocha/issues/4088): Initial draft of project charter ([**@boneskull**](https://github.com/boneskull)) -- [#4066](https://github.com/mochajs/mocha/issues/4066): Change `sh` to `bash` for code block in docs/index.md ([**@HyunSangHan**](https://github.com/HyunSangHan)) -- [#4045](https://github.com/mochajs/mocha/issues/4045): Update README.md concerning GraphicsMagick installation ([**@HyunSangHan**](https://github.com/HyunSangHan)) -- [#3988](https://github.com/mochajs/mocha/issues/3988): Fix sponsors background color for readability ([**@outsideris**](https://github.com/outsideris)) - -## :nut_and_bolt: Other - -- [#4118](https://github.com/mochajs/mocha/issues/4118): Update node-environment-flags to 1.0.6 ([**@kylef**](https://github.com/kylef)) -- [#4097](https://github.com/mochajs/mocha/issues/4097): Add GH Funding Metadata ([**@SheetJSDev**](https://github.com/SheetJSDev)) -- [#4089](https://github.com/mochajs/mocha/issues/4089): Add funding information to `package.json` ([**@Munter**](https://github.com/Munter)) -- [#4077](https://github.com/mochajs/mocha/issues/4077): Improve integration tests ([**@soobing**](https://github.com/soobing)) - -# 6.2.3 / 2020-03-25 - -## :lock: Security Fixes - -- [848d6fb8](https://github.com/mochajs/mocha/commit/848d6fb8feef659564b296db457312d38176910d): Update dependencies mkdirp, yargs-parser and yargs ([**@juergba**](https://github.com/juergba)) - -# 6.2.2 / 2019-10-18 - -## :bug: Fixes - -- [#4025](https://github.com/mochajs/mocha/issues/4025): Fix duplicate `EVENT_RUN_END` events upon uncaught exception ([**@juergba**](https://github.com/juergba)) -- [#4051](https://github.com/mochajs/mocha/issues/4051): Fix "unhide" function in `html` reporter (browser) ([**@pec9399**](https://github.com/pec9399)) -- [#4063](https://github.com/mochajs/mocha/issues/4063): Fix use of [esm](https://npm.im/esm) in Node.js v8.x ([**@boneskull**](https://github.com/boneskull)) -- [#4033](https://github.com/mochajs/mocha/issues/4033): Fix output when multiple async exceptions are thrown ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#4046](https://github.com/mochajs/mocha/issues/4046): Site accessibility fixes ([**@Mia-jeong**](https://github.com/Mia-jeong)) -- [#4026](https://github.com/mochajs/mocha/issues/4026): Update docs for custom reporters in browser ([**@Lindsay-Needs-Sleep**](https://github.com/Lindsay-Needs-Sleep)) -- [#3971](https://github.com/mochajs/mocha/issues/3971): Adopt new OpenJS Foundation Code of Conduct ([**@craigtaub**](https://github.com/craigtaub)) - -# 6.2.1 / 2019-09-29 - -## :bug: Fixes - -- [#3955](https://github.com/mochajs/mocha/issues/3955): tty.getWindowSize is not a function inside a "worker_threads" worker ([**@1999**](https://github.com/1999)) -- [#3970](https://github.com/mochajs/mocha/issues/3970): remove extraGlobals() ([**@juergba**](https://github.com/juergba)) -- [#3984](https://github.com/mochajs/mocha/issues/3984): Update yargs-unparser to v1.6.0 ([**@juergba**](https://github.com/juergba)) -- [#3983](https://github.com/mochajs/mocha/issues/3983): Package 'esm': spawn child-process for correct loading ([**@juergba**](https://github.com/juergba)) -- [#3986](https://github.com/mochajs/mocha/issues/3986): Update yargs to v13.3.0 and yargs-parser to v13.1.1 ([**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#3886](https://github.com/mochajs/mocha/issues/3886): fix styles on mochajs.org ([**@outsideris**](https://github.com/outsideris)) -- [#3966](https://github.com/mochajs/mocha/issues/3966): Remove jsdoc index.html placeholder from eleventy file structure and fix broken link in jsdoc tutorial ([**@Munter**](https://github.com/Munter)) -- [#3765](https://github.com/mochajs/mocha/issues/3765): Add Matomo to website ([**@MarioDiaz98**](https://github.com/MarioDiaz98)) -- [#3947](https://github.com/mochajs/mocha/issues/3947): Clarify effect of .skip() ([**@oliversalzburg**](https://github.com/oliversalzburg)) - -# 6.2.0 / 2019-07-18 - -## :tada: Enhancements - -- [#3827](https://github.com/mochajs/mocha/issues/3827): Do not fork child-process if no Node flags are present ([**@boneskull**](https://github.com/boneskull)) -- [#3725](https://github.com/mochajs/mocha/issues/3725): Base reporter store ref to console.log, see [mocha/wiki](https://github.com/mochajs/mocha/wiki/HOW-TO:-Correctly-stub-stdout) ([**@craigtaub**](https://github.com/craigtaub)) - -## :bug: Fixes - -- [#3942](https://github.com/mochajs/mocha/issues/3942): Fix "No test files found" Error when file is passed via `--file` ([**@gabegorelick**](https://github.com/gabegorelick)) -- [#3914](https://github.com/mochajs/mocha/issues/3914): Modify Mocha constructor to accept options `global` or `globals` ([**@pascalpp**](https://github.com/pascalpp)) -- [#3894](https://github.com/mochajs/mocha/issues/3894): Fix parsing of config files with `_mocha` binary ([**@juergba**](https://github.com/juergba)) -- [#3834](https://github.com/mochajs/mocha/issues/3834): Fix CLI parsing with default values ([**@boneskull**](https://github.com/boneskull), [**@juergba**](https://github.com/juergba)) -- [#3831](https://github.com/mochajs/mocha/issues/3831): Fix `--timeout`/`--slow` string values and duplicate arguments ([**@boneskull**](https://github.com/boneskull), [**@juergba**](https://github.com/juergba)) - -## :book: Documentation - -- [#3906](https://github.com/mochajs/mocha/issues/3906): Document option to define custom report name for XUnit reporter ([**@pkuczynski**](https://github.com/pkuczynski)) -- [#3889](https://github.com/mochajs/mocha/issues/3889): Adds doc links for mocha-examples ([**@craigtaub**](https://github.com/craigtaub)) -- [#3887](https://github.com/mochajs/mocha/issues/3887): Fix broken links ([**@toyjhlee**](https://github.com/toyjhlee)) -- [#3841](https://github.com/mochajs/mocha/issues/3841): Fix anchors to configuration section ([**@trescube**](https://github.com/trescube)) - -## :mag: Coverage - -- [#3915](https://github.com/mochajs/mocha/issues/3915), [#3929](https://github.com/mochajs/mocha/issues/3929): Increase tests coverage for `--watch` options ([**@geigerzaehler**](https://github.com/geigerzaehler)) - -## :nut_and_bolt: Other - -- [#3953](https://github.com/mochajs/mocha/issues/3953): Collect test files later, prepares improvements to the `--watch` mode behavior ([**@geigerzaehler**](https://github.com/geigerzaehler)) -- [#3939](https://github.com/mochajs/mocha/issues/3939): Upgrade for npm audit ([**@boneskull**](https://github.com/boneskull)) -- [#3930](https://github.com/mochajs/mocha/issues/3930): Extract `runWatch` into separate module ([**@geigerzaehler**](https://github.com/geigerzaehler)) -- [#3922](https://github.com/mochajs/mocha/issues/3922): Add `mocha.min.js` file to stacktrace filter ([**@brian-lagerman**](https://github.com/brian-lagerman)) -- [#3919](https://github.com/mochajs/mocha/issues/3919): Update CI config files to use Node-12.x ([**@plroebuck**](https://github.com/plroebuck)) -- [#3892](https://github.com/mochajs/mocha/issues/3892): Rework reporter tests ([**@plroebuck**](https://github.com/plroebuck)) -- [#3872](https://github.com/mochajs/mocha/issues/3872): Rename `--exclude` to `--ignore` and create alias ([**@boneskull**](https://github.com/boneskull)) -- [#3963](https://github.com/mochajs/mocha/issues/3963): Hide stacktrace when cli args are missing ([**@outsideris**](https://github.com/outsideris)) -- [#3956](https://github.com/mochajs/mocha/issues/3956): Do not redeclare variable in docs array example ([**@DanielRuf**](https://github.com/DanielRuf)) -- [#3957](https://github.com/mochajs/mocha/issues/3957): Remove duplicate line-height property in `mocha.css` ([**@DanielRuf**](https://github.com/DanielRuf)) -- [#3960](https://github.com/mochajs/mocha/issues/3960): Don't re-initialize grep option on watch re-run ([**@geigerzaehler**](https://github.com/geigerzaehler)) - -# 6.1.4 / 2019-04-18 - -## :lock: Security Fixes - -- [#3877](https://github.com/mochajs/mocha/issues/3877): Upgrade [js-yaml](https://npm.im/js-yaml), addressing [code injection vulnerability](https://www.npmjs.com/advisories/813) ([**@bjornstar**](https://github.com/bjornstar)) - -# 6.1.3 / 2019-04-11 - -## :bug: Fixes - -- [#3863](https://github.com/mochajs/mocha/issues/3863): Fix `yargs`-related global scope pollution ([**@inukshuk**](https://github.com/inukshuk)) -- [#3869](https://github.com/mochajs/mocha/issues/3869): Fix failure when installed w/ `pnpm` ([**@boneskull**](https://github.com/boneskull)) - -# 6.1.2 / 2019-04-08 - -## :bug: Fixes - -- [#3867](https://github.com/mochajs/mocha/issues/3867): Re-publish v6.1.1 from POSIX OS to avoid dropped executable flags ([**@boneskull**](https://github.com/boneskull)) - -# 6.1.1 / 2019-04-07 - -## :bug: Fixes - -- [#3866](https://github.com/mochajs/mocha/issues/3866): Fix Windows End-of-Line publishing issue ([**@juergba**](https://github.com/juergba) & [**@cspotcode**](https://github.com/cspotcode)) - -# 6.1.0 / 2019-04-07 - -## :lock: Security Fixes - -- [#3845](https://github.com/mochajs/mocha/issues/3845): Update dependency "js-yaml" to v3.13.0 per npm security advisory ([**@plroebuck**](https://github.com/plroebuck)) - -## :tada: Enhancements - -- [#3766](https://github.com/mochajs/mocha/issues/3766): Make reporter constructor support optional `options` parameter ([**@plroebuck**](https://github.com/plroebuck)) -- [#3760](https://github.com/mochajs/mocha/issues/3760): Add support for config files with `.jsonc` extension ([**@sstephant**](https://github.com/sstephant)) - -## :fax: Deprecations - -These are _soft_-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha: - -- [#3719](https://github.com/mochajs/mocha/issues/3719): Deprecate `this.skip()` for "after all" hooks ([**@juergba**](https://github.com/juergba)) - -## :bug: Fixes - -- [#3829](https://github.com/mochajs/mocha/issues/3829): Use cwd-relative pathname to load config file ([**@plroebuck**](https://github.com/plroebuck)) -- [#3745](https://github.com/mochajs/mocha/issues/3745): Fix async calls of `this.skip()` in "before each" hooks ([**@juergba**](https://github.com/juergba)) -- [#3669](https://github.com/mochajs/mocha/issues/3669): Enable `--allow-uncaught` for uncaught exceptions thrown inside hooks ([**@givanse**](https://github.com/givanse)) - -and some regressions: - -- [#3848](https://github.com/mochajs/mocha/issues/3848): Fix `Suite` cloning by copying `root` property ([**@fatso83**](https://github.com/fatso83)) -- [#3816](https://github.com/mochajs/mocha/issues/3816): Guard against undefined timeout option ([**@boneskull**](https://github.com/boneskull)) -- [#3814](https://github.com/mochajs/mocha/issues/3814): Update "yargs" in order to avoid deprecation message ([**@boneskull**](https://github.com/boneskull)) -- [#3788](https://github.com/mochajs/mocha/issues/3788): Fix support for multiple node flags ([**@aginzberg**](https://github.com/aginzberg)) - -## :book: Documentation - -- [mochajs/mocha-examples](https://github.com/mochajs/mocha-examples): New repository of working examples of common configurations using mocha ([**@craigtaub**](https://github.com/craigtaub)) -- [#3850](https://github.com/mochajs/mocha/issues/3850): Remove pound icon showing on header hover on docs ([**@jd2rogers2**](https://github.com/jd2rogers2)) -- [#3812](https://github.com/mochajs/mocha/issues/3812): Add autoprefixer to documentation page CSS ([**@Munter**](https://github.com/Munter)) -- [#3811](https://github.com/mochajs/mocha/issues/3811): Update doc examples "tests.html" ([**@DavidLi119**](https://github.com/DavidLi119)) -- [#3807](https://github.com/mochajs/mocha/issues/3807): Mocha website HTML tweaks ([**@plroebuck**](https://github.com/plroebuck)) -- [#3793](https://github.com/mochajs/mocha/issues/3793): Update config file example ".mocharc.yml" ([**@cspotcode**](https://github.com/cspotcode)) - -## :nut_and_bolt: Other - -- [#3830](https://github.com/mochajs/mocha/issues/3830): Replace dependency "findup-sync" with "find-up" for faster startup ([**@cspotcode**](https://github.com/cspotcode)) -- [#3799](https://github.com/mochajs/mocha/issues/3799): Update devDependencies to fix many npm vulnerabilities ([**@XhmikosR**](https://github.com/XhmikosR)) - -# 6.0.2 / 2019-02-25 - -## :bug: Fixes - -Two more regressions fixed: - -- [#3768](https://github.com/mochajs/mocha/issues/3768): Test file paths no longer dropped from `mocha.opts` ([**@boneskull**](https://github.com/boneskull)) -- [#3767](https://github.com/mochajs/mocha/issues/3767): `--require` does not break on module names that look like certain `node` flags ([**@boneskull**](https://github.com/boneskull)) - -# 6.0.1 / 2019-02-21 - -The obligatory round of post-major-release bugfixes. - -## :bug: Fixes - -These issues were regressions. - -- [#3754](https://github.com/mochajs/mocha/issues/3754): Mocha again finds `test.js` when run without arguments ([**@plroebuck**](https://github.com/plroebuck)) -- [#3756](https://github.com/mochajs/mocha/issues/3756): Mocha again supports third-party interfaces via `--ui` ([**@boneskull**](https://github.com/boneskull)) -- [#3755](https://github.com/mochajs/mocha/issues/3755): Fix broken `--watch` ([**@boneskull**](https://github.com/boneskull)) -- [#3759](https://github.com/mochajs/mocha/issues/3759): Fix unwelcome deprecation notice when Mocha run against languages (CoffeeScript) with implicit return statements; _returning a non-`undefined` value from a `describe` callback is no longer considered deprecated_ ([**@boneskull**](https://github.com/boneskull)) - -## :book: Documentation - -- [#3738](https://github.com/mochajs/mocha/issues/3738): Upgrade to `@mocha/docdash@2` ([**@tendonstrength**](https://github.com/tendonstrength)) -- [#3751](https://github.com/mochajs/mocha/issues/3751): Use preferred names for example config files ([**@Szauka**](https://github.com/Szauka)) - -# 6.0.0 / 2019-02-18 - -## :tada: Enhancements - -- [#3726](https://github.com/mochajs/mocha/issues/3726): Add ability to unload files from `require` cache ([**@plroebuck**](https://github.com/plroebuck)) - -## :bug: Fixes - -- [#3737](https://github.com/mochajs/mocha/issues/3737): Fix falsy values from options globals ([**@plroebuck**](https://github.com/plroebuck)) -- [#3707](https://github.com/mochajs/mocha/issues/3707): Fix encapsulation issues for `Suite#_onlyTests` and `Suite#_onlySuites` ([**@vkarpov15**](https://github.com/vkarpov15)) -- [#3711](https://github.com/mochajs/mocha/issues/3711): Fix diagnostic messages dealing with plurality and markup of output ([**@plroebuck**](https://github.com/plroebuck)) -- [#3723](https://github.com/mochajs/mocha/issues/3723): Fix "reporter-option" to allow comma-separated options ([**@boneskull**](https://github.com/boneskull)) -- [#3722](https://github.com/mochajs/mocha/issues/3722): Fix code quality and performance of `lookupFiles` and `files` ([**@plroebuck**](https://github.com/plroebuck)) -- [#3650](https://github.com/mochajs/mocha/issues/3650), [#3654](https://github.com/mochajs/mocha/issues/3654): Fix noisy error message when no files found ([**@craigtaub**](https://github.com/craigtaub)) -- [#3632](https://github.com/mochajs/mocha/issues/3632): Tests having an empty title are no longer confused with the "root" suite ([**@juergba**](https://github.com/juergba)) -- [#3666](https://github.com/mochajs/mocha/issues/3666): Fix missing error codes ([**@vkarpov15**](https://github.com/vkarpov15)) -- [#3684](https://github.com/mochajs/mocha/issues/3684): Fix exiting problem in Node.js v11.7.0+ ([**@addaleax**](https://github.com/addaleax)) -- [#3691](https://github.com/mochajs/mocha/issues/3691): Fix `--delay` (and other boolean options) not working in all cases ([**@boneskull**](https://github.com/boneskull)) -- [#3692](https://github.com/mochajs/mocha/issues/3692): Fix invalid command-line argument usage not causing actual errors ([**@boneskull**](https://github.com/boneskull)) -- [#3698](https://github.com/mochajs/mocha/issues/3698), [#3699](https://github.com/mochajs/mocha/issues/3699): Fix debug-related Node.js options not working in all cases ([**@boneskull**](https://github.com/boneskull)) -- [#3700](https://github.com/mochajs/mocha/issues/3700): Growl notifications now show the correct number of tests run ([**@outsideris**](https://github.com/outsideris)) -- [#3686](https://github.com/mochajs/mocha/issues/3686): Avoid potential ReDoS when diffing large objects ([**@cyjake**](https://github.com/cyjake)) -- [#3715](https://github.com/mochajs/mocha/issues/3715): Fix incorrect order of emitted events when used programmatically ([**@boneskull**](https://github.com/boneskull)) -- [#3706](https://github.com/mochajs/mocha/issues/3706): Fix regression wherein `--reporter-option`/`--reporter-options` did not support comma-separated key/value pairs ([**@boneskull**](https://github.com/boneskull)) - -## :book: Documentation - -- [#3652](https://github.com/mochajs/mocha/issues/3652): Switch from Jekyll to Eleventy ([**@Munter**](https://github.com/Munter)) - -## :nut_and_bolt: Other - -- [#3677](https://github.com/mochajs/mocha/issues/3677): Add error objects for createUnsupportedError and createInvalidExceptionError ([**@boneskull**](https://github.com/boneskull)) -- [#3733](https://github.com/mochajs/mocha/issues/3733): Removed unnecessary processing in post-processing hook ([**@wanseob**](https://github.com/wanseob)) -- [#3730](https://github.com/mochajs/mocha/issues/3730): Update nyc to latest version ([**@coreyfarrell**](https://github.com/coreyfarrell)) -- [#3648](https://github.com/mochajs/mocha/issues/3648), [#3680](https://github.com/mochajs/mocha/issues/3680): Fixes to support latest versions of [unexpected](https://npm.im/unexpected) and [unexpected-sinon](https://npm.im/unexpected-sinon) ([**@sunesimonsen**](https://github.com/sunesimonsen)) -- [#3638](https://github.com/mochajs/mocha/issues/3638): Add meta tag to site ([**@MartijnCuppens**](https://github.com/MartijnCuppens)) -- [#3653](https://github.com/mochajs/mocha/issues/3653): Fix parts of test suite failing to run on Windows ([**@boneskull**](https://github.com/boneskull)) - -# 6.0.0-1 / 2019-01-02 - -## :bug: Fixes - -- Fix missing `mocharc.json` in published package ([**@boneskull**](https://github.com/boneskull)) - -# 6.0.0-0 / 2019-01-01 - -**Documentation for this release can be found at [next.mochajs.org](https://next.mochajs.org)**! - -Welcome [**@plroebuck**](https://github.com/plroebuck), [**@craigtaub**](https://github.com/craigtaub), & [**@markowsiak**](https://github.com/markowsiak) to the team! - -## :boom: Breaking Changes - -- [#3149](https://github.com/mochajs/mocha/issues/3149): **Drop Node.js v4.x support** ([**@outsideris**](https://github.com/outsideris)) -- [#3556](https://github.com/mochajs/mocha/issues/3556): Changes to command-line options ([**@boneskull**](https://github.com/boneskull)): - - `--grep` and `--fgrep` are now mutually exclusive; attempting to use both will cause Mocha to fail instead of simply ignoring `--grep` - - `--compilers` is no longer supported; attempting to use will cause Mocha to fail with a link to more information - - `-d` is no longer an alias for `--debug`; `-d` is currently ignored - - [#3275](https://github.com/mochajs/mocha/issues/3275): `--watch-extensions` no longer implies `js`; it must be explicitly added ([**@TheDancingCode**](https://github.com/TheDancingCode)) -- [#2908](https://github.com/mochajs/mocha/issues/2908): `tap` reporter emits error messages ([**@chrmod**](https://github.com/chrmod)) -- [#2819](https://github.com/mochajs/mocha/issues/2819): When conditionally skipping in a `before` hook, subsequent `before` hooks _and_ tests in nested suites are now skipped ([**@bannmoore**](https://github.com/bannmoore)) -- [#627](https://github.com/mochajs/mocha/issues/627): Emit filepath in "timeout exceeded" exceptions where applicable ([**@boneskull**](https://github.com/boneskull)) -- [#3556](https://github.com/mochajs/mocha/issues/3556): `lib/template.html` has moved to `lib/browser/template.html` ([**@boneskull**](https://github.com/boneskull)) -- [#2576](https://github.com/mochajs/mocha/issues/2576): An exception is now thrown if Mocha fails to parse or find a `mocha.opts` at a user-specified path ([**@plroebuck**](https://github.com/plroebuck)) -- [#3458](https://github.com/mochajs/mocha/issues/3458): Instantiating a `Base`-extending reporter without a `Runner` parameter will throw an exception ([**@craigtaub**](https://github.com/craigtaub)) -- [#3125](https://github.com/mochajs/mocha/issues/3125): For consumers of Mocha's programmatic API, all exceptions thrown from Mocha now have a `code` property (and some will have additional metadata). Some `Error` messages have changed. **Please use the `code` property to check `Error` types instead of the `message` property**; these descriptions will be localized in the future. ([**@craigtaub**](https://github.com/craigtaub)) - -## :fax: Deprecations - -These are _soft_-deprecated, and will emit a warning upon use. Support will be removed in (likely) the next major version of Mocha: - -- `-gc` users should use `--gc-global` instead -- Consumers of the function exported by `bin/options` should now use the `loadMochaOpts` or `loadOptions` (preferred) functions exported by the `lib/cli/options` module - -Regarding the `Mocha` class constructor (from `lib/mocha`): - -- Use property `color: false` instead of `useColors: false` -- Use property `timeout: false` instead of `enableTimeouts: false` - -All of the above deprecations were introduced by [#3556](https://github.com/mochajs/mocha/issues/3556). - -`mocha.opts` is now considered "legacy"; please prefer RC file or `package.json` over `mocha.opts`. - -## :tada: Enhancements - -Enhancements introduced in [#3556](https://github.com/mochajs/mocha/issues/3556): - -- Mocha now supports "RC" files in JS, JSON, YAML, or `package.json`-based (using `mocha` property) format - - - `.mocharc.js`, `.mocharc.json`, `.mocharc.yaml` or `.mocharc.yml` are valid "rc" file names and will be automatically loaded - - Use `--config /path/to/rc/file` to specify an explicit path - - Use `--package /path/to/package.json` to specify an explicit `package.json` to read the `mocha` prop from - - Use `--no-config` or `--no-package` to completely disable loading of configuration via RC file and `package.json`, respectively - - Configurations are merged as applicable using the priority list: - 1. Command-line arguments - 1. RC file - 1. `package.json` - 1. `mocha.opts` - 1. Mocha's own defaults - - Check out these [example config files](https://github.com/mochajs/mocha/tree/master/example/config) - -- Node/V8 flag support in `mocha` executable: - - - Support all allowed `node` flags as supported by the running version of `node` (also thanks to [**@demurgos**](https://github.com/demurgos)) - - Support any V8 flag by prepending `--v8-` to the flag name - - All flags are also supported via config files, `package.json` properties, or `mocha.opts` - - Debug-related flags (e.g., `--inspect`) now _imply_ `--no-timeouts` - - Use of e.g., `--debug` will automatically invoke `--inspect` if supported by running version of `node` - -- Support negation of any Mocha-specific command-line flag by prepending `--no-` to the flag name - -- Interfaces now have descriptions when listed using `--interfaces` flag - -- `Mocha` constructor supports all options - -- `--extension` is now an alias for `--watch-extensions` and affects _non-watch-mode_ test runs as well. For example, to run _only_ `test/*.coffee` (not `test/*.js`), you can do `mocha --require coffee-script/register --extensions coffee`. - -- [#3552](https://github.com/mochajs/mocha/issues/3552): `tap` reporter is now TAP13-capable ([**@plroebuck**](https://github.com/plroebuck) & [**@mollstam**](https://github.com/mollstam)) - -- [#3535](https://github.com/mochajs/mocha/issues/3535): Mocha's version can now be queried programmatically via public property `Mocha.prototype.version` ([**@plroebuck**](https://github.com/plroebuck)) - -- [#3428](https://github.com/mochajs/mocha/issues/3428): `xunit` reporter shows diffs ([**@mlucool**](https://github.com/mlucool)) - -- [#2529](https://github.com/mochajs/mocha/issues/2529): `Runner` now emits a `retry` event when tests are retried (reporters can listen for this) ([**@catdad**](https://github.com/catdad)) - -- [#2962](https://github.com/mochajs/mocha/issues/2962), [#3111](https://github.com/mochajs/mocha/issues/3111): In-browser notification support; warn about missing prereqs when `--growl` supplied ([**@plroebuck**](https://github.com/plroebuck)) - -## :bug: Fixes - -- [#3356](https://github.com/mochajs/mocha/issues/3356): `--no-timeouts` and `--timeout 0` now does what you'd expect ([**@boneskull**](https://github.com/boneskull)) -- [#3475](https://github.com/mochajs/mocha/issues/3475): Restore `--no-exit` option ([**@boneskull**](https://github.com/boneskull)) -- [#3570](https://github.com/mochajs/mocha/issues/3570): Long-running tests now respect `SIGINT` ([**@boneskull**](https://github.com/boneskull)) -- [#2944](https://github.com/mochajs/mocha/issues/2944): `--forbid-only` and `--forbid-pending` now "fail fast" when encountered on a suite ([**@outsideris**](https://github.com/outsideris)) -- [#1652](https://github.com/mochajs/mocha/issues/1652), [#2951](https://github.com/mochajs/mocha/issues/2951): Fix broken clamping of timeout values ([**@plroebuck**](https://github.com/plroebuck)) -- [#2095](https://github.com/mochajs/mocha/issues/2095), [#3521](https://github.com/mochajs/mocha/issues/3521): Do not log `stdout:` prefix in browser console ([**@Bamieh**](https://github.com/Bamieh)) -- [#3595](https://github.com/mochajs/mocha/issues/3595): Fix mochajs.org deployment problems ([**@papandreou**](https://github.com/papandreou)) -- [#3518](https://github.com/mochajs/mocha/issues/3518): Improve `utils.isPromise()` ([**@fabiosantoscode**](https://github.com/fabiosantoscode)) -- [#3320](https://github.com/mochajs/mocha/issues/3320): Fail gracefully when non-extensible objects are thrown in async tests ([**@fargies**](https://github.com/fargies)) -- [#2475](https://github.com/mochajs/mocha/issues/2475): XUnit does not duplicate test result numbers in "errors" and "failures"; "failures" will **always** be zero ([**@mlucool**](https://github.com/mlucool)) -- [#3398](https://github.com/mochajs/mocha/issues/3398), [#3598](https://github.com/mochajs/mocha/issues/3598), [#3457](https://github.com/mochajs/mocha/issues/3457), [#3617](https://github.com/mochajs/mocha/issues/3617): Fix regression wherein `--bail` would not execute "after" nor "after each" hooks ([**@juergba**](https://github.com/juergba)) -- [#3580](https://github.com/mochajs/mocha/issues/3580): Fix potential exception when using XUnit reporter programmatically ([**@Lana-Light**](https://github.com/Lana-Light)) -- [#1304](https://github.com/mochajs/mocha/issues/1304): Do not output color to `TERM=dumb` ([**@plroebuck**](https://github.com/plroebuck)) - -## :book: Documentation - -- [#3525](https://github.com/mochajs/mocha/issues/3525): Improvements to `.github/CONTRIBUTING.md` ([**@markowsiak**](https://github.com/markowsiak)) -- [#3466](https://github.com/mochajs/mocha/issues/3466): Update description of `slow` option ([**@finfin**](https://github.com/finfin)) -- [#3405](https://github.com/mochajs/mocha/issues/3405): Remove references to bower installations ([**@goteamtim**](https://github.com/goteamtim)) -- [#3361](https://github.com/mochajs/mocha/issues/3361): Improvements to `--watch` docs ([**@benglass**](https://github.com/benglass)) -- [#3136](https://github.com/mochajs/mocha/issues/3136): Improve docs around globbing and shell expansion ([**@akrawchyk**](https://github.com/akrawchyk)) -- [#2819](https://github.com/mochajs/mocha/issues/2819): Update docs around skips and hooks ([**@bannmoore**](https://github.com/bannmoore)) -- Many improvements by [**@outsideris**](https://github.com/outsideris) - -## :nut_and_bolt: Other - -- [#3557](https://github.com/mochajs/mocha/issues/3557): Use `ms` userland module instead of hand-rolled solution ([**@gizemkeser**](https://github.com/gizemkeser)) -- Many CI fixes and other refactors by [**@plroebuck**](https://github.com/plroebuck) -- Test refactors by [**@outsideris**](https://github.com/outsideris) - -# 5.2.0 / 2018-05-18 - -## :tada: Enhancements - -- [#3375](https://github.com/mochajs/mocha/pull/3375): Add support for comments in `mocha.opts` ([@plroebuck](https://github.com/plroebuck)) - -## :bug: Fixes - -- [#3346](https://github.com/mochajs/mocha/pull/3346): Exit correctly from `before` hooks when using `--bail` ([@outsideris](https://github.com/outsideris)) - -## :book: Documentation - -- [#3328](https://github.com/mochajs/mocha/pull/3328): Mocha-flavored [API docs](https://mochajs.org/api/)! ([@Munter](https://github.com/munter)) - -## :nut_and_bolt: Other - -- [#3330](https://github.com/mochajs/mocha/pull/3330): Use `Buffer.from()` ([@harrysarson](https://github.com/harrysarson)) -- [#3295](https://github.com/mochajs/mocha/pull/3295): Remove redundant folder ([@DavNej](https://github.com/DajNev)) -- [#3356](https://github.com/mochajs/mocha/pull/3356): Refactoring ([@plroebuck](https://github.com/plroebuck)) - -# 5.1.1 / 2018-04-18 - -## :bug: Fixes - -- [#3325](https://github.com/mochajs/mocha/issues/3325): Revert change which broke `--watch` ([@boneskull](https://github.com/boneskull)) - -# 5.1.0 / 2018-04-12 - -## :tada: Enhancements - -- [#3210](https://github.com/mochajs/mocha/pull/3210): Add `--exclude` option ([@metalex9](https://github.com/metalex9)) - -## :bug: Fixes - -- [#3318](https://github.com/mochajs/mocha/pull/3318): Fix failures in circular objects in JSON reporter ([@jeversmann](https://github.com/jeversmann), [@boneskull](https://github.com/boneskull)) - -## :book: Documentation - -- [#3323](https://github.com/mochajs/mocha/pull/3323): Publish actual [API documentation](https://mochajs.org/api/)! ([@dfberry](https://github.com/dfberry), [@Munter](https://github.com/munter)) -- [#3299](https://github.com/mochajs/mocha/pull/3299): Improve docs around exclusive tests ([@nicgirault](https://github.com/nicgirault)) - -## :nut_and_bolt: Other - -- [#3302](https://github.com/mochajs/mocha/pull/3302), [#3308](https://github.com/mochajs/mocha/pull/3308), [#3310](https://github.com/mochajs/mocha/pull/3310), [#3315](https://github.com/mochajs/mocha/pull/3315), [#3316](https://github.com/mochajs/mocha/pull/3316): Build matrix improvements ([more info](https://boneskull.com/mocha-and-travis-ci-build-stages/)) ([@outsideris](https://github.com/outsideris), [@boneskull](https://github.com/boneskull)) -- [#3272](https://github.com/mochajs/mocha/pull/3272): Refactor reporter tests ([@jMuzsik](https://github.com/jMuzsik)) - -# 5.0.5 / 2018-03-22 - -Welcome [@outsideris](https://github.com/outsideris) to the team! - -## :bug: Fixes - -- [#3096](https://github.com/mochajs/mocha/issues/3096): Fix `--bail` failing to bail within hooks ([@outsideris](https://github.com/outsideris)) -- [#3184](https://github.com/mochajs/mocha/issues/3184): Don't skip too many suites (using `describe.skip()`) ([@outsideris](https://github.com/outsideris)) - -## :book: Documentation - -- [#3133](https://github.com/mochajs/mocha/issues/3133): Improve docs regarding "pending" behavior ([@ematicipo](https://github.com/ematicipo)) -- [#3276](https://github.com/mochajs/mocha/pull/3276), [#3274](https://github.com/mochajs/mocha/pull/3274): Fix broken stuff in `CHANGELOG.md` ([@tagoro9](https://github.com/tagoro9), [@honzajavorek](https://github.com/honzajavorek)) - -## :nut_and_bolt: Other - -- [#3208](https://github.com/mochajs/mocha/issues/3208): Improve test coverage for AMD users ([@outsideris](https://github.com/outsideris)) -- [#3267](https://github.com/mochajs/mocha/pull/3267): Remove vestiges of PhantomJS from CI ([@anishkny](https://github.com/anishkny)) -- [#2952](https://github.com/mochajs/mocha/issues/2952): Fix a debug message ([@boneskull](https://github.com/boneskull)) - -# 5.0.4 / 2018-03-07 - -## :bug: Fixes - -- [#3265](https://github.com/mochajs/mocha/issues/3265): Fixes regression in "watch" functionality introduced in v5.0.2 ([@outsideris](https://github.com/outsideris)) - -# 5.0.3 / 2018-03-06 - -This patch features a fix to address a potential "low severity" [ReDoS vulnerability](https://snyk.io/vuln/npm:diff:20180305) in the [diff](https://npm.im/diff) package (a dependency of Mocha). - -## :lock: Security Fixes - -- [#3266](https://github.com/mochajs/mocha/pull/3266): Bump `diff` to v3.5.0 ([@anishkny](https://github.com/anishkny)) - -## :nut_and_bolt: Other - -- [#3011](https://github.com/mochajs/mocha/issues/3011): Expose `generateDiff()` in `Base` reporter ([@harrysarson](https://github.com/harrysarson)) - -# 5.0.2 / 2018-03-05 - -This release fixes a class of tests which report as _false positives_. **Certain tests will now break**, though they would have previously been reported as passing. Details below. Sorry for the inconvenience! - -## :bug: Fixes - -- [#3226](https://github.com/mochajs/mocha/issues/3226): Do not swallow errors that are thrown asynchronously from passing tests ([@boneskull](https://github.com/boneskull)). Example: - - \`\`\`js - it('should actually fail, sorry!', function (done) { - // passing assertion - assert(true === true); - - // test complete & is marked as passing - done(); - - // ...but something evil lurks within - setTimeout(() => { - throw new Error('chaos!'); - }, 100); - }); - \`\`\` - - Previously to this version, Mocha would have _silently swallowed_ the `chaos!` exception, and you wouldn't know. Well, _now you know_. Mocha cannot recover from this gracefully, so it will exit with a nonzero code. - - **Maintainers of external reporters**: _If_ a test of this class is encountered, the `Runner` instance will emit the `end` event _twice_; you _may_ need to change your reporter to use `runner.once('end')` intead of `runner.on('end')`. - -- [#3093](https://github.com/mochajs/mocha/issues/3093): Fix stack trace reformatting problem ([@outsideris](https://github.com/outsideris)) - -## :nut_and_bolt: Other - -- [#3248](https://github.com/mochajs/mocha/issues/3248): Update `browser-stdout` to v1.3.1 ([@honzajavorek](https://github.com/honzajavorek)) - -# 5.0.1 / 2018-02-07 - -...your garden-variety patch release. - -Special thanks to [Wallaby.js](https://wallabyjs.com) for their continued support! :heart: - -## :bug: Fixes - -- [#1838](https://github.com/mochajs/mocha/issues/1838): `--delay` now works with `.only()` ([@silviom](https://github.com/silviom)) -- [#3119](https://github.com/mochajs/mocha/issues/3119): Plug memory leak present in v8 ([@boneskull](https://github.com/boneskull)) - -## :book: Documentation - -- [#3132](https://github.com/mochajs/mocha/issues/3132), [#3098](https://github.com/mochajs/mocha/issues/3098): Update `--glob` docs ([@outsideris](https://github.com/outsideris)) -- [#3212](https://github.com/mochajs/mocha/pull/3212): Update [Wallaby.js](https://wallabyjs.com)-related docs ([@ArtemGovorov](https://github.com/ArtemGovorov)) -- [#3205](https://github.com/mochajs/mocha/pull/3205): Remove outdated cruft ([@boneskull](https://github.com/boneskull)) - -## :nut_and_bolt: Other - -- [#3224](https://github.com/mochajs/mocha/pull/3224): Add proper Wallaby.js config ([@ArtemGovorov](https://github.com/ArtemGovorov)) -- [#3230](https://github.com/mochajs/mocha/pull/3230): Update copyright year ([@josephlin55555](https://github.com/josephlin55555)) - -# 5.0.0 / 2018-01-17 - -Mocha starts off 2018 right by again dropping support for _unmaintained rubbish_. - -Welcome [@vkarpov15](https://github.com/vkarpov15) to the team! - -## :boom: Breaking Changes - -- **[#3148](https://github.com/mochajs/mocha/issues/3148): Drop support for IE9 and IE10** ([@Bamieh](https://github.com/Bamieh)) - Practically speaking, only code which consumes (through bundling or otherwise) the userland [buffer](https://npm.im/buffer) module should be affected. However, Mocha will no longer test against these browsers, nor apply fixes for them. - -## :tada: Enhancements - -- [#3181](https://github.com/mochajs/mocha/issues/3181): Add useful new `--file` command line argument ([documentation](https://mochajs.org/#--file-file)) ([@hswolff](https://github.com/hswolff)) - -## :bug: Fixes - -- [#3187](https://github.com/mochajs/mocha/issues/3187): Fix inaccurate test duration reporting ([@FND](https://github.com/FND)) -- [#3202](https://github.com/mochajs/mocha/pull/3202): Fix bad markup in HTML reporter ([@DanielRuf](https://github.com/DanielRuf)) - -## :sunglasses: Developer Experience - -- [#2352](https://github.com/mochajs/mocha/issues/2352): Ditch GNU Make for [nps](https://npm.im/nps) to manage scripts ([@TedYav](https://github.com/TedYav)) - -## :book: Documentation - -- [#3137](https://github.com/mochajs/mocha/issues/3137): Add missing `--no-timeouts` docs ([@dfberry](https://github.com/dfberry)) -- [#3134](https://github.com/mochajs/mocha/issues/3134): Improve `done()` callback docs ([@maraisr](https://github.com/maraisr)) -- [#3135](https://github.com/mochajs/mocha/issues/3135): Fix cross-references ([@vkarpov15](https://github.com/vkarpov15)) -- [#3163](https://github.com/mochajs/mocha/pull/3163): Fix tpyos ([@tbroadley](https://github.com/tbroadley)) -- [#3177](https://github.com/mochajs/mocha/pull/3177): Tweak `README.md` organization ([@xxczaki](https://github.com/xxczaki)) -- Misc updates ([@boneskull](https://github.com/boneskull)) - -## :nut_and_bolt: Other - -- [#3118](https://github.com/mochajs/mocha/issues/3118): Move TextMate Integration to [its own repo](https://github.com/mochajs/mocha.tmbundle) ([@Bamieh](https://github.com/Bamieh)) -- [#3185](https://github.com/mochajs/mocha/issues/3185): Add Node.js v9 to build matrix; remove v7 ([@xxczaki](https://github.com/xxczaki)) -- [#3172](https://github.com/mochajs/mocha/issues/3172): Markdown linting ([@boneskull](https://github.com/boneskull)) -- Test & Netlify updates ([@Munter](https://github.com/munter), [@boneskull](https://github.com/boneskull)) diff --git a/node_modules/mocha/LICENSE b/node_modules/mocha/LICENSE index c4dc0c0..5c62253 100644 --- a/node_modules/mocha/LICENSE +++ b/node_modules/mocha/LICENSE @@ -1,6 +1,6 @@ (The MIT License) -Copyright (c) 2011-2021 OpenJS Foundation and contributors, https://openjsf.org +Copyright (c) 2011-2022 OpenJS Foundation and contributors, https://openjsf.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/node_modules/mocha/README.md b/node_modules/mocha/README.md index 15c4d4f..3545f7a 100644 --- a/node_modules/mocha/README.md +++ b/node_modules/mocha/README.md @@ -1,5 +1,5 @@

- Mocha test framework + Mocha test framework logo

☕️ Simple, flexible, fun JavaScript test framework for Node.js & The Browser ☕️

@@ -8,9 +8,9 @@ GitHub Actions Build Status Coverage Status FOSSA Status -Gitter -OpenCollective -OpenCollective +Chat - Discord +OpenCollective Sponsors +OpenCollective Backers

@@ -22,11 +22,12 @@ ## Links -- **[Documentation](https://mochajs.org/)** +- **[Documentation](https://mochajs.org)** - **[Release Notes / History / Changes](https://github.com/mochajs/mocha/blob/master/CHANGELOG.md)** - [Code of Conduct](https://github.com/mochajs/mocha/blob/master/.github/CODE_OF_CONDUCT.md) - [Contributing](https://github.com/mochajs/mocha/blob/master/.github/CONTRIBUTING.md) -- [Gitter Chatroom](https://gitter.im/mochajs/mocha) (ask questions here!) +- [Development](https://github.com/mochajs/mocha/blob/master/.github/DEVELOPMENT.md) +- [Discord](https://discord.gg/KeDn2uXhER) (ask questions here!) - [Issue Tracker](https://github.com/mochajs/mocha/issues) ## Backers @@ -37,7 +38,10 @@ ## Sponsors -Does your company use Mocha? Ask your manager or marketing team if your company would be interested in supporting our project. Support will allow the maintainers to dedicate more time for maintenance and new features for everyone. Also, your company's logo will show [on GitHub](https://github.com/mochajs/mocha#readme) and on [our site](https://mochajs.org#sponsors) - who doesn't want a little extra exposure? [Here's the info](https://opencollective.com/mochajs). +Does your company use Mocha? Ask your manager or marketing team if your company would be interested in supporting our project. +Support will allow the maintainers to dedicate more time for maintenance and new features for everyone. +Also, your company's logo will show [on GitHub](https://github.com/mochajs/mocha#readme) and on [our site](https://mochajs.org#sponsors) - who doesn't want a little extra exposure? +[Here's the info](https://opencollective.com/mochajs). [![MochaJS Sponsor](https://opencollective.com/mochajs/tiers/sponsors/0/avatar)](https://opencollective.com/mochajs/tiers/sponsors/0/website) [![MochaJS Sponsor](https://opencollective.com/mochajs/tiers/sponsors/1/avatar)](https://opencollective.com/mochajs/tiers/sponsors/1/website) @@ -53,11 +57,11 @@ You might want to know that: You might want to help: -- New to contributing to Mocha? Check out this list of [good first issues](https://github.com/mochajs/mocha/issues?q=is%3Aissue+is%3Aopen+label%3Agood-first-issue) -- Mocha could use a hand with [these issues](https://github.com/mochajs/mocha/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) +- New to contributing to Mocha? Check out this list of [good first issues](https://github.com/mochajs/mocha/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22) +- Mocha could use a hand with [these issues](https://github.com/mochajs/mocha/issues?q=is%3Aopen+is%3Aissue+label%3A%22status%3A+accepting+prs%22) - The [maintainer's handbook](https://github.com/mochajs/mocha/blob/master/MAINTAINERS.md) explains how things get done -Finally, come [chat with the maintainers](https://gitter.im/mochajs/contributors) on Gitter if you want to help with: +Finally, come [chat with the maintainers on Discord](https://discord.gg/KeDn2uXhER) if you want to help with: - Triaging issues, answering questions - Review, merging, and closing pull requests @@ -65,6 +69,6 @@ Finally, come [chat with the maintainers](https://gitter.im/mochajs/contributors ## License -Copyright 2011-2021 OpenJS Foundation and contributors. Licensed [MIT](https://github.com/mochajs/mocha/blob/master/LICENSE). +Copyright 2011-2022 OpenJS Foundation and contributors. Licensed [MIT](https://github.com/mochajs/mocha/blob/master/LICENSE). [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha.svg?type=large)](https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha?ref=badge_large) diff --git a/node_modules/mocha/assets/growl/error.png b/node_modules/mocha/assets/growl/error.png deleted file mode 100644 index a07a1ba..0000000 Binary files a/node_modules/mocha/assets/growl/error.png and /dev/null differ diff --git a/node_modules/mocha/assets/growl/ok.png b/node_modules/mocha/assets/growl/ok.png deleted file mode 100644 index b3623a5..0000000 Binary files a/node_modules/mocha/assets/growl/ok.png and /dev/null differ diff --git a/node_modules/mocha/bin/_mocha b/node_modules/mocha/bin/_mocha old mode 100755 new mode 100644 diff --git a/node_modules/mocha/bin/mocha b/node_modules/mocha/bin/mocha.js old mode 100755 new mode 100644 similarity index 77% rename from node_modules/mocha/bin/mocha rename to node_modules/mocha/bin/mocha.js index 79d3556..fb58e65 --- a/node_modules/mocha/bin/mocha +++ b/node_modules/mocha/bin/mocha.js @@ -10,7 +10,6 @@ * @private */ -const {deprecate} = require('../lib/utils'); const {loadOptions} = require('../lib/cli/options'); const { unparseNodeFlags, @@ -23,6 +22,7 @@ const {aliases} = require('../lib/cli/run-option-metadata'); const mochaArgs = {}; const nodeArgs = {}; +let hasInspect = false; const opts = loadOptions(process.argv.slice(2)); debug('loaded opts', opts); @@ -59,48 +59,39 @@ Object.keys(opts).forEach(opt => { // disable 'timeout' for debugFlags Object.keys(nodeArgs).forEach(opt => disableTimeouts(opt)); +mochaArgs['node-option'] && + mochaArgs['node-option'].forEach(opt => disableTimeouts(opt)); // Native debugger handling // see https://nodejs.org/api/debugger.html#debugger_debugger -// look for 'inspect' or 'debug' that would launch this debugger, +// look for 'inspect' that would launch this debugger, // remove it from Mocha's opts and prepend it to Node's opts. // A deprecation warning will be printed by node, if applicable. // (mochaArgs._ are "positional" arguments, not prefixed with - or --) if (mochaArgs._) { - const i = mochaArgs._.findIndex(val => val === 'inspect' || val === 'debug'); + const i = mochaArgs._.findIndex(val => val === 'inspect'); if (i > -1) { - const [command] = mochaArgs._.splice(i, 1); + mochaArgs._.splice(i, 1); disableTimeouts('inspect'); - nodeArgs._ = [command]; + hasInspect = true; } } -// historical -if (nodeArgs.gc) { - deprecate( - '"-gc" is deprecated and will be removed from a future version of Mocha. Use "--gc-global" instead.' - ); - nodeArgs['gc-global'] = nodeArgs.gc; - delete nodeArgs.gc; -} - -// --require/-r is treated as Mocha flag except when 'esm' is preloaded -if (mochaArgs.require && mochaArgs.require.includes('esm')) { - nodeArgs.require = ['esm']; - mochaArgs.require = mochaArgs.require.filter(mod => mod !== 'esm'); - if (!mochaArgs.require.length) { - delete mochaArgs.require; - } -} - -if (Object.keys(nodeArgs).length) { +if (mochaArgs['node-option'] || Object.keys(nodeArgs).length || hasInspect) { const {spawn} = require('child_process'); const mochaPath = require.resolve('../lib/cli/cli.js'); - debug('final node args', nodeArgs); + const nodeArgv = + (mochaArgs['node-option'] && mochaArgs['node-option'].map(v => '--' + v)) || + unparseNodeFlags(nodeArgs); + + if (hasInspect) nodeArgv.unshift('inspect'); + delete mochaArgs['node-option']; + + debug('final node argv', nodeArgv); const args = [].concat( - unparseNodeFlags(nodeArgs), + nodeArgv, mochaPath, unparse(mochaArgs, {alias: aliases}) ); @@ -147,5 +138,5 @@ if (Object.keys(nodeArgs).length) { }); } else { debug('running Mocha in-process'); - require('../lib/cli/cli').main(unparse(mochaArgs, {alias: aliases})); + require('../lib/cli/cli').main([], mochaArgs); } diff --git a/node_modules/mocha/browser-entry.js b/node_modules/mocha/browser-entry.js index dee3789..67517db 100644 --- a/node_modules/mocha/browser-entry.js +++ b/node_modules/mocha/browser-entry.js @@ -40,12 +40,12 @@ var originalOnerrorHandler = global.onerror; * Revert to original onerror handler if previously defined. */ -process.removeListener = function(e, fn) { +process.removeListener = function (e, fn) { if (e === 'uncaughtException') { if (originalOnerrorHandler) { global.onerror = originalOnerrorHandler; } else { - global.onerror = function() {}; + global.onerror = function () {}; } var i = uncaughtExceptionHandlers.indexOf(fn); if (i !== -1) { @@ -58,7 +58,7 @@ process.removeListener = function(e, fn) { * Implements listenerCount for 'uncaughtException'. */ -process.listenerCount = function(name) { +process.listenerCount = function (name) { if (name === 'uncaughtException') { return uncaughtExceptionHandlers.length; } @@ -69,9 +69,9 @@ process.listenerCount = function(name) { * Implements uncaughtException listener. */ -process.on = function(e, fn) { +process.on = function (e, fn) { if (e === 'uncaughtException') { - global.onerror = function(err, url, line) { + global.onerror = function (err, url, line) { fn(new Error(err + ' (' + url + ':' + line + ')')); return !mocha.options.allowUncaught; }; @@ -79,7 +79,7 @@ process.on = function(e, fn) { } }; -process.listeners = function(e) { +process.listeners = function (e) { if (e === 'uncaughtException') { return uncaughtExceptionHandlers; } @@ -110,7 +110,7 @@ function timeslice() { * High-performance override of Runner.immediately. */ -Mocha.Runner.immediately = function(callback) { +Mocha.Runner.immediately = function (callback) { immediateQueue.push(callback); if (!immediateTimeout) { immediateTimeout = setTimeout(timeslice, 0); @@ -122,8 +122,8 @@ Mocha.Runner.immediately = function(callback) { * This is useful when running tests in a browser because window.onerror will * only receive the 'message' attribute of the Error. */ -mocha.throwError = function(err) { - uncaughtExceptionHandlers.forEach(function(fn) { +mocha.throwError = function (err) { + uncaughtExceptionHandlers.forEach(function (fn) { fn(err); }); throw err; @@ -134,7 +134,7 @@ mocha.throwError = function(err) { * Normally this would happen in Mocha.prototype.loadFiles. */ -mocha.ui = function(ui) { +mocha.ui = function (ui) { Mocha.prototype.ui.call(this, ui); this.suite.emit('pre-require', global, null, this); return this; @@ -144,7 +144,7 @@ mocha.ui = function(ui) { * Setup mocha with the given setting options. */ -mocha.setup = function(opts) { +mocha.setup = function (opts) { if (typeof opts === 'string') { opts = {ui: opts}; } @@ -153,10 +153,10 @@ mocha.setup = function(opts) { } var self = this; Object.keys(opts) - .filter(function(opt) { + .filter(function (opt) { return opt !== 'delay'; }) - .forEach(function(opt) { + .forEach(function (opt) { if (Object.prototype.hasOwnProperty.call(opts, opt)) { self[opt](opts[opt]); } @@ -168,7 +168,7 @@ mocha.setup = function(opts) { * Run mocha, returning the Runner. */ -mocha.run = function(fn) { +mocha.run = function (fn) { var options = mocha.options; mocha.globals('location'); @@ -183,7 +183,7 @@ mocha.run = function(fn) { mocha.invert(); } - return Mocha.prototype.run.call(mocha, function(err) { + return Mocha.prototype.run.call(mocha, function (err) { // The DOM Document is not available in Web Workers. var document = global.document; if ( @@ -209,11 +209,18 @@ Mocha.process = process; /** * Expose mocha. */ - global.Mocha = Mocha; global.mocha = mocha; -// this allows test/acceptance/required-tokens.js to pass; thus, -// you can now do `const describe = require('mocha').describe` in a -// browser context (assuming browserification). should fix #880 -module.exports = Object.assign(mocha, global); +// for bundlers: enable `import {describe, it} from 'mocha'` +// `bdd` interface only +// prettier-ignore +[ + 'describe', 'context', 'it', 'specify', + 'xdescribe', 'xcontext', 'xit', 'xspecify', + 'before', 'beforeEach', 'afterEach', 'after' +].forEach(function(key) { + mocha[key] = global[key]; +}); + +module.exports = mocha; diff --git a/node_modules/mocha/lib/browser/growl.js b/node_modules/mocha/lib/browser/growl.js deleted file mode 100644 index 7b46b8e..0000000 --- a/node_modules/mocha/lib/browser/growl.js +++ /dev/null @@ -1,169 +0,0 @@ -'use strict'; - -/** - * Web Notifications module. - * @module Growl - */ - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ -var Date = global.Date; -var setTimeout = global.setTimeout; -var EVENT_RUN_END = require('../runner').constants.EVENT_RUN_END; -var isBrowser = require('../utils').isBrowser; - -/** - * Checks if browser notification support exists. - * - * @public - * @see {@link https://caniuse.com/#feat=notifications|Browser support (notifications)} - * @see {@link https://caniuse.com/#feat=promises|Browser support (promises)} - * @see {@link Mocha#growl} - * @see {@link Mocha#isGrowlCapable} - * @return {boolean} whether browser notification support exists - */ -exports.isCapable = function() { - var hasNotificationSupport = 'Notification' in window; - var hasPromiseSupport = typeof Promise === 'function'; - return isBrowser() && hasNotificationSupport && hasPromiseSupport; -}; - -/** - * Implements browser notifications as a pseudo-reporter. - * - * @public - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/notification|Notification API} - * @see {@link https://developers.google.com/web/fundamentals/push-notifications/display-a-notification|Displaying a Notification} - * @see {@link Growl#isPermitted} - * @see {@link Mocha#_growl} - * @param {Runner} runner - Runner instance. - */ -exports.notify = function(runner) { - var promise = isPermitted(); - - /** - * Attempt notification. - */ - var sendNotification = function() { - // If user hasn't responded yet... "No notification for you!" (Seinfeld) - Promise.race([promise, Promise.resolve(undefined)]) - .then(canNotify) - .then(function() { - display(runner); - }) - .catch(notPermitted); - }; - - runner.once(EVENT_RUN_END, sendNotification); -}; - -/** - * Checks if browser notification is permitted by user. - * - * @private - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission} - * @see {@link Mocha#growl} - * @see {@link Mocha#isGrowlPermitted} - * @returns {Promise} promise determining if browser notification - * permissible when fulfilled. - */ -function isPermitted() { - var permitted = { - granted: function allow() { - return Promise.resolve(true); - }, - denied: function deny() { - return Promise.resolve(false); - }, - default: function ask() { - return Notification.requestPermission().then(function(permission) { - return permission === 'granted'; - }); - } - }; - - return permitted[Notification.permission](); -} - -/** - * @summary - * Determines if notification should proceed. - * - * @description - * Notification shall not proceed unless `value` is true. - * - * `value` will equal one of: - *

    - *
  • true (from `isPermitted`)
  • - *
  • false (from `isPermitted`)
  • - *
  • undefined (from `Promise.race`)
  • - *
- * - * @private - * @param {boolean|undefined} value - Determines if notification permissible. - * @returns {Promise} Notification can proceed - */ -function canNotify(value) { - if (!value) { - var why = value === false ? 'blocked' : 'unacknowledged'; - var reason = 'not permitted by user (' + why + ')'; - return Promise.reject(new Error(reason)); - } - return Promise.resolve(); -} - -/** - * Displays the notification. - * - * @private - * @param {Runner} runner - Runner instance. - */ -function display(runner) { - var stats = runner.stats; - var symbol = { - cross: '\u274C', - tick: '\u2705' - }; - var logo = require('../../package.json').notifyLogo; - var _message; - var message; - var title; - - if (stats.failures) { - _message = stats.failures + ' of ' + stats.tests + ' tests failed'; - message = symbol.cross + ' ' + _message; - title = 'Failed'; - } else { - _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; - message = symbol.tick + ' ' + _message; - title = 'Passed'; - } - - // Send notification - var options = { - badge: logo, - body: message, - dir: 'ltr', - icon: logo, - lang: 'en-US', - name: 'mocha', - requireInteraction: false, - timestamp: Date.now() - }; - var notification = new Notification(title, options); - - // Autoclose after brief delay (makes various browsers act same) - var FORCE_DURATION = 4000; - setTimeout(notification.close.bind(notification), FORCE_DURATION); -} - -/** - * As notifications are tangential to our purpose, just log the error. - * - * @private - * @param {Error} err - Why notification didn't happen. - */ -function notPermitted(err) { - console.error('notification error:', err.message); -} diff --git a/node_modules/mocha/lib/browser/parse-query.js b/node_modules/mocha/lib/browser/parse-query.js index dc1a884..3a7ac1a 100644 --- a/node_modules/mocha/lib/browser/parse-query.js +++ b/node_modules/mocha/lib/browser/parse-query.js @@ -11,7 +11,7 @@ module.exports = function parseQuery(qs) { return qs .replace('?', '') .split('&') - .reduce(function(obj, pair) { + .reduce(function (obj, pair) { var i = pair.indexOf('='); var key = pair.slice(0, i); var val = pair.slice(++i); diff --git a/node_modules/mocha/lib/browser/progress.js b/node_modules/mocha/lib/browser/progress.js index 72ce5c5..c82bc08 100644 --- a/node_modules/mocha/lib/browser/progress.js +++ b/node_modules/mocha/lib/browser/progress.js @@ -27,7 +27,7 @@ function Progress() { * @param {number} size * @return {Progress} Progress instance. */ -Progress.prototype.size = function(size) { +Progress.prototype.size = function (size) { this._size = size; return this; }; @@ -39,7 +39,7 @@ Progress.prototype.size = function(size) { * @param {string} text * @return {Progress} Progress instance. */ -Progress.prototype.text = function(text) { +Progress.prototype.text = function (text) { this._text = text; return this; }; @@ -51,7 +51,7 @@ Progress.prototype.text = function(text) { * @param {number} size * @return {Progress} Progress instance. */ -Progress.prototype.fontSize = function(size) { +Progress.prototype.fontSize = function (size) { this._fontSize = size; return this; }; @@ -62,7 +62,7 @@ Progress.prototype.fontSize = function(size) { * @param {string} family * @return {Progress} Progress instance. */ -Progress.prototype.font = function(family) { +Progress.prototype.font = function (family) { this._font = family; return this; }; @@ -73,7 +73,7 @@ Progress.prototype.font = function(family) { * @param {number} n * @return {Progress} Progress instance. */ -Progress.prototype.update = function(n) { +Progress.prototype.update = function (n) { this.percent = n; return this; }; @@ -84,8 +84,22 @@ Progress.prototype.update = function(n) { * @param {CanvasRenderingContext2d} ctx * @return {Progress} Progress instance. */ -Progress.prototype.draw = function(ctx) { +Progress.prototype.draw = function (ctx) { try { + var darkMatcher = window.matchMedia('(prefers-color-scheme: dark)'); + var isDarkMode = !!darkMatcher.matches; + var lightColors = { + outerCircle: '#9f9f9f', + innerCircle: '#eee', + text: '#000' + }; + var darkColors = { + outerCircle: '#888', + innerCircle: '#444', + text: '#fff' + }; + var colors = isDarkMode ? darkColors : lightColors; + var percent = Math.min(this.percent, 100); var size = this._size; var half = size / 2; @@ -100,13 +114,13 @@ Progress.prototype.draw = function(ctx) { ctx.clearRect(0, 0, size, size); // outer circle - ctx.strokeStyle = '#9f9f9f'; + ctx.strokeStyle = colors.outerCircle; ctx.beginPath(); ctx.arc(x, y, rad, 0, angle, false); ctx.stroke(); // inner circle - ctx.strokeStyle = '#eee'; + ctx.strokeStyle = colors.innerCircle; ctx.beginPath(); ctx.arc(x, y, rad - 1, 0, angle, true); ctx.stroke(); @@ -115,6 +129,7 @@ Progress.prototype.draw = function(ctx) { var text = this._text || (percent | 0) + '%'; var w = ctx.measureText(text).width; + ctx.fillStyle = colors.text; ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1); } catch (ignore) { // don't fail if we can't render progress diff --git a/node_modules/mocha/lib/cli/cli.js b/node_modules/mocha/lib/cli/cli.js old mode 100755 new mode 100644 index f3b780c..b1b5354 --- a/node_modules/mocha/lib/cli/cli.js +++ b/node_modules/mocha/lib/cli/cli.js @@ -23,7 +23,7 @@ const { const lookupFiles = require('./lookup-files'); const commands = require('./commands'); const ansi = require('ansi-colors'); -const {repository, homepage, version, gitter} = require('../../package.json'); +const {repository, homepage, version, discord} = require('../../package.json'); const {cwd} = require('../utils'); /** @@ -33,8 +33,9 @@ const {cwd} = require('../utils'); * @public * @summary Mocha's main command-line entry-point. * @param {string[]} argv - Array of arguments to parse, or by default the lovely `process.argv.slice(2)` + * @param {object} [mochaArgs] - Object of already parsed Mocha arguments (by bin/mocha) */ -exports.main = (argv = process.argv.slice(2)) => { +exports.main = (argv = process.argv.slice(2), mochaArgs) => { debug('entered main with raw args', argv); // ensure we can require() from current working directory if (typeof module.paths !== 'undefined') { @@ -43,7 +44,7 @@ exports.main = (argv = process.argv.slice(2)) => { Error.stackTraceLimit = Infinity; // configurable via --stack-trace-limit? - var args = loadOptions(argv); + var args = mochaArgs || loadOptions(argv); yargs() .scriptName('mocha') @@ -67,7 +68,7 @@ exports.main = (argv = process.argv.slice(2)) => { .wrap(process.stdout.columns ? Math.min(process.stdout.columns, 80) : 80) .epilog( `Mocha Resources - Chat: ${ansi.magenta(gitter)} + Chat: ${ansi.magenta(discord)} GitHub: ${ansi.blue(repository.url)} Docs: ${ansi.yellow(homepage)} ` diff --git a/node_modules/mocha/lib/cli/collect-files.js b/node_modules/mocha/lib/cli/collect-files.js index 39934cb..cc04559 100644 --- a/node_modules/mocha/lib/cli/collect-files.js +++ b/node_modules/mocha/lib/cli/collect-files.js @@ -35,7 +35,10 @@ module.exports = ({ try { const moreSpecFiles = castArray(lookupFiles(arg, extension, recursive)) .filter(filename => - ignore.every(pattern => !minimatch(filename, pattern)) + ignore.every( + pattern => + !minimatch(filename, pattern, {windowsPathsNoEscape: true}) + ) ) .map(filename => path.resolve(filename)); return [...specFiles, ...moreSpecFiles]; diff --git a/node_modules/mocha/lib/cli/commands.js b/node_modules/mocha/lib/cli/commands.js index eb10c68..1102f86 100644 --- a/node_modules/mocha/lib/cli/commands.js +++ b/node_modules/mocha/lib/cli/commands.js @@ -2,7 +2,7 @@ /** * Exports Yargs commands - * @see https://git.io/fpJ0G + * @see https://github.com/yargs/yargs/blob/main/docs/advanced.md * @private * @module */ diff --git a/node_modules/mocha/lib/cli/config.js b/node_modules/mocha/lib/cli/config.js index b7510d7..ac71983 100644 --- a/node_modules/mocha/lib/cli/config.js +++ b/node_modules/mocha/lib/cli/config.js @@ -30,10 +30,6 @@ exports.CONFIG_FILES = [ '.mocharc.json' ]; -const isModuleNotFoundError = err => - err.code !== 'MODULE_NOT_FOUND' || - err.message.indexOf('Cannot find module') !== -1; - /** * Parsers for various config filetypes. Each accepts a filepath and * returns an object (but could throw) @@ -41,17 +37,16 @@ const isModuleNotFoundError = err => const parsers = (exports.parsers = { yaml: filepath => require('js-yaml').load(fs.readFileSync(filepath, 'utf8')), js: filepath => { - const cwdFilepath = path.resolve(filepath); + let cwdFilepath; try { - debug('parsers: load using cwd-relative path: "%s"', cwdFilepath); + debug('parsers: load cwd-relative path: "%s"', path.resolve(filepath)); + cwdFilepath = require.resolve(path.resolve(filepath)); // evtl. throws return require(cwdFilepath); } catch (err) { - if (isModuleNotFoundError(err)) { - debug('parsers: retry load as module-relative path: "%s"', filepath); - return require(filepath); - } else { - throw err; // rethrow - } + if (cwdFilepath) throw err; + + debug('parsers: retry load as module-relative path: "%s"', filepath); + return require(filepath); } }, json: filepath => diff --git a/node_modules/mocha/lib/cli/lookup-files.js b/node_modules/mocha/lib/cli/lookup-files.js index 0ad957c..7b3cdd1 100644 --- a/node_modules/mocha/lib/cli/lookup-files.js +++ b/node_modules/mocha/lib/cli/lookup-files.js @@ -8,11 +8,9 @@ var fs = require('fs'); var path = require('path'); var glob = require('glob'); -var {format} = require('util'); var errors = require('../errors'); var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError; var createMissingArgumentError = errors.createMissingArgumentError; -var {sQuote, dQuote} = require('../utils'); const debug = require('debug')('mocha:cli:lookup-files'); /** @@ -77,7 +75,7 @@ module.exports = function lookupFiles( if (!fs.existsSync(filepath)) { let pattern; - if (glob.hasMagic(filepath)) { + if (glob.hasMagic(filepath, {windowsPathsNoEscape: true})) { // Handle glob as is without extensions pattern = filepath; } else { @@ -88,10 +86,15 @@ module.exports = function lookupFiles( pattern = `${filepath}+(${strExtensions})`; debug('looking for files using glob pattern: %s', pattern); } - files.push(...glob.sync(pattern, {nodir: true})); + files.push( + ...glob.sync(pattern, { + nodir: true, + windowsPathsNoEscape: true + }) + ); if (!files.length) { throw createNoFilesMatchPatternError( - 'Cannot find any files matching pattern ' + dQuote(filepath), + `Cannot find any files matching pattern "${filepath}"`, filepath ); } @@ -127,11 +130,7 @@ module.exports = function lookupFiles( } if (!extensions.length) { throw createMissingArgumentError( - format( - 'Argument %s required when argument %s is a directory', - sQuote('extensions'), - sQuote('filepath') - ), + `Argument '${extensions}' required when argument '${filepath}' is a directory`, 'extensions', 'array' ); diff --git a/node_modules/mocha/lib/cli/node-flags.js b/node_modules/mocha/lib/cli/node-flags.js index 1203ad2..25ca266 100644 --- a/node_modules/mocha/lib/cli/node-flags.js +++ b/node_modules/mocha/lib/cli/node-flags.js @@ -49,7 +49,7 @@ exports.isNodeFlag = (flag, bareword = true) => { // and also any V8 flags with `--v8-` prefix (!isMochaFlag(flag) && nodeFlags && nodeFlags.has(flag)) || debugFlags.has(flag) || - /(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc(?:[_-]global)?$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test( + /(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc[_-]global$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test( flag ) ); @@ -67,7 +67,6 @@ exports.impliesNoTimeouts = flag => debugFlags.has(flag); /** * All non-strictly-boolean arguments to node--those with values--must specify those values using `=`, e.g., `--inspect=0.0.0.0`. * Unparse these arguments using `yargs-unparser` (which would result in `--inspect 0.0.0.0`), then supply `=` where we have values. - * Apparently --require in Node.js v8 does NOT want `=`. * There's probably an easier or more robust way to do this; fixes welcome * @param {Object} opts - Arguments object * @returns {string[]} Unparsed arguments using `=` to specify values @@ -79,9 +78,7 @@ exports.unparseNodeFlags = opts => { ? args .join(' ') .split(/\b/) - .map((arg, index, args) => - arg === ' ' && args[index - 1] !== 'require' ? '=' : arg - ) + .map(arg => (arg === ' ' ? '=' : arg)) .join('') .split(' ') : []; diff --git a/node_modules/mocha/lib/cli/one-and-dones.js b/node_modules/mocha/lib/cli/one-and-dones.js index 56fc1af..21bad6f 100644 --- a/node_modules/mocha/lib/cli/one-and-dones.js +++ b/node_modules/mocha/lib/cli/one-and-dones.js @@ -8,7 +8,6 @@ * @private */ -const align = require('wide-align'); const Mocha = require('../mocha'); /** @@ -30,7 +29,7 @@ const showKeys = obj => { .forEach(key => { const description = obj[key].description; console.log( - ` ${align.left(key, maxKeyLength + 1)}${ + ` ${key.padEnd(maxKeyLength + 1)}${ description ? `- ${description}` : '' }` ); diff --git a/node_modules/mocha/lib/cli/run-helpers.js b/node_modules/mocha/lib/cli/run-helpers.js index dfac8b4..078ca7e 100644 --- a/node_modules/mocha/lib/cli/run-helpers.js +++ b/node_modules/mocha/lib/cli/run-helpers.js @@ -14,7 +14,7 @@ const {watchRun, watchParallelRun} = require('./watch-run'); const collectFiles = require('./collect-files'); const {format} = require('util'); const {createInvalidLegacyPluginError} = require('../errors'); -const {requireOrImport} = require('../esm-utils'); +const {requireOrImport} = require('../nodejs/esm-utils'); const PluginLoader = require('../plugin-loader'); /** @@ -195,10 +195,10 @@ exports.runMocha = async (mocha, options) => { * it actually exists. This must be run _after_ requires are processed (see * {@link handleRequires}), as it'll prevent interfaces from loading otherwise. * @param {Object} opts - Options object - * @param {"reporter"|"interface"} pluginType - Type of plugin. - * @param {Object} [map] - An object perhaps having key `key`. Used as a cache - * of sorts; `Mocha.reporters` is one, where each key corresponds to a reporter - * name + * @param {"reporter"|"ui"} pluginType - Type of plugin. + * @param {Object} [map] - Used as a cache of sorts; + * `Mocha.reporters` where each key corresponds to a reporter name, + * `Mocha.interfaces` where each key corresponds to an interface name. * @private */ exports.validateLegacyPlugin = (opts, pluginType, map = {}) => { @@ -225,18 +225,18 @@ exports.validateLegacyPlugin = (opts, pluginType, map = {}) => { // if this exists, then it's already loaded, so nothing more to do. if (!map[pluginId]) { + let foundId; try { - opts[pluginType] = require(pluginId); + foundId = require.resolve(pluginId); + map[pluginId] = require(foundId); } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - // Try to load reporters from a path (absolute or relative) - try { - opts[pluginType] = require(path.resolve(pluginId)); - } catch (err) { - throw createUnknownError(err); - } - } else { - throw createUnknownError(err); + if (foundId) throw createUnknownError(err); + + // Try to load reporters from a cwd-relative path + try { + map[pluginId] = require(path.resolve(pluginId)); + } catch (e) { + throw createUnknownError(e); } } } diff --git a/node_modules/mocha/lib/cli/run-option-metadata.js b/node_modules/mocha/lib/cli/run-option-metadata.js index 33cd15a..492608f 100644 --- a/node_modules/mocha/lib/cli/run-option-metadata.js +++ b/node_modules/mocha/lib/cli/run-option-metadata.js @@ -18,6 +18,7 @@ const TYPES = (exports.types = { 'file', 'global', 'ignore', + 'node-option', 'reporter-option', 'require', 'spec', @@ -32,11 +33,12 @@ const TYPES = (exports.types = { 'color', 'delay', 'diff', + 'dry-run', 'exit', + 'fail-zero', 'forbid-only', 'forbid-pending', 'full-trace', - 'growl', 'inline-diffs', 'invert', 'list-interfaces', @@ -73,11 +75,11 @@ exports.aliases = { fgrep: ['f'], global: ['globals'], grep: ['g'], - growl: ['G'], ignore: ['exclude'], invert: ['i'], jobs: ['j'], 'no-colors': ['C'], + 'node-option': ['n'], parallel: ['p'], reporter: ['R'], 'reporter-option': ['reporter-options', 'O'], diff --git a/node_modules/mocha/lib/cli/run.js b/node_modules/mocha/lib/cli/run.js index a8c8b61..66c8cbb 100644 --- a/node_modules/mocha/lib/cli/run.js +++ b/node_modules/mocha/lib/cli/run.js @@ -83,6 +83,10 @@ exports.builder = yargs => description: 'Show diff on failure', group: GROUPS.OUTPUT }, + 'dry-run': { + description: 'Report tests without executing them', + group: GROUPS.RULES + }, exit: { description: 'Force Mocha to quit after tests complete', group: GROUPS.RULES @@ -94,6 +98,10 @@ exports.builder = yargs => requiresArg: true, coerce: list }, + 'fail-zero': { + description: 'Fail test run if no test(s) encountered', + group: GROUPS.RULES + }, fgrep: { conflicts: 'grep', description: 'Only run tests containing this string', @@ -133,10 +141,6 @@ exports.builder = yargs => group: GROUPS.FILTERS, requiresArg: true }, - growl: { - description: 'Enable Growl notifications', - group: GROUPS.OUTPUT - }, ignore: { defaultDescription: '(none)', description: 'Ignore file(s) or glob pattern(s)', @@ -172,6 +176,10 @@ exports.builder = yargs => group: GROUPS.OUTPUT, hidden: true }, + 'node-option': { + description: 'Node or V8 option (no leading "--")', + group: GROUPS.CONFIG + }, package: { description: 'Path to package.json for config', group: GROUPS.CONFIG, @@ -321,7 +329,7 @@ exports.builder = yargs => if (argv.compilers) { throw createUnsupportedError( `--compilers is DEPRECATED and no longer supported. - See https://git.io/vdcSr for migration information.` + See https://github.com/mochajs/mocha/wiki/compilers-deprecation for migration information.` ); } @@ -354,14 +362,14 @@ exports.builder = yargs => .number(types.number) .alias(aliases); -exports.handler = async function(argv) { +exports.handler = async function (argv) { debug('post-yargs config', argv); const mocha = new Mocha(argv); try { await runMocha(mocha, argv); } catch (err) { - console.error('\n' + (err.stack || `Error: ${err.message || err}`)); + console.error('\n Exception during run:', err); process.exit(1); } }; diff --git a/node_modules/mocha/lib/cli/watch-run.js b/node_modules/mocha/lib/cli/watch-run.js index dabcd53..a77ed7a 100644 --- a/node_modules/mocha/lib/cli/watch-run.js +++ b/node_modules/mocha/lib/cli/watch-run.js @@ -46,7 +46,7 @@ exports.watchParallelRun = ( // this `require` is needed because the require cache has been cleared. the dynamic // exports set via the below call to `mocha.ui()` won't work properly if a - // test depends on this module (see `required-tokens.spec.js`). + // test depends on this module. const Mocha = require('../mocha'); // ... and now that we've gotten a new module, we need to use it again due @@ -108,7 +108,7 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => { // this `require` is needed because the require cache has been cleared. the dynamic // exports set via the below call to `mocha.ui()` won't work properly if a - // test depends on this module (see `required-tokens.spec.js`). + // test depends on this module. const Mocha = require('../mocha'); // ... and now that we've gotten a new module, we need to use it again due @@ -231,10 +231,7 @@ const createWatcher = ( process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.on('data', data => { - const str = data - .toString() - .trim() - .toLowerCase(); + const str = data.toString().trim().toLowerCase(); if (str === 'rs') rerunner.scheduleRun(); }); diff --git a/node_modules/mocha/lib/context.js b/node_modules/mocha/lib/context.js index 2497ded..388d308 100644 --- a/node_modules/mocha/lib/context.js +++ b/node_modules/mocha/lib/context.js @@ -22,7 +22,7 @@ function Context() {} * @param {Runnable} runnable * @return {Context} context */ -Context.prototype.runnable = function(runnable) { +Context.prototype.runnable = function (runnable) { if (!arguments.length) { return this._runnable; } @@ -37,7 +37,7 @@ Context.prototype.runnable = function(runnable) { * @param {number} ms * @return {Context} self */ -Context.prototype.timeout = function(ms) { +Context.prototype.timeout = function (ms) { if (!arguments.length) { return this.runnable().timeout(); } @@ -52,7 +52,7 @@ Context.prototype.timeout = function(ms) { * @param {number} ms * @return {Context} self */ -Context.prototype.slow = function(ms) { +Context.prototype.slow = function (ms) { if (!arguments.length) { return this.runnable().slow(); } @@ -66,7 +66,7 @@ Context.prototype.slow = function(ms) { * @private * @throws Pending */ -Context.prototype.skip = function() { +Context.prototype.skip = function () { this.runnable().skip(); }; @@ -77,7 +77,7 @@ Context.prototype.skip = function() { * @param {number} n * @return {Context} self */ -Context.prototype.retries = function(n) { +Context.prototype.retries = function (n) { if (!arguments.length) { return this.runnable().retries(); } diff --git a/node_modules/mocha/lib/errors.js b/node_modules/mocha/lib/errors.js index 681198a..bcc7291 100644 --- a/node_modules/mocha/lib/errors.js +++ b/node_modules/mocha/lib/errors.js @@ -18,7 +18,7 @@ const emitWarning = (msg, type) => { process.emitWarning(msg, type); } else { /* istanbul ignore next */ - process.nextTick(function() { + process.nextTick(function () { console.warn(type + ': ' + msg); }); } @@ -328,7 +328,7 @@ function createFatalError(message, value) { /** * Dynamically creates a plugin-type-specific error based on plugin type * @param {string} message - Error message - * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed + * @param {"reporter"|"ui"} pluginType - Plugin type. Future: expand as needed * @param {string} [pluginId] - Name/path of plugin, if any * @throws When `pluginType` is not known * @public @@ -339,7 +339,7 @@ function createInvalidLegacyPluginError(message, pluginType, pluginId) { switch (pluginType) { case 'reporter': return createInvalidReporterError(message, pluginId); - case 'interface': + case 'ui': return createInvalidInterfaceError(message, pluginId); default: throw new Error('unknown pluginType "' + pluginType + '"'); diff --git a/node_modules/mocha/lib/esm-utils.js b/node_modules/mocha/lib/esm-utils.js deleted file mode 100644 index eebeb93..0000000 --- a/node_modules/mocha/lib/esm-utils.js +++ /dev/null @@ -1,58 +0,0 @@ -const path = require('path'); -const url = require('url'); - -const formattedImport = async file => { - if (path.isAbsolute(file)) { - try { - return await import(url.pathToFileURL(file)); - } catch (err) { - // This is a hack created because ESM in Node.js (at least in Node v15.5.1) does not emit - // the location of the syntax error in the error thrown. - // This is problematic because the user can't see what file has the problem, - // so we add the file location to the error. - // This `if` should be removed once Node.js fixes the problem. - if ( - err instanceof SyntaxError && - err.message && - err.stack && - !err.stack.includes(file) - ) { - const newErrorWithFilename = new SyntaxError(err.message); - newErrorWithFilename.stack = err.stack.replace( - /^SyntaxError/, - `SyntaxError[ @${file} ]` - ); - throw newErrorWithFilename; - } - throw err; - } - } - return import(file); -}; - -exports.requireOrImport = async file => { - if (path.extname(file) === '.mjs') { - return formattedImport(file); - } - // This is currently the only known way of figuring out whether a file is CJS or ESM. - // If Node.js or the community establish a better procedure for that, we can fix this code. - // Another option here would be to always use `import()`, as this also supports CJS, but I would be - // wary of using it for _all_ existing test files, till ESM is fully stable. - try { - return require(file); - } catch (err) { - if (err.code === 'ERR_REQUIRE_ESM') { - return formattedImport(file); - } else { - throw err; - } - } -}; - -exports.loadFilesAsync = async (files, preLoadFunc, postLoadFunc) => { - for (const file of files) { - preLoadFunc(file); - const result = await exports.requireOrImport(path.resolve(file)); - postLoadFunc(file, result); - } -}; diff --git a/node_modules/mocha/lib/hook.js b/node_modules/mocha/lib/hook.js index 890086f..862271e 100644 --- a/node_modules/mocha/lib/hook.js +++ b/node_modules/mocha/lib/hook.js @@ -31,7 +31,7 @@ inherits(Hook, Runnable); /** * Resets the state for a next run. */ -Hook.prototype.reset = function() { +Hook.prototype.reset = function () { Runnable.prototype.reset.call(this); delete this._error; }; @@ -44,7 +44,7 @@ Hook.prototype.reset = function() { * @param {Error} err * @return {Error} */ -Hook.prototype.error = function(err) { +Hook.prototype.error = function (err) { if (!arguments.length) { err = this._error; this._error = null; @@ -62,7 +62,9 @@ Hook.prototype.error = function(err) { */ Hook.prototype.serialize = function serialize() { return { - $$isPending: this.isPending(), + $$currentRetry: this.currentRetry(), + $$fullTitle: this.fullTitle(), + $$isPending: Boolean(this.isPending()), $$titlePath: this.titlePath(), ctx: this.ctx && this.ctx.currentTest @@ -73,9 +75,13 @@ Hook.prototype.serialize = function serialize() { } } : {}, + duration: this.duration, + file: this.file, parent: { + $$fullTitle: this.parent.fullTitle(), [MOCHA_ID_PROP_NAME]: this.parent.id }, + state: this.state, title: this.title, type: this.type, [MOCHA_ID_PROP_NAME]: this.id diff --git a/node_modules/mocha/lib/interfaces/bdd.js b/node_modules/mocha/lib/interfaces/bdd.js index 65a6b9f..4058161 100644 --- a/node_modules/mocha/lib/interfaces/bdd.js +++ b/node_modules/mocha/lib/interfaces/bdd.js @@ -1,8 +1,8 @@ 'use strict'; var Test = require('../test'); -var EVENT_FILE_PRE_REQUIRE = require('../suite').constants - .EVENT_FILE_PRE_REQUIRE; +var EVENT_FILE_PRE_REQUIRE = + require('../suite').constants.EVENT_FILE_PRE_REQUIRE; /** * BDD-style interface: @@ -24,7 +24,7 @@ var EVENT_FILE_PRE_REQUIRE = require('../suite').constants module.exports = function bddInterface(suite) { var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) { + suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) { var common = require('./common')(suites, context, mocha); context.before = common.before; @@ -38,11 +38,11 @@ module.exports = function bddInterface(suite) { * and/or tests. */ - context.describe = context.context = function(title, fn) { + context.describe = context.context = function (title, fn) { return common.suite.create({ - title: title, - file: file, - fn: fn + title, + file, + fn }); }; @@ -50,26 +50,26 @@ module.exports = function bddInterface(suite) { * Pending describe. */ - context.xdescribe = context.xcontext = context.describe.skip = function( - title, - fn - ) { - return common.suite.skip({ - title: title, - file: file, - fn: fn - }); - }; + context.xdescribe = + context.xcontext = + context.describe.skip = + function (title, fn) { + return common.suite.skip({ + title, + file, + fn + }); + }; /** * Exclusive suite. */ - context.describe.only = function(title, fn) { + context.describe.only = function (title, fn) { return common.suite.only({ - title: title, - file: file, - fn: fn + title, + file, + fn }); }; @@ -79,7 +79,7 @@ module.exports = function bddInterface(suite) { * acting as a thunk. */ - context.it = context.specify = function(title, fn) { + context.it = context.specify = function (title, fn) { var suite = suites[0]; if (suite.isPending()) { fn = null; @@ -94,7 +94,7 @@ module.exports = function bddInterface(suite) { * Exclusive test-case. */ - context.it.only = function(title, fn) { + context.it.only = function (title, fn) { return common.test.only(mocha, context.it(title, fn)); }; @@ -102,9 +102,12 @@ module.exports = function bddInterface(suite) { * Pending test case. */ - context.xit = context.xspecify = context.it.skip = function(title) { - return context.it(title); - }; + context.xit = + context.xspecify = + context.it.skip = + function (title) { + return context.it(title); + }; }); }; diff --git a/node_modules/mocha/lib/interfaces/common.js b/node_modules/mocha/lib/interfaces/common.js index 20e83a1..ba8b5f8 100644 --- a/node_modules/mocha/lib/interfaces/common.js +++ b/node_modules/mocha/lib/interfaces/common.js @@ -19,7 +19,7 @@ var createForbiddenExclusivityError = errors.createForbiddenExclusivityError; * @param {Mocha} mocha * @return {Object} An object containing common functions. */ -module.exports = function(suites, context, mocha) { +module.exports = function (suites, context, mocha) { /** * Check if the suite should be tested. * @@ -56,7 +56,7 @@ module.exports = function(suites, context, mocha) { * @param {string} name * @param {Function} fn */ - before: function(name, fn) { + before: function (name, fn) { suites[0].beforeAll(name, fn); }, @@ -66,7 +66,7 @@ module.exports = function(suites, context, mocha) { * @param {string} name * @param {Function} fn */ - after: function(name, fn) { + after: function (name, fn) { suites[0].afterAll(name, fn); }, @@ -76,7 +76,7 @@ module.exports = function(suites, context, mocha) { * @param {string} name * @param {Function} fn */ - beforeEach: function(name, fn) { + beforeEach: function (name, fn) { suites[0].beforeEach(name, fn); }, @@ -86,7 +86,7 @@ module.exports = function(suites, context, mocha) { * @param {string} name * @param {Function} fn */ - afterEach: function(name, fn) { + afterEach: function (name, fn) { suites[0].afterEach(name, fn); }, @@ -172,7 +172,7 @@ module.exports = function(suites, context, mocha) { * @param {Function} test * @returns {*} */ - only: function(mocha, test) { + only: function (mocha, test) { if (mocha.options.forbidOnly) { throw createForbiddenExclusivityError(mocha); } @@ -185,7 +185,7 @@ module.exports = function(suites, context, mocha) { * * @param {string} title */ - skip: function(title) { + skip: function (title) { context.test(title); } } diff --git a/node_modules/mocha/lib/interfaces/exports.js b/node_modules/mocha/lib/interfaces/exports.js index 5b4c7bd..79b762b 100644 --- a/node_modules/mocha/lib/interfaces/exports.js +++ b/node_modules/mocha/lib/interfaces/exports.js @@ -19,7 +19,7 @@ var Test = require('../test'); * * @param {Suite} suite Root suite. */ -module.exports = function(suite) { +module.exports = function (suite) { var suites = [suite]; suite.on(Suite.constants.EVENT_FILE_REQUIRE, visit); diff --git a/node_modules/mocha/lib/interfaces/qunit.js b/node_modules/mocha/lib/interfaces/qunit.js index 97c3cc1..8f5434c 100644 --- a/node_modules/mocha/lib/interfaces/qunit.js +++ b/node_modules/mocha/lib/interfaces/qunit.js @@ -1,8 +1,8 @@ 'use strict'; var Test = require('../test'); -var EVENT_FILE_PRE_REQUIRE = require('../suite').constants - .EVENT_FILE_PRE_REQUIRE; +var EVENT_FILE_PRE_REQUIRE = + require('../suite').constants.EVENT_FILE_PRE_REQUIRE; /** * QUnit-style interface: @@ -32,7 +32,7 @@ var EVENT_FILE_PRE_REQUIRE = require('../suite').constants module.exports = function qUnitInterface(suite) { var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) { + suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) { var common = require('./common')(suites, context, mocha); context.before = common.before; @@ -44,13 +44,13 @@ module.exports = function qUnitInterface(suite) { * Describe a "suite" with the given `title`. */ - context.suite = function(title) { + context.suite = function (title) { if (suites.length > 1) { suites.shift(); } return common.suite.create({ - title: title, - file: file, + title, + file, fn: false }); }; @@ -59,13 +59,13 @@ module.exports = function qUnitInterface(suite) { * Exclusive Suite. */ - context.suite.only = function(title) { + context.suite.only = function (title) { if (suites.length > 1) { suites.shift(); } return common.suite.only({ - title: title, - file: file, + title, + file, fn: false }); }; @@ -76,7 +76,7 @@ module.exports = function qUnitInterface(suite) { * acting as a thunk. */ - context.test = function(title, fn) { + context.test = function (title, fn) { var test = new Test(title, fn); test.file = file; suites[0].addTest(test); @@ -87,7 +87,7 @@ module.exports = function qUnitInterface(suite) { * Exclusive test-case. */ - context.test.only = function(title, fn) { + context.test.only = function (title, fn) { return common.test.only(mocha, context.test(title, fn)); }; diff --git a/node_modules/mocha/lib/interfaces/tdd.js b/node_modules/mocha/lib/interfaces/tdd.js index baf4d9d..8b7b1d5 100644 --- a/node_modules/mocha/lib/interfaces/tdd.js +++ b/node_modules/mocha/lib/interfaces/tdd.js @@ -1,8 +1,8 @@ 'use strict'; var Test = require('../test'); -var EVENT_FILE_PRE_REQUIRE = require('../suite').constants - .EVENT_FILE_PRE_REQUIRE; +var EVENT_FILE_PRE_REQUIRE = + require('../suite').constants.EVENT_FILE_PRE_REQUIRE; /** * TDD-style interface: @@ -29,10 +29,10 @@ var EVENT_FILE_PRE_REQUIRE = require('../suite').constants * * @param {Suite} suite Root suite. */ -module.exports = function(suite) { +module.exports = function (suite) { var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) { + suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) { var common = require('./common')(suites, context, mocha); context.setup = common.beforeEach; @@ -45,33 +45,33 @@ module.exports = function(suite) { * Describe a "suite" with the given `title` and callback `fn` containing * nested suites and/or tests. */ - context.suite = function(title, fn) { + context.suite = function (title, fn) { return common.suite.create({ - title: title, - file: file, - fn: fn + title, + file, + fn }); }; /** * Pending suite. */ - context.suite.skip = function(title, fn) { + context.suite.skip = function (title, fn) { return common.suite.skip({ - title: title, - file: file, - fn: fn + title, + file, + fn }); }; /** * Exclusive test-case. */ - context.suite.only = function(title, fn) { + context.suite.only = function (title, fn) { return common.suite.only({ - title: title, - file: file, - fn: fn + title, + file, + fn }); }; @@ -79,7 +79,7 @@ module.exports = function(suite) { * Describe a specification or test-case with the given `title` and * callback `fn` acting as a thunk. */ - context.test = function(title, fn) { + context.test = function (title, fn) { var suite = suites[0]; if (suite.isPending()) { fn = null; @@ -94,7 +94,7 @@ module.exports = function(suite) { * Exclusive test-case. */ - context.test.only = function(title, fn) { + context.test.only = function (title, fn) { return common.test.only(mocha, context.test(title, fn)); }; diff --git a/node_modules/mocha/lib/mocha.js b/node_modules/mocha/lib/mocha.js index f1f2e25..f93865d 100644 --- a/node_modules/mocha/lib/mocha.js +++ b/node_modules/mocha/lib/mocha.js @@ -9,28 +9,20 @@ var escapeRe = require('escape-string-regexp'); var path = require('path'); var builtinReporters = require('./reporters'); -var growl = require('./nodejs/growl'); var utils = require('./utils'); var mocharc = require('./mocharc.json'); var Suite = require('./suite'); -var esmUtils = utils.supportsEsModules(true) - ? require('./esm-utils') - : undefined; +var esmUtils = require('./nodejs/esm-utils'); var createStatsCollector = require('./stats-collector'); const { - warn, createInvalidReporterError, createInvalidInterfaceError, createMochaInstanceAlreadyDisposedError, createMochaInstanceAlreadyRunningError, createUnsupportedError } = require('./errors'); -const { - EVENT_FILE_PRE_REQUIRE, - EVENT_FILE_POST_REQUIRE, - EVENT_FILE_REQUIRE -} = Suite.constants; -var sQuote = utils.sQuote; +const {EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE} = + Suite.constants; var debug = require('debug')('mocha:mocha'); exports = module.exports = Mocha; @@ -97,46 +89,46 @@ exports.Hook = require('./hook'); exports.Test = require('./test'); let currentContext; -exports.afterEach = function(...args) { +exports.afterEach = function (...args) { return (currentContext.afterEach || currentContext.teardown).apply( this, args ); }; -exports.after = function(...args) { +exports.after = function (...args) { return (currentContext.after || currentContext.suiteTeardown).apply( this, args ); }; -exports.beforeEach = function(...args) { +exports.beforeEach = function (...args) { return (currentContext.beforeEach || currentContext.setup).apply(this, args); }; -exports.before = function(...args) { +exports.before = function (...args) { return (currentContext.before || currentContext.suiteSetup).apply(this, args); }; -exports.describe = function(...args) { +exports.describe = function (...args) { return (currentContext.describe || currentContext.suite).apply(this, args); }; -exports.describe.only = function(...args) { +exports.describe.only = function (...args) { return (currentContext.describe || currentContext.suite).only.apply( this, args ); }; -exports.describe.skip = function(...args) { +exports.describe.skip = function (...args) { return (currentContext.describe || currentContext.suite).skip.apply( this, args ); }; -exports.it = function(...args) { +exports.it = function (...args) { return (currentContext.it || currentContext.test).apply(this, args); }; -exports.it.only = function(...args) { +exports.it.only = function (...args) { return (currentContext.it || currentContext.test).only.apply(this, args); }; -exports.it.skip = function(...args) { +exports.it.skip = function (...args) { return (currentContext.it || currentContext.test).skip.apply(this, args); }; exports.xdescribe = exports.describe.skip; @@ -147,7 +139,7 @@ exports.suiteTeardown = exports.after; exports.suite = exports.describe; exports.teardown = exports.afterEach; exports.test = exports.it; -exports.run = function(...args) { +exports.run = function (...args) { return currentContext.run.apply(this, args); }; @@ -164,13 +156,14 @@ exports.run = function(...args) { * @param {boolean} [options.color] - Color TTY output from reporter? * @param {boolean} [options.delay] - Delay root suite execution? * @param {boolean} [options.diff] - Show diff on failure? + * @param {boolean} [options.dryRun] - Report tests without running them? + * @param {boolean} [options.failZero] - Fail test run if zero tests? * @param {string} [options.fgrep] - Test filter given string. * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite? * @param {boolean} [options.forbidPending] - Pending tests fail the suite? * @param {boolean} [options.fullTrace] - Full stacktrace upon failure? * @param {string[]} [options.global] - Variables expected in global scope. * @param {RegExp|string} [options.grep] - Test filter given regular expression. - * @param {boolean} [options.growl] - Enable desktop notifications? * @param {boolean} [options.inlineDiffs] - Display inline diffs? * @param {boolean} [options.invert] - Invert test filter matches? * @param {boolean} [options.noHighlighting] - Disable syntax highlighting? @@ -200,7 +193,7 @@ function Mocha(options = {}) { .ui(options.ui) .reporter( options.reporter, - options.reporterOption || options.reporterOptions // reporterOptions was previously the only way to specify options to reporter + options.reporterOption || options.reporterOptions // for backwards compatibility ) .slow(options.slow) .global(options.global); @@ -222,13 +215,14 @@ function Mocha(options = {}) { 'color', 'delay', 'diff', + 'dryRun', + 'failZero', 'forbidOnly', 'forbidPending', 'fullTrace', - 'growl', 'inlineDiffs', 'invert' - ].forEach(function(opt) { + ].forEach(function (opt) { if (options[opt]) { this[opt](); } @@ -286,7 +280,7 @@ function Mocha(options = {}) { * @returns {Mocha} this * @chainable */ -Mocha.prototype.bail = function(bail) { +Mocha.prototype.bail = function (bail) { this.suite.bail(bail !== false); return this; }; @@ -304,7 +298,7 @@ Mocha.prototype.bail = function(bail) { * @returns {Mocha} this * @chainable */ -Mocha.prototype.addFile = function(file) { +Mocha.prototype.addFile = function (file) { this.files.push(file); return this; }; @@ -325,7 +319,7 @@ Mocha.prototype.addFile = function(file) { * // Use XUnit reporter and direct its output to file * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' }); */ -Mocha.prototype.reporter = function(reporterName, reporterOptions) { +Mocha.prototype.reporter = function (reporterName, reporterOptions) { if (typeof reporterName === 'function') { this._reporter = reporterName; } else { @@ -337,39 +331,26 @@ Mocha.prototype.reporter = function(reporterName, reporterOptions) { } // Try to load reporters from process.cwd() and node_modules if (!reporter) { + let foundReporter; try { - reporter = require(reporterName); + foundReporter = require.resolve(reporterName); + reporter = require(foundReporter); } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - // Try to load reporters from a path (absolute or relative) - try { - reporter = require(path.resolve(utils.cwd(), reporterName)); - } catch (_err) { - _err.code === 'MODULE_NOT_FOUND' - ? warn(sQuote(reporterName) + ' reporter not found') - : warn( - sQuote(reporterName) + - ' reporter blew up with error:\n' + - err.stack - ); - } - } else { - warn( - sQuote(reporterName) + ' reporter blew up with error:\n' + err.stack - ); + if (foundReporter) { + throw createInvalidReporterError(err.message, foundReporter); + } + // Try to load reporters from a cwd-relative path + try { + reporter = require(path.resolve(reporterName)); + } catch (e) { + throw createInvalidReporterError(e.message, reporterName); } } } - if (!reporter) { - throw createInvalidReporterError( - 'invalid reporter ' + sQuote(reporterName), - reporterName - ); - } this._reporter = reporter; } this.options.reporterOption = reporterOptions; - // alias option name is used in public reporters xunit/tap/progress + // alias option name is used in built-in reporters xunit/tap/progress this.options.reporterOptions = reporterOptions; return this; }; @@ -385,7 +366,7 @@ Mocha.prototype.reporter = function(reporterName, reporterOptions) { * @chainable * @throws {Error} if requested interface cannot be loaded */ -Mocha.prototype.ui = function(ui) { +Mocha.prototype.ui = function (ui) { var bindInterface; if (typeof ui === 'function') { bindInterface = ui; @@ -396,16 +377,13 @@ Mocha.prototype.ui = function(ui) { try { bindInterface = require(ui); } catch (err) { - throw createInvalidInterfaceError( - 'invalid interface ' + sQuote(ui), - ui - ); + throw createInvalidInterfaceError(`invalid interface '${ui}'`, ui); } } } bindInterface(this.suite); - this.suite.on(EVENT_FILE_PRE_REQUIRE, function(context) { + this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) { currentContext = context; }); @@ -427,10 +405,10 @@ Mocha.prototype.ui = function(ui) { * @see {@link Mocha#loadFilesAsync} * @param {Function} [fn] - Callback invoked upon completion. */ -Mocha.prototype.loadFiles = function(fn) { +Mocha.prototype.loadFiles = function (fn) { var self = this; var suite = this.suite; - this.files.forEach(function(file) { + this.files.forEach(function (file) { file = path.resolve(file); suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self); suite.emit(EVENT_FILE_REQUIRE, require(file), file, self); @@ -451,6 +429,8 @@ Mocha.prototype.loadFiles = function(fn) { * @see {@link Mocha#addFile} * @see {@link Mocha#run} * @see {@link Mocha#unloadFiles} + * @param {Object} [options] - Settings object. + * @param {Function} [options.esmDecorator] - Function invoked on esm module name right before importing it. By default will passthrough as is. * @returns {Promise} * @example * @@ -459,26 +439,21 @@ Mocha.prototype.loadFiles = function(fn) { * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0)) * .catch(() => process.exitCode = 1); */ -Mocha.prototype.loadFilesAsync = function() { +Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) { var self = this; var suite = this.suite; this.lazyLoadFiles(true); - if (!esmUtils) { - return new Promise(function(resolve) { - self.loadFiles(resolve); - }); - } - return esmUtils.loadFilesAsync( this.files, - function(file) { + function (file) { suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self); }, - function(file, resultModule) { + function (file, resultModule) { suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self); suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self); - } + }, + esmDecorator ); }; @@ -490,10 +465,10 @@ Mocha.prototype.loadFilesAsync = function() { * @see {@link Mocha#unloadFiles} * @param {string} file - Pathname of file to be unloaded. */ -Mocha.unloadFile = function(file) { +Mocha.unloadFile = function (file) { if (utils.isBrowser()) { throw createUnsupportedError( - 'unloadFile() is only suported in a Node.js environment' + 'unloadFile() is only supported in a Node.js environment' ); } return require('./nodejs/file-unloader').unloadFile(file); @@ -514,7 +489,7 @@ Mocha.unloadFile = function(file) { * @returns {Mocha} this * @chainable */ -Mocha.prototype.unloadFiles = function() { +Mocha.prototype.unloadFiles = function () { if (this._state === mochaStates.DISPOSED) { throw createMochaInstanceAlreadyDisposedError( 'Mocha instance is already disposed, it cannot be used again.', @@ -523,7 +498,7 @@ Mocha.prototype.unloadFiles = function() { ); } - this.files.forEach(function(file) { + this.files.forEach(function (file) { Mocha.unloadFile(file); }); this._state = mochaStates.INIT; @@ -543,7 +518,7 @@ Mocha.prototype.unloadFiles = function() { * // Select tests whose full title begins with `"foo"` followed by a period * mocha.fgrep('foo.'); */ -Mocha.prototype.fgrep = function(str) { +Mocha.prototype.fgrep = function (str) { if (!str) { return this; } @@ -584,10 +559,10 @@ Mocha.prototype.fgrep = function(str) { * // Given embedded test `it('only-this-test')`... * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this! */ -Mocha.prototype.grep = function(re) { +Mocha.prototype.grep = function (re) { if (utils.isString(re)) { // extract args if it's regex-like, i.e: [string, pattern, flag] - var arg = re.match(/^\/(.*)\/(g|i|)$|.*/); + var arg = re.match(/^\/(.*)\/([gimy]{0,4})$|.*/); this.options.grep = new RegExp(arg[1] || arg[0], arg[2]); } else { this.options.grep = re; @@ -607,7 +582,7 @@ Mocha.prototype.grep = function(re) { * // Select tests whose full title does *not* contain `"match"`, ignoring case * mocha.grep(/match/i).invert(); */ -Mocha.prototype.invert = function() { +Mocha.prototype.invert = function () { this.options.invert = true; return this; }; @@ -621,7 +596,7 @@ Mocha.prototype.invert = function() { * @return {Mocha} this * @chainable */ -Mocha.prototype.checkLeaks = function(checkLeaks) { +Mocha.prototype.checkLeaks = function (checkLeaks) { this.options.checkLeaks = checkLeaks !== false; return this; }; @@ -636,7 +611,7 @@ Mocha.prototype.checkLeaks = function(checkLeaks) { * @return {Mocha} this * @chainable */ -Mocha.prototype.cleanReferencesAfterRun = function(cleanReferencesAfterRun) { +Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) { this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false; return this; }; @@ -646,7 +621,7 @@ Mocha.prototype.cleanReferencesAfterRun = function(cleanReferencesAfterRun) { * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector. * @public */ -Mocha.prototype.dispose = function() { +Mocha.prototype.dispose = function () { if (this._state === mochaStates.RUNNING) { throw createMochaInstanceAlreadyRunningError( 'Cannot dispose while the mocha instance is still running tests.' @@ -667,54 +642,11 @@ Mocha.prototype.dispose = function() { * @return {Mocha} this * @chainable */ -Mocha.prototype.fullTrace = function(fullTrace) { +Mocha.prototype.fullTrace = function (fullTrace) { this.options.fullTrace = fullTrace !== false; return this; }; -/** - * Enables desktop notification support if prerequisite software installed. - * - * @public - * @see [CLI option](../#-growl-g) - * @return {Mocha} this - * @chainable - */ -Mocha.prototype.growl = function() { - this.options.growl = this.isGrowlCapable(); - if (!this.options.growl) { - var detail = utils.isBrowser() - ? 'notification support not available in this browser...' - : 'notification support prerequisites not installed...'; - console.error(detail + ' cannot enable!'); - } - return this; -}; - -/** - * @summary - * Determines if Growl support seems likely. - * - * @description - * Not available when run in browser. - * - * @private - * @see {@link Growl#isCapable} - * @see {@link Mocha#growl} - * @return {boolean} whether Growl support can be expected - */ -Mocha.prototype.isGrowlCapable = growl.isCapable; - -/** - * Implements desktop notifications using a pseudo-reporter. - * - * @private - * @see {@link Mocha#growl} - * @see {@link Growl#notify} - * @param {Runner} runner - Runner instance. - */ -Mocha.prototype._growl = growl.notify; - /** * Specifies whitelist of variable names to be expected in global scope. * @@ -729,16 +661,16 @@ Mocha.prototype._growl = growl.notify; * // Specify variables to be expected in global scope * mocha.global(['jQuery', 'MyLib']); */ -Mocha.prototype.global = function(global) { +Mocha.prototype.global = function (global) { this.options.global = (this.options.global || []) .concat(global) .filter(Boolean) - .filter(function(elt, idx, arr) { + .filter(function (elt, idx, arr) { return arr.indexOf(elt) === idx; }); return this; }; -// for backwards compability, 'globals' is an alias of 'global' +// for backwards compatibility, 'globals' is an alias of 'global' Mocha.prototype.globals = Mocha.prototype.global; /** @@ -750,7 +682,7 @@ Mocha.prototype.globals = Mocha.prototype.global; * @return {Mocha} this * @chainable */ -Mocha.prototype.color = function(color) { +Mocha.prototype.color = function (color) { this.options.color = color !== false; return this; }; @@ -765,7 +697,7 @@ Mocha.prototype.color = function(color) { * @return {Mocha} this * @chainable */ -Mocha.prototype.inlineDiffs = function(inlineDiffs) { +Mocha.prototype.inlineDiffs = function (inlineDiffs) { this.options.inlineDiffs = inlineDiffs !== false; return this; }; @@ -779,7 +711,7 @@ Mocha.prototype.inlineDiffs = function(inlineDiffs) { * @return {Mocha} this * @chainable */ -Mocha.prototype.diff = function(diff) { +Mocha.prototype.diff = function (diff) { this.options.diff = diff !== false; return this; }; @@ -807,7 +739,7 @@ Mocha.prototype.diff = function(diff) { * // Same as above but using string argument * mocha.timeout('1s'); */ -Mocha.prototype.timeout = function(msecs) { +Mocha.prototype.timeout = function (msecs) { this.suite.timeout(msecs); return this; }; @@ -826,7 +758,7 @@ Mocha.prototype.timeout = function(msecs) { * // Allow any failed test to retry one more time * mocha.retries(1); */ -Mocha.prototype.retries = function(retry) { +Mocha.prototype.retries = function (retry) { this.suite.retries(retry); return this; }; @@ -848,7 +780,7 @@ Mocha.prototype.retries = function(retry) { * // Same as above but using string argument * mocha.slow('0.5s'); */ -Mocha.prototype.slow = function(msecs) { +Mocha.prototype.slow = function (msecs) { this.suite.slow(msecs); return this; }; @@ -862,7 +794,7 @@ Mocha.prototype.slow = function(msecs) { * @return {Mocha} this * @chainable */ -Mocha.prototype.asyncOnly = function(asyncOnly) { +Mocha.prototype.asyncOnly = function (asyncOnly) { this.options.asyncOnly = asyncOnly !== false; return this; }; @@ -874,7 +806,7 @@ Mocha.prototype.asyncOnly = function(asyncOnly) { * @return {Mocha} this * @chainable */ -Mocha.prototype.noHighlighting = function() { +Mocha.prototype.noHighlighting = function () { this.options.noHighlighting = true; return this; }; @@ -888,7 +820,7 @@ Mocha.prototype.noHighlighting = function() { * @return {Mocha} this * @chainable */ -Mocha.prototype.allowUncaught = function(allowUncaught) { +Mocha.prototype.allowUncaught = function (allowUncaught) { this.options.allowUncaught = allowUncaught !== false; return this; }; @@ -910,6 +842,34 @@ Mocha.prototype.delay = function delay() { return this; }; +/** + * Enables or disables running tests in dry-run mode. + * + * @public + * @see [CLI option](../#-dry-run) + * @param {boolean} [dryRun=true] - Whether to activate dry-run mode. + * @return {Mocha} this + * @chainable + */ +Mocha.prototype.dryRun = function (dryRun) { + this.options.dryRun = dryRun !== false; + return this; +}; + +/** + * Fails test run if no tests encountered with exit-code 1. + * + * @public + * @see [CLI option](../#-fail-zero) + * @param {boolean} [failZero=true] - Whether to fail test run. + * @return {Mocha} this + * @chainable + */ +Mocha.prototype.failZero = function (failZero) { + this.options.failZero = failZero !== false; + return this; +}; + /** * Causes tests marked `only` to fail the suite. * @@ -919,7 +879,7 @@ Mocha.prototype.delay = function delay() { * @returns {Mocha} this * @chainable */ -Mocha.prototype.forbidOnly = function(forbidOnly) { +Mocha.prototype.forbidOnly = function (forbidOnly) { this.options.forbidOnly = forbidOnly !== false; return this; }; @@ -933,7 +893,7 @@ Mocha.prototype.forbidOnly = function(forbidOnly) { * @returns {Mocha} this * @chainable */ -Mocha.prototype.forbidPending = function(forbidPending) { +Mocha.prototype.forbidPending = function (forbidPending) { this.options.forbidPending = forbidPending !== false; return this; }; @@ -942,7 +902,7 @@ Mocha.prototype.forbidPending = function(forbidPending) { * Throws an error if mocha is in the wrong state to be able to transition to a "running" state. * @private */ -Mocha.prototype._guardRunningStateTransition = function() { +Mocha.prototype._guardRunningStateTransition = function () { if (this._state === mochaStates.RUNNING) { throw createMochaInstanceAlreadyRunningError( 'Mocha instance is currently running tests, cannot start a next test run until this one is done', @@ -1001,7 +961,7 @@ Object.defineProperty(Mocha.prototype, 'version', { * // exit with non-zero status if there were test failures * mocha.run(failures => process.exitCode = failures ? 1 : 0); */ -Mocha.prototype.run = function(fn) { +Mocha.prototype.run = function (fn) { this._guardRunningStateTransition(); this._state = mochaStates.RUNNING; if (this._previousRunner) { @@ -1015,8 +975,10 @@ Mocha.prototype.run = function(fn) { var options = this.options; options.files = this.files; const runner = new this._runnerClass(suite, { + cleanReferencesAfterRun: this._cleanReferencesAfterRun, delay: options.delay, - cleanReferencesAfterRun: this._cleanReferencesAfterRun + dryRun: options.dryRun, + failZero: options.failZero }); createStatsCollector(runner); var reporter = new this._reporter(runner, options); @@ -1032,9 +994,6 @@ Mocha.prototype.run = function(fn) { if (options.global) { runner.globals(options.global); } - if (options.growl) { - this._growl(runner); - } if (options.color !== undefined) { exports.reporters.Base.useColors = options.color; } @@ -1302,9 +1261,10 @@ Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() { * @public * @returns {boolean} */ -Mocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures() { - return Boolean(this.options.globalTeardown.length); -}; +Mocha.prototype.hasGlobalTeardownFixtures = + function hasGlobalTeardownFixtures() { + return Boolean(this.options.globalTeardown.length); + }; /** * An alternative way to define root hooks that works with parallel runs. diff --git a/node_modules/mocha/lib/nodejs/buffered-worker-pool.js b/node_modules/mocha/lib/nodejs/buffered-worker-pool.js index 9b0d451..fe4abf9 100644 --- a/node_modules/mocha/lib/nodejs/buffered-worker-pool.js +++ b/node_modules/mocha/lib/nodejs/buffered-worker-pool.js @@ -75,7 +75,23 @@ class BufferedWorkerPool { process.execArgv.join(' ') ); - this.options = {...WORKER_POOL_DEFAULT_OPTS, opts, maxWorkers}; + let counter = 0; + const onCreateWorker = ({forkOpts}) => { + return { + forkOpts: { + ...forkOpts, + // adds an incremental id to all workers, which can be useful to allocate resources for each process + env: {...process.env, MOCHA_WORKER_ID: counter++} + } + }; + }; + + this.options = { + ...WORKER_POOL_DEFAULT_OPTS, + ...opts, + maxWorkers, + onCreateWorker + }; this._pool = workerpool.pool(WORKER_PATH, this.options); } diff --git a/node_modules/mocha/lib/nodejs/esm-utils.js b/node_modules/mocha/lib/nodejs/esm-utils.js new file mode 100644 index 0000000..5318099 --- /dev/null +++ b/node_modules/mocha/lib/nodejs/esm-utils.js @@ -0,0 +1,106 @@ +const path = require('path'); +const url = require('url'); + +const forward = x => x; + +const formattedImport = async (file, esmDecorator = forward) => { + if (path.isAbsolute(file)) { + try { + return await exports.doImport(esmDecorator(url.pathToFileURL(file))); + } catch (err) { + // This is a hack created because ESM in Node.js (at least in Node v15.5.1) does not emit + // the location of the syntax error in the error thrown. + // This is problematic because the user can't see what file has the problem, + // so we add the file location to the error. + // TODO: remove once Node.js fixes the problem. + if ( + err instanceof SyntaxError && + err.message && + err.stack && + !err.stack.includes(file) + ) { + const newErrorWithFilename = new SyntaxError(err.message); + newErrorWithFilename.stack = err.stack.replace( + /^SyntaxError/, + `SyntaxError[ @${file} ]` + ); + throw newErrorWithFilename; + } + throw err; + } + } + return exports.doImport(esmDecorator(file)); +}; + +exports.doImport = async file => import(file); + +exports.requireOrImport = async (file, esmDecorator) => { + if (path.extname(file) === '.mjs') { + return formattedImport(file, esmDecorator); + } + try { + return dealWithExports(await formattedImport(file, esmDecorator)); + } catch (err) { + if ( + err.code === 'ERR_MODULE_NOT_FOUND' || + err.code === 'ERR_UNKNOWN_FILE_EXTENSION' || + err.code === 'ERR_UNSUPPORTED_DIR_IMPORT' + ) { + try { + // Importing a file usually works, but the resolution of `import` is the ESM + // resolution algorithm, and not the CJS resolution algorithm. We may have + // failed because we tried the ESM resolution, so we try to `require` it. + return require(file); + } catch (requireErr) { + if ( + requireErr.code === 'ERR_REQUIRE_ESM' || + (requireErr instanceof SyntaxError && + requireErr + .toString() + .includes('Cannot use import statement outside a module')) + ) { + // ERR_REQUIRE_ESM happens when the test file is a JS file, but via type:module is actually ESM, + // AND has an import to a file that doesn't exist. + // This throws an `ERR_MODULE_NOT_FOUND` error above, + // and when we try to `require` it here, it throws an `ERR_REQUIRE_ESM`. + // What we want to do is throw the original error (the `ERR_MODULE_NOT_FOUND`), + // and not the `ERR_REQUIRE_ESM` error, which is a red herring. + // + // SyntaxError happens when in an edge case: when we're using an ESM loader that loads + // a `test.ts` file (i.e. unrecognized extension), and that file includes an unknown + // import (which throws an ERR_MODULE_NOT_FOUND). `require`-ing it will throw the + // syntax error, because we cannot require a file that has `import`-s. + throw err; + } else { + throw requireErr; + } + } + } else { + throw err; + } + } +}; + +function dealWithExports(module) { + if (module.default) { + return module.default; + } else { + return {...module, default: undefined}; + } +} + +exports.loadFilesAsync = async ( + files, + preLoadFunc, + postLoadFunc, + esmDecorator +) => { + for (const file of files) { + preLoadFunc(file); + const result = await exports.requireOrImport( + path.resolve(file), + esmDecorator + ); + postLoadFunc(file, result); + } +}; diff --git a/node_modules/mocha/lib/nodejs/growl.js b/node_modules/mocha/lib/nodejs/growl.js deleted file mode 100644 index 6664d67..0000000 --- a/node_modules/mocha/lib/nodejs/growl.js +++ /dev/null @@ -1,137 +0,0 @@ -'use strict'; - -/** - * Desktop Notifications module. - * @module Growl - */ - -const os = require('os'); -const path = require('path'); -const {sync: which} = require('which'); -const {EVENT_RUN_END} = require('../runner').constants; -const {isBrowser} = require('../utils'); - -/** - * @summary - * Checks if Growl notification support seems likely. - * - * @description - * Glosses over the distinction between an unsupported platform - * and one that lacks prerequisite software installations. - * - * @public - * @see {@link https://github.com/tj/node-growl/blob/master/README.md|Prerequisite Installs} - * @see {@link Mocha#growl} - * @see {@link Mocha#isGrowlCapable} - * @return {boolean} whether Growl notification support can be expected - */ -exports.isCapable = () => { - if (!isBrowser()) { - return getSupportBinaries().reduce( - (acc, binary) => acc || Boolean(which(binary, {nothrow: true})), - false - ); - } - return false; -}; - -/** - * Implements desktop notifications as a pseudo-reporter. - * - * @public - * @see {@link Mocha#_growl} - * @param {Runner} runner - Runner instance. - */ -exports.notify = runner => { - runner.once(EVENT_RUN_END, () => { - display(runner); - }); -}; - -/** - * Displays the notification. - * - * @private - * @param {Runner} runner - Runner instance. - */ -const display = runner => { - const growl = require('growl'); - const stats = runner.stats; - const symbol = { - cross: '\u274C', - tick: '\u2705' - }; - let _message; - let message; - let title; - - if (stats.failures) { - _message = `${stats.failures} of ${stats.tests} tests failed`; - message = `${symbol.cross} ${_message}`; - title = 'Failed'; - } else { - _message = `${stats.passes} tests passed in ${stats.duration}ms`; - message = `${symbol.tick} ${_message}`; - title = 'Passed'; - } - - // Send notification - const options = { - image: logo(), - name: 'mocha', - title - }; - growl(message, options, onCompletion); -}; - -/** - * @summary - * Callback for result of attempted Growl notification. - * - * @description - * Despite its appearance, this is not an Error-first - * callback -- all parameters are populated regardless of success. - * - * @private - * @callback Growl~growlCB - * @param {*} err - Error object, or null if successful. - */ -function onCompletion(err) { - if (err) { - // As notifications are tangential to our purpose, just log the error. - const message = - err.code === 'ENOENT' ? 'prerequisite software not found' : err.message; - console.error('notification error:', message); - } -} - -/** - * Returns Mocha logo image path. - * - * @private - * @return {string} Pathname of Mocha logo - */ -const logo = () => { - return path.join(__dirname, '..', 'assets', 'mocha-logo-96.png'); -}; - -/** - * @summary - * Gets platform-specific Growl support binaries. - * - * @description - * Somewhat brittle dependency on `growl` package implementation, but it - * rarely changes. - * - * @private - * @see {@link https://github.com/tj/node-growl/blob/master/lib/growl.js#L28-L126|setupCmd} - * @return {string[]} names of Growl support binaries - */ -const getSupportBinaries = () => { - const binaries = { - Darwin: ['terminal-notifier', 'growlnotify'], - Linux: ['notify-send', 'growl'], - Windows_NT: ['growlnotify.exe'] - }; - return binaries[os.type()] || []; -}; diff --git a/node_modules/mocha/lib/nodejs/parallel-buffered-runner.js b/node_modules/mocha/lib/nodejs/parallel-buffered-runner.js index 76a9bee..6052efc 100644 --- a/node_modules/mocha/lib/nodejs/parallel-buffered-runner.js +++ b/node_modules/mocha/lib/nodejs/parallel-buffered-runner.js @@ -6,7 +6,6 @@ 'use strict'; -const allSettled = require('@ungap/promise-all-settled').bind(Promise); const Runner = require('../runner'); const {EVENT_RUN_BEGIN, EVENT_RUN_END} = Runner.constants; const debug = require('debug')('mocha:parallel:parallel-buffered-runner'); @@ -271,8 +270,9 @@ class ParallelBufferedRunner extends Runner { * * @param {Function} callback - Called with an exit code corresponding to * number of test failures. - * @param {{files: string[], options: Options}} opts - Files to run and - * command-line options, respectively. + * @param {Object} [opts] - options + * @param {string[]} opts.files - Files to run + * @param {Options} opts.options - command-line options */ run(callback, {files, options = {}} = {}) { /** @@ -321,7 +321,7 @@ class ParallelBufferedRunner extends Runner { delete options[opt]; }); - const results = await allSettled( + const results = await Promise.allSettled( files.map(this._createFileRunner(pool, options)) ); diff --git a/node_modules/mocha/lib/reporters/base.js b/node_modules/mocha/lib/reporters/base.js index 1f97e31..e0ca5f4 100644 --- a/node_modules/mocha/lib/reporters/base.js +++ b/node_modules/mocha/lib/reporters/base.js @@ -10,6 +10,7 @@ var diff = require('diff'); var milliseconds = require('ms'); var utils = require('../utils'); var supportsColor = require('supports-color'); +var symbols = require('log-symbols'); var constants = require('../runner').constants; var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; @@ -55,6 +56,11 @@ exports.useColors = exports.inlineDiffs = false; +/** + * Truncate diffs longer than this value to avoid slow performance + */ +exports.maxDiffSize = 8192; + /** * Default color map. */ @@ -88,20 +94,13 @@ exports.colors = { */ exports.symbols = { - ok: '✓', - err: '✖', - dot: '․', + ok: symbols.success, + err: symbols.error, + dot: '.', comma: ',', bang: '!' }; -// With node.js on Windows: use symbols available in terminal default fonts -if (process.platform === 'win32') { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - /** * Color `str` with the given `type`, * allowing colors to be disabled, @@ -113,7 +112,7 @@ if (process.platform === 'win32') { * @param {string} str * @return {string} */ -var color = (exports.color = function(type, str) { +var color = (exports.color = function (type, str) { if (!exports.useColors) { return String(str); } @@ -141,23 +140,23 @@ if (isatty) { */ exports.cursor = { - hide: function() { + hide: function () { isatty && process.stdout.write('\u001b[?25l'); }, - show: function() { + show: function () { isatty && process.stdout.write('\u001b[?25h'); }, - deleteLine: function() { + deleteLine: function () { isatty && process.stdout.write('\u001b[2K'); }, - beginningOfLine: function() { + beginningOfLine: function () { isatty && process.stdout.write('\u001b[0G'); }, - CR: function() { + CR: function () { if (isatty) { exports.cursor.deleteLine(); exports.cursor.beginningOfLine(); @@ -167,7 +166,7 @@ exports.cursor = { } }; -var showDiff = (exports.showDiff = function(err) { +var showDiff = (exports.showDiff = function (err) { return ( err && err.showDiff !== false && @@ -194,11 +193,23 @@ function stringifyDiffObjs(err) { * @param {string} expected * @return {string} Diff */ -var generateDiff = (exports.generateDiff = function(actual, expected) { + +var generateDiff = (exports.generateDiff = function (actual, expected) { try { - return exports.inlineDiffs + var maxLen = exports.maxDiffSize; + var skipped = 0; + if (maxLen > 0) { + skipped = Math.max(actual.length - maxLen, expected.length - maxLen); + actual = actual.slice(0, maxLen); + expected = expected.slice(0, maxLen); + } + let result = exports.inlineDiffs ? inlineDiff(actual, expected) : unifiedDiff(actual, expected); + if (skipped > 0) { + result = `${result}\n [mocha] output truncated to ${maxLen} characters, see "maxDiffSize" reporter-option\n`; + } + return result; } catch (err) { var msg = '\n ' + @@ -210,6 +221,56 @@ var generateDiff = (exports.generateDiff = function(actual, expected) { } }); +/** + * Traverses err.cause and returns all stack traces + * + * @private + * @param {Error} err + * @param {Set} [seen] + * @return {FullErrorStack} + */ +var getFullErrorStack = function (err, seen) { + if (seen && seen.has(err)) { + return { message: '', msg: '', stack: '' }; + } + + var message; + + if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else { + message = ''; + } + + var msg; + var stack = err.stack || message; + var index = message ? stack.indexOf(message) : -1; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + + if (err.cause) { + seen = seen || new Set(); + seen.add(err); + const causeStack = getFullErrorStack(err.cause, seen) + stack += '\n Caused by: ' + causeStack.msg + (causeStack.stack ? '\n' + causeStack.stack : ''); + } + } + + return { + message, + msg, + stack + }; +}; + /** * Outputs the given `failures` as a list. * @@ -219,10 +280,10 @@ var generateDiff = (exports.generateDiff = function(actual, expected) { * @param {Object[]} failures - Each is Test instance with corresponding * Error property */ -exports.list = function(failures) { +exports.list = function (failures) { var multipleErr, multipleTest; Base.consoleLog(); - failures.forEach(function(test, i) { + failures.forEach(function (test, i) { // format var fmt = color('error title', ' %s) %s:\n') + @@ -230,7 +291,6 @@ exports.list = function(failures) { color('error stack', '\n%s\n'); // msg - var msg; var err; if (test.err && test.err.multiple) { if (multipleTest !== test) { @@ -241,25 +301,8 @@ exports.list = function(failures) { } else { err = test.err; } - var message; - if (err.message && typeof err.message.toString === 'function') { - message = err.message + ''; - } else if (typeof err.inspect === 'function') { - message = err.inspect() + ''; - } else { - message = ''; - } - var stack = err.stack || message; - var index = message ? stack.indexOf(message) : -1; - if (index === -1) { - msg = message; - } else { - index += message.length; - msg = stack.slice(0, index); - // remove msg from stack - stack = stack.slice(index + 1); - } + var { message, msg, stack } = getFullErrorStack(err); // uncaught if (err.uncaught) { @@ -281,7 +324,7 @@ exports.list = function(failures) { // indented test title var testTitle = ''; - test.titlePath().forEach(function(str, index) { + test.titlePath().forEach(function (str, index) { if (index !== 0) { testTitle += '\n '; } @@ -317,7 +360,13 @@ function Base(runner, options) { this.runner = runner; this.stats = runner.stats; // assigned so Reporters keep a closer reference - runner.on(EVENT_TEST_PASS, function(test) { + var maxDiffSizeOpt = + this.options.reporterOption && this.options.reporterOption.maxDiffSize; + if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) { + exports.maxDiffSize = Number(maxDiffSizeOpt); + } + + runner.on(EVENT_TEST_PASS, function (test) { if (test.duration > test.slow()) { test.speed = 'slow'; } else if (test.duration > test.slow() / 2) { @@ -327,7 +376,7 @@ function Base(runner, options) { } }); - runner.on(EVENT_TEST_FAIL, function(test, err) { + runner.on(EVENT_TEST_FAIL, function (test, err) { if (showDiff(err)) { stringifyDiffObjs(err); } @@ -347,7 +396,7 @@ function Base(runner, options) { * @public * @memberof Mocha.reporters */ -Base.prototype.epilogue = function() { +Base.prototype.epilogue = function () { var stats = this.stats; var fmt; @@ -410,7 +459,7 @@ function inlineDiff(actual, expected) { if (lines.length > 4) { var width = String(lines.length).length; msg = lines - .map(function(str, i) { + .map(function (str, i) { return pad(++i, width) + ' |' + ' ' + str; }) .join('\n'); @@ -467,10 +516,7 @@ function unifiedDiff(actual, expected) { ' ' + colorLines('diff removed', '- actual') + '\n\n' + - lines - .map(cleanUp) - .filter(notBlank) - .join('\n') + lines.map(cleanUp).filter(notBlank).join('\n') ); } @@ -485,7 +531,7 @@ function unifiedDiff(actual, expected) { function errorDiff(actual, expected) { return diff .diffWordsWithSpace(actual, expected) - .map(function(str) { + .map(function (str) { if (str.added) { return colorLines('diff added inline', str.value); } @@ -508,7 +554,7 @@ function errorDiff(actual, expected) { function colorLines(name, str) { return str .split('\n') - .map(function(str) { + .map(function (str) { return color(name, str); }) .join('\n'); @@ -534,3 +580,12 @@ function sameType(a, b) { Base.consoleLog = consoleLog; Base.abstract = true; + +/** + * An object with all stack traces recursively mounted from each err.cause + * @memberof module:lib/reporters/base + * @typedef {Object} FullErrorStack + * @property {string} message + * @property {string} msg + * @property {string} stack + */ diff --git a/node_modules/mocha/lib/reporters/doc.js b/node_modules/mocha/lib/reporters/doc.js index fd6b469..b2c3e48 100644 --- a/node_modules/mocha/lib/reporters/doc.js +++ b/node_modules/mocha/lib/reporters/doc.js @@ -39,7 +39,7 @@ function Doc(runner, options) { return Array(indents).join(' '); } - runner.on(EVENT_SUITE_BEGIN, function(suite) { + runner.on(EVENT_SUITE_BEGIN, function (suite) { if (suite.root) { return; } @@ -50,7 +50,7 @@ function Doc(runner, options) { Base.consoleLog('%s
', indent()); }); - runner.on(EVENT_SUITE_END, function(suite) { + runner.on(EVENT_SUITE_END, function (suite) { if (suite.root) { return; } @@ -60,14 +60,14 @@ function Doc(runner, options) { --indents; }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { Base.consoleLog('%s
%s
', indent(), utils.escape(test.title)); Base.consoleLog('%s
%s
', indent(), utils.escape(test.file)); var code = utils.escape(utils.clean(test.body)); Base.consoleLog('%s
%s
', indent(), code); }); - runner.on(EVENT_TEST_FAIL, function(test, err) { + runner.on(EVENT_TEST_FAIL, function (test, err) { Base.consoleLog( '%s
%s
', indent(), diff --git a/node_modules/mocha/lib/reporters/dot.js b/node_modules/mocha/lib/reporters/dot.js index 3913f0c..c67ac8f 100644 --- a/node_modules/mocha/lib/reporters/dot.js +++ b/node_modules/mocha/lib/reporters/dot.js @@ -38,18 +38,18 @@ function Dot(runner, options) { var width = (Base.window.width * 0.75) | 0; var n = -1; - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { process.stdout.write('\n'); }); - runner.on(EVENT_TEST_PENDING, function() { + runner.on(EVENT_TEST_PENDING, function () { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('pending', Base.symbols.comma)); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { if (++n % width === 0) { process.stdout.write('\n '); } @@ -60,14 +60,14 @@ function Dot(runner, options) { } }); - runner.on(EVENT_TEST_FAIL, function() { + runner.on(EVENT_TEST_FAIL, function () { if (++n % width === 0) { process.stdout.write('\n '); } process.stdout.write(Base.color('fail', Base.symbols.bang)); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { process.stdout.write('\n'); self.epilogue(); }); diff --git a/node_modules/mocha/lib/reporters/html.js b/node_modules/mocha/lib/reporters/html.js index 70e8698..034fb07 100644 --- a/node_modules/mocha/lib/reporters/html.js +++ b/node_modules/mocha/lib/reporters/html.js @@ -91,7 +91,7 @@ function HTML(runner, options) { } // pass toggle - on(passesLink, 'click', function(evt) { + on(passesLink, 'click', function (evt) { evt.preventDefault(); unhide(); var name = /pass/.test(report.className) ? '' : ' pass'; @@ -102,7 +102,7 @@ function HTML(runner, options) { }); // failure toggle - on(failuresLink, 'click', function(evt) { + on(failuresLink, 'click', function (evt) { evt.preventDefault(); unhide(); var name = /fail/.test(report.className) ? '' : ' fail'; @@ -119,7 +119,7 @@ function HTML(runner, options) { progress.size(40); } - runner.on(EVENT_SUITE_BEGIN, function(suite) { + runner.on(EVENT_SUITE_BEGIN, function (suite) { if (suite.root) { return; } @@ -138,7 +138,7 @@ function HTML(runner, options) { el.appendChild(stack[0]); }); - runner.on(EVENT_SUITE_END, function(suite) { + runner.on(EVENT_SUITE_END, function (suite) { if (suite.root) { updateStats(); return; @@ -146,7 +146,7 @@ function HTML(runner, options) { stack.shift(); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { var url = self.testURL(test); var markup = '
  • %e%ems ' + @@ -159,7 +159,7 @@ function HTML(runner, options) { updateStats(); }); - runner.on(EVENT_TEST_FAIL, function(test) { + runner.on(EVENT_TEST_FAIL, function (test) { var el = fragment( '
  • %e ' + playIcon + @@ -181,7 +181,7 @@ function HTML(runner, options) { if (indexOfMessage === -1) { stackString = test.err.stack; } else { - stackString = test.err.stack.substr( + stackString = test.err.stack.slice( test.err.message.length + indexOfMessage ); } @@ -215,7 +215,7 @@ function HTML(runner, options) { updateStats(); }); - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { var el = fragment( '
  • %e

  • ', test.title @@ -273,7 +273,7 @@ function makeUrl(s) { * * @param {Object} [suite] */ -HTML.prototype.suiteURL = function(suite) { +HTML.prototype.suiteURL = function (suite) { return makeUrl(suite.fullTitle()); }; @@ -282,7 +282,7 @@ HTML.prototype.suiteURL = function(suite) { * * @param {Object} [test] */ -HTML.prototype.testURL = function(test) { +HTML.prototype.testURL = function (test) { return makeUrl(test.fullTitle()); }; @@ -292,10 +292,10 @@ HTML.prototype.testURL = function(test) { * @param {HTMLLIElement} el * @param {string} contents */ -HTML.prototype.addCodeToggle = function(el, contents) { +HTML.prototype.addCodeToggle = function (el, contents) { var h2 = el.getElementsByTagName('h2')[0]; - on(h2, 'click', function() { + on(h2, 'click', function () { pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; }); @@ -323,7 +323,7 @@ function fragment(html) { var div = document.createElement('div'); var i = 1; - div.innerHTML = html.replace(/%([se])/g, function(_, type) { + div.innerHTML = html.replace(/%([se])/g, function (_, type) { switch (type) { case 's': return String(args[i++]); diff --git a/node_modules/mocha/lib/reporters/json-stream.js b/node_modules/mocha/lib/reporters/json-stream.js index 87cf607..5926587 100644 --- a/node_modules/mocha/lib/reporters/json-stream.js +++ b/node_modules/mocha/lib/reporters/json-stream.js @@ -35,22 +35,22 @@ function JSONStream(runner, options) { var self = this; var total = runner.total; - runner.once(EVENT_RUN_BEGIN, function() { - writeEvent(['start', {total: total}]); + runner.once(EVENT_RUN_BEGIN, function () { + writeEvent(['start', {total}]); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { writeEvent(['pass', clean(test)]); }); - runner.on(EVENT_TEST_FAIL, function(test, err) { + runner.on(EVENT_TEST_FAIL, function (test, err) { test = clean(test); test.err = err.message; test.stack = err.stack || null; writeEvent(['fail', test]); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { writeEvent(['end', self.stats]); }); } diff --git a/node_modules/mocha/lib/reporters/json.js b/node_modules/mocha/lib/reporters/json.js index a314cd3..6194d87 100644 --- a/node_modules/mocha/lib/reporters/json.js +++ b/node_modules/mocha/lib/reporters/json.js @@ -7,12 +7,16 @@ */ var Base = require('./base'); +var fs = require('fs'); +var path = require('path'); +const createUnsupportedError = require('../errors').createUnsupportedError; +const utils = require('../utils'); var constants = require('../runner').constants; var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; +var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; var EVENT_TEST_END = constants.EVENT_TEST_END; var EVENT_RUN_END = constants.EVENT_RUN_END; -var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; /** * Expose `JSON`. @@ -30,7 +34,7 @@ exports = module.exports = JSONReporter; * @param {Runner} runner - Instance triggers reporter actions. * @param {Object} [options] - runner options */ -function JSONReporter(runner, options) { +function JSONReporter(runner, options = {}) { Base.call(this, runner, options); var self = this; @@ -38,24 +42,32 @@ function JSONReporter(runner, options) { var pending = []; var failures = []; var passes = []; + var output; - runner.on(EVENT_TEST_END, function(test) { + if (options.reporterOption && options.reporterOption.output) { + if (utils.isBrowser()) { + throw createUnsupportedError('file output not supported in browser'); + } + output = options.reporterOption.output; + } + + runner.on(EVENT_TEST_END, function (test) { tests.push(test); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { passes.push(test); }); - runner.on(EVENT_TEST_FAIL, function(test) { + runner.on(EVENT_TEST_FAIL, function (test) { failures.push(test); }); - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { pending.push(test); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { var obj = { stats: self.stats, tests: tests.map(clean), @@ -66,7 +78,20 @@ function JSONReporter(runner, options) { runner.testResults = obj; - process.stdout.write(JSON.stringify(obj, null, 2)); + var json = JSON.stringify(obj, null, 2); + if (output) { + try { + fs.mkdirSync(path.dirname(output), {recursive: true}); + fs.writeFileSync(output, json); + } catch (err) { + console.error( + `${Base.symbols.err} [mocha] writing output to "${output}" failed: ${err.message}\n` + ); + process.stdout.write(json); + } + } else { + process.stdout.write(json); + } }); } @@ -105,7 +130,7 @@ function clean(test) { function cleanCycles(obj) { var cache = []; return JSON.parse( - JSON.stringify(obj, function(key, value) { + JSON.stringify(obj, function (key, value) { if (typeof value === 'object' && value !== null) { if (cache.indexOf(value) !== -1) { // Instead of going in a circle, we'll print [object Object] @@ -128,7 +153,7 @@ function cleanCycles(obj) { */ function errorJSON(err) { var res = {}; - Object.getOwnPropertyNames(err).forEach(function(key) { + Object.getOwnPropertyNames(err).forEach(function (key) { res[key] = err[key]; }, err); return res; diff --git a/node_modules/mocha/lib/reporters/landing.js b/node_modules/mocha/lib/reporters/landing.js index 03c9acb..4188c7c 100644 --- a/node_modules/mocha/lib/reporters/landing.js +++ b/node_modules/mocha/lib/reporters/landing.js @@ -68,12 +68,12 @@ function Landing(runner, options) { return ' ' + color('runway', buf); } - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { stream.write('\n\n\n '); cursor.hide(); }); - runner.on(EVENT_TEST_END, function(test) { + runner.on(EVENT_TEST_END, function (test) { // check if the plane crashed var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed; // show the crash @@ -93,16 +93,16 @@ function Landing(runner, options) { stream.write('\u001b[0m'); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { cursor.show(); process.stdout.write('\n'); self.epilogue(); }); // if cursor is hidden when we ctrl-C, then it will remain hidden unless... - process.once('SIGINT', function() { + process.once('SIGINT', function () { cursor.show(); - process.nextTick(function() { + process.nextTick(function () { process.kill(process.pid, 'SIGINT'); }); }); diff --git a/node_modules/mocha/lib/reporters/list.js b/node_modules/mocha/lib/reporters/list.js index c7ff8c4..aebdd65 100644 --- a/node_modules/mocha/lib/reporters/list.js +++ b/node_modules/mocha/lib/reporters/list.js @@ -40,20 +40,20 @@ function List(runner, options) { var self = this; var n = 0; - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { Base.consoleLog(); }); - runner.on(EVENT_TEST_BEGIN, function(test) { + runner.on(EVENT_TEST_BEGIN, function (test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { var fmt = color('checkmark', ' -') + color('pending', ' %s'); Base.consoleLog(fmt, test.fullTitle()); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { var fmt = color('checkmark', ' ' + Base.symbols.ok) + color('pass', ' %s: ') + @@ -62,7 +62,7 @@ function List(runner, options) { Base.consoleLog(fmt, test.fullTitle(), test.duration); }); - runner.on(EVENT_TEST_FAIL, function(test) { + runner.on(EVENT_TEST_FAIL, function (test) { cursor.CR(); Base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); diff --git a/node_modules/mocha/lib/reporters/markdown.js b/node_modules/mocha/lib/reporters/markdown.js index 460e248..d5adfae 100644 --- a/node_modules/mocha/lib/reporters/markdown.js +++ b/node_modules/mocha/lib/reporters/markdown.js @@ -50,8 +50,8 @@ function Markdown(runner, options) { var ret = obj; var key = SUITE_PREFIX + suite.title; - obj = obj[key] = obj[key] || {suite: suite}; - suite.suites.forEach(function(suite) { + obj = obj[key] = obj[key] || {suite}; + suite.suites.forEach(function (suite) { mapTOC(suite, obj); }); @@ -83,18 +83,18 @@ function Markdown(runner, options) { generateTOC(runner.suite); - runner.on(EVENT_SUITE_BEGIN, function(suite) { + runner.on(EVENT_SUITE_BEGIN, function (suite) { ++level; var slug = utils.slug(suite.fullTitle()); buf += '
    ' + '\n'; buf += title(suite.title) + '\n'; }); - runner.on(EVENT_SUITE_END, function() { + runner.on(EVENT_SUITE_END, function () { --level; }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; @@ -102,7 +102,7 @@ function Markdown(runner, options) { buf += '```\n\n'; }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); diff --git a/node_modules/mocha/lib/reporters/min.js b/node_modules/mocha/lib/reporters/min.js index 019ffe5..4de98e6 100644 --- a/node_modules/mocha/lib/reporters/min.js +++ b/node_modules/mocha/lib/reporters/min.js @@ -34,7 +34,7 @@ exports = module.exports = Min; function Min(runner, options) { Base.call(this, runner, options); - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { // clear screen process.stdout.write('\u001b[2J'); // set cursor position diff --git a/node_modules/mocha/lib/reporters/nyan.js b/node_modules/mocha/lib/reporters/nyan.js index 4eda971..96de365 100644 --- a/node_modules/mocha/lib/reporters/nyan.js +++ b/node_modules/mocha/lib/reporters/nyan.js @@ -46,27 +46,27 @@ function NyanCat(runner, options) { this.trajectories = [[], [], [], []]; this.trajectoryWidthMax = width - nyanCatWidth; - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { Base.cursor.hide(); self.draw(); }); - runner.on(EVENT_TEST_PENDING, function() { + runner.on(EVENT_TEST_PENDING, function () { self.draw(); }); - runner.on(EVENT_TEST_PASS, function() { + runner.on(EVENT_TEST_PASS, function () { self.draw(); }); - runner.on(EVENT_TEST_FAIL, function() { + runner.on(EVENT_TEST_FAIL, function () { self.draw(); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { Base.cursor.show(); for (var i = 0; i < self.numberOfLines; i++) { - write('\n'); + process.stdout.write('\n'); } self.epilogue(); }); @@ -83,7 +83,7 @@ inherits(NyanCat, Base); * @private */ -NyanCat.prototype.draw = function() { +NyanCat.prototype.draw = function () { this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); @@ -98,19 +98,19 @@ NyanCat.prototype.draw = function() { * @private */ -NyanCat.prototype.drawScoreboard = function() { +NyanCat.prototype.drawScoreboard = function () { var stats = this.stats; function draw(type, n) { - write(' '); - write(Base.color(type, n)); - write('\n'); + process.stdout.write(' '); + process.stdout.write(Base.color(type, n)); + process.stdout.write('\n'); } draw('green', stats.passes); draw('fail', stats.failures); draw('pending', stats.pending); - write('\n'); + process.stdout.write('\n'); this.cursorUp(this.numberOfLines); }; @@ -121,7 +121,7 @@ NyanCat.prototype.drawScoreboard = function() { * @private */ -NyanCat.prototype.appendRainbow = function() { +NyanCat.prototype.appendRainbow = function () { var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); @@ -140,13 +140,13 @@ NyanCat.prototype.appendRainbow = function() { * @private */ -NyanCat.prototype.drawRainbow = function() { +NyanCat.prototype.drawRainbow = function () { var self = this; - this.trajectories.forEach(function(line) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); + this.trajectories.forEach(function (line) { + process.stdout.write('\u001b[' + self.scoreboardWidth + 'C'); + process.stdout.write(line.join('')); + process.stdout.write('\n'); }); this.cursorUp(this.numberOfLines); @@ -157,31 +157,31 @@ NyanCat.prototype.drawRainbow = function() { * * @private */ -NyanCat.prototype.drawNyanCat = function() { +NyanCat.prototype.drawNyanCat = function () { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; var dist = '\u001b[' + startWidth + 'C'; var padding = ''; - write(dist); - write('_,------,'); - write('\n'); + process.stdout.write(dist); + process.stdout.write('_,------,'); + process.stdout.write('\n'); - write(dist); + process.stdout.write(dist); padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); + process.stdout.write('_|' + padding + '/\\_/\\ '); + process.stdout.write('\n'); - write(dist); + process.stdout.write(dist); padding = self.tick ? '_' : '__'; var tail = self.tick ? '~' : '^'; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); + process.stdout.write(tail + '|' + padding + this.face() + ' '); + process.stdout.write('\n'); - write(dist); + process.stdout.write(dist); padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); + process.stdout.write(padding + '"" "" '); + process.stdout.write('\n'); this.cursorUp(this.numberOfLines); }; @@ -193,7 +193,7 @@ NyanCat.prototype.drawNyanCat = function() { * @return {string} */ -NyanCat.prototype.face = function() { +NyanCat.prototype.face = function () { var stats = this.stats; if (stats.failures) { return '( x .x)'; @@ -212,8 +212,8 @@ NyanCat.prototype.face = function() { * @param {number} n */ -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); +NyanCat.prototype.cursorUp = function (n) { + process.stdout.write('\u001b[' + n + 'A'); }; /** @@ -223,8 +223,8 @@ NyanCat.prototype.cursorUp = function(n) { * @param {number} n */ -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); +NyanCat.prototype.cursorDown = function (n) { + process.stdout.write('\u001b[' + n + 'B'); }; /** @@ -233,7 +233,7 @@ NyanCat.prototype.cursorDown = function(n) { * @private * @return {Array} */ -NyanCat.prototype.generateColors = function() { +NyanCat.prototype.generateColors = function () { var colors = []; for (var i = 0; i < 6 * 7; i++) { @@ -255,7 +255,7 @@ NyanCat.prototype.generateColors = function() { * @param {string} str * @return {string} */ -NyanCat.prototype.rainbowify = function(str) { +NyanCat.prototype.rainbowify = function (str) { if (!Base.useColors) { return str; } @@ -264,13 +264,4 @@ NyanCat.prototype.rainbowify = function(str) { return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; }; -/** - * Stdout helper. - * - * @param {string} string A message to write to stdout. - */ -function write(string) { - process.stdout.write(string); -} - NyanCat.description = '"nyan cat"'; diff --git a/node_modules/mocha/lib/reporters/progress.js b/node_modules/mocha/lib/reporters/progress.js index 0211122..4f6d879 100644 --- a/node_modules/mocha/lib/reporters/progress.js +++ b/node_modules/mocha/lib/reporters/progress.js @@ -57,13 +57,13 @@ function Progress(runner, options) { options.verbose = reporterOptions.verbose || false; // tests started - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { process.stdout.write('\n'); cursor.hide(); }); // tests complete - runner.on(EVENT_TEST_END, function() { + runner.on(EVENT_TEST_END, function () { complete++; var percent = complete / total; @@ -89,7 +89,7 @@ function Progress(runner, options) { // tests are complete, output some stats // and the failures if any - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { cursor.show(); process.stdout.write('\n'); self.epilogue(); diff --git a/node_modules/mocha/lib/reporters/spec.js b/node_modules/mocha/lib/reporters/spec.js index e51ed80..8497249 100644 --- a/node_modules/mocha/lib/reporters/spec.js +++ b/node_modules/mocha/lib/reporters/spec.js @@ -45,28 +45,28 @@ function Spec(runner, options) { return Array(indents).join(' '); } - runner.on(EVENT_RUN_BEGIN, function() { + runner.on(EVENT_RUN_BEGIN, function () { Base.consoleLog(); }); - runner.on(EVENT_SUITE_BEGIN, function(suite) { + runner.on(EVENT_SUITE_BEGIN, function (suite) { ++indents; Base.consoleLog(color('suite', '%s%s'), indent(), suite.title); }); - runner.on(EVENT_SUITE_END, function() { + runner.on(EVENT_SUITE_END, function () { --indents; if (indents === 1) { Base.consoleLog(); } }); - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { var fmt = indent() + color('pending', ' - %s'); Base.consoleLog(fmt, test.title); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { var fmt; if (test.speed === 'fast') { fmt = @@ -84,7 +84,7 @@ function Spec(runner, options) { } }); - runner.on(EVENT_TEST_FAIL, function(test) { + runner.on(EVENT_TEST_FAIL, function (test) { Base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title); }); diff --git a/node_modules/mocha/lib/reporters/tap.js b/node_modules/mocha/lib/reporters/tap.js index aa79fb1..37fa8b5 100644 --- a/node_modules/mocha/lib/reporters/tap.js +++ b/node_modules/mocha/lib/reporters/tap.js @@ -49,27 +49,27 @@ function TAP(runner, options) { this._producer = createProducer(tapVersion); - runner.once(EVENT_RUN_BEGIN, function() { + runner.once(EVENT_RUN_BEGIN, function () { self._producer.writeVersion(); }); - runner.on(EVENT_TEST_END, function() { + runner.on(EVENT_TEST_END, function () { ++n; }); - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { self._producer.writePending(n, test); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { self._producer.writePass(n, test); }); - runner.on(EVENT_TEST_FAIL, function(test, err) { + runner.on(EVENT_TEST_FAIL, function (test, err) { self._producer.writeFail(n, test, err); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { self._producer.writeEpilogue(runner.stats); }); } @@ -113,8 +113,8 @@ function println(format, varArgs) { */ function createProducer(tapVersion) { var producers = { - '12': new TAP12Producer(), - '13': new TAP13Producer() + 12: new TAP12Producer(), + 13: new TAP13Producer() }; var producer = producers[tapVersion]; @@ -144,7 +144,7 @@ function TAPProducer() {} * * @abstract */ -TAPProducer.prototype.writeVersion = function() {}; +TAPProducer.prototype.writeVersion = function () {}; /** * Writes the plan to reporter output stream. @@ -152,7 +152,7 @@ TAPProducer.prototype.writeVersion = function() {}; * @abstract * @param {number} ntests - Number of tests that are planned to run. */ -TAPProducer.prototype.writePlan = function(ntests) { +TAPProducer.prototype.writePlan = function (ntests) { println('%d..%d', 1, ntests); }; @@ -163,7 +163,7 @@ TAPProducer.prototype.writePlan = function(ntests) { * @param {number} n - Index of test that passed. * @param {Test} test - Instance containing test information. */ -TAPProducer.prototype.writePass = function(n, test) { +TAPProducer.prototype.writePass = function (n, test) { println('ok %d %s', n, title(test)); }; @@ -174,7 +174,7 @@ TAPProducer.prototype.writePass = function(n, test) { * @param {number} n - Index of test that was skipped. * @param {Test} test - Instance containing test information. */ -TAPProducer.prototype.writePending = function(n, test) { +TAPProducer.prototype.writePending = function (n, test) { println('ok %d %s # SKIP -', n, title(test)); }; @@ -186,7 +186,7 @@ TAPProducer.prototype.writePending = function(n, test) { * @param {Test} test - Instance containing test information. * @param {Error} err - Reason the test failed. */ -TAPProducer.prototype.writeFail = function(n, test, err) { +TAPProducer.prototype.writeFail = function (n, test, err) { println('not ok %d %s', n, title(test)); }; @@ -196,7 +196,7 @@ TAPProducer.prototype.writeFail = function(n, test, err) { * @abstract * @param {Object} stats - Object containing run statistics. */ -TAPProducer.prototype.writeEpilogue = function(stats) { +TAPProducer.prototype.writeEpilogue = function (stats) { // :TBD: Why is this not counting pending tests? println('# tests ' + (stats.passes + stats.failures)); println('# pass ' + stats.passes); @@ -222,7 +222,7 @@ function TAP12Producer() { * Writes that test failed to reporter output stream, with error formatting. * @override */ - this.writeFail = function(n, test, err) { + this.writeFail = function (n, test, err) { TAPProducer.prototype.writeFail.call(this, n, test, err); if (err.message) { println(err.message.replace(/^/gm, ' ')); @@ -255,7 +255,7 @@ function TAP13Producer() { * Writes the TAP version to reporter output stream. * @override */ - this.writeVersion = function() { + this.writeVersion = function () { println('TAP version 13'); }; @@ -263,7 +263,7 @@ function TAP13Producer() { * Writes that test failed to reporter output stream, with error formatting. * @override */ - this.writeFail = function(n, test, err) { + this.writeFail = function (n, test, err) { TAPProducer.prototype.writeFail.call(this, n, test, err); var emitYamlBlock = err.message != null || err.stack != null; if (emitYamlBlock) { diff --git a/node_modules/mocha/lib/reporters/xunit.js b/node_modules/mocha/lib/reporters/xunit.js index a690ac5..4e6fe2b 100644 --- a/node_modules/mocha/lib/reporters/xunit.js +++ b/node_modules/mocha/lib/reporters/xunit.js @@ -74,19 +74,19 @@ function XUnit(runner, options) { // fall back to the default suite name suiteName = suiteName || DEFAULT_SUITE_NAME; - runner.on(EVENT_TEST_PENDING, function(test) { + runner.on(EVENT_TEST_PENDING, function (test) { tests.push(test); }); - runner.on(EVENT_TEST_PASS, function(test) { + runner.on(EVENT_TEST_PASS, function (test) { tests.push(test); }); - runner.on(EVENT_TEST_FAIL, function(test) { + runner.on(EVENT_TEST_FAIL, function (test) { tests.push(test); }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { self.write( tag( 'testsuite', @@ -103,7 +103,7 @@ function XUnit(runner, options) { ) ); - tests.forEach(function(t) { + tests.forEach(function (t) { self.test(t); }); @@ -122,9 +122,9 @@ inherits(XUnit, Base); * @param failures * @param {Function} fn */ -XUnit.prototype.done = function(failures, fn) { +XUnit.prototype.done = function (failures, fn) { if (this.fileStream) { - this.fileStream.end(function() { + this.fileStream.end(function () { fn(failures); }); } else { @@ -137,7 +137,7 @@ XUnit.prototype.done = function(failures, fn) { * * @param {string} line */ -XUnit.prototype.write = function(line) { +XUnit.prototype.write = function (line) { if (this.fileStream) { this.fileStream.write(line + '\n'); } else if (typeof process === 'object' && process.stdout) { @@ -152,12 +152,13 @@ XUnit.prototype.write = function(line) { * * @param {Test} test */ -XUnit.prototype.test = function(test) { +XUnit.prototype.test = function (test) { Base.useColors = false; var attrs = { classname: test.parent.fullTitle(), name: test.title, + file: test.file, time: test.duration / 1000 || 0 }; diff --git a/node_modules/mocha/lib/runnable.js b/node_modules/mocha/lib/runnable.js index 3b59680..5e0970b 100644 --- a/node_modules/mocha/lib/runnable.js +++ b/node_modules/mocha/lib/runnable.js @@ -57,7 +57,7 @@ utils.inherits(Runnable, EventEmitter); /** * Resets the state initially or for a next run. */ -Runnable.prototype.reset = function() { +Runnable.prototype.reset = function () { this.timedOut = false; this._currentRetry = 0; this.pending = false; @@ -86,7 +86,7 @@ Runnable.prototype.reset = function() { * @returns {Runnable} this * @chainable */ -Runnable.prototype.timeout = function(ms) { +Runnable.prototype.timeout = function (ms) { if (!arguments.length) { return this._timeout; } @@ -120,7 +120,7 @@ Runnable.prototype.timeout = function(ms) { * @param {number|string} ms * @return {Runnable|number} ms or Runnable instance. */ -Runnable.prototype.slow = function(ms) { +Runnable.prototype.slow = function (ms) { if (!arguments.length || typeof ms === 'undefined') { return this._slow; } @@ -138,7 +138,7 @@ Runnable.prototype.slow = function(ms) { * @memberof Mocha.Runnable * @public */ -Runnable.prototype.skip = function() { +Runnable.prototype.skip = function () { this.pending = true; throw new Pending('sync skip; aborting execution'); }; @@ -148,7 +148,7 @@ Runnable.prototype.skip = function() { * * @private */ -Runnable.prototype.isPending = function() { +Runnable.prototype.isPending = function () { return this.pending || (this.parent && this.parent.isPending()); }; @@ -157,7 +157,7 @@ Runnable.prototype.isPending = function() { * @return {boolean} * @private */ -Runnable.prototype.isFailed = function() { +Runnable.prototype.isFailed = function () { return !this.isPending() && this.state === constants.STATE_FAILED; }; @@ -166,7 +166,7 @@ Runnable.prototype.isFailed = function() { * @return {boolean} * @private */ -Runnable.prototype.isPassed = function() { +Runnable.prototype.isPassed = function () { return !this.isPending() && this.state === constants.STATE_PASSED; }; @@ -175,7 +175,7 @@ Runnable.prototype.isPassed = function() { * * @private */ -Runnable.prototype.retries = function(n) { +Runnable.prototype.retries = function (n) { if (!arguments.length) { return this._retries; } @@ -187,7 +187,7 @@ Runnable.prototype.retries = function(n) { * * @private */ -Runnable.prototype.currentRetry = function(n) { +Runnable.prototype.currentRetry = function (n) { if (!arguments.length) { return this._currentRetry; } @@ -202,7 +202,7 @@ Runnable.prototype.currentRetry = function(n) { * @public * @return {string} */ -Runnable.prototype.fullTitle = function() { +Runnable.prototype.fullTitle = function () { return this.titlePath().join(' '); }; @@ -211,9 +211,9 @@ Runnable.prototype.fullTitle = function() { * * @memberof Mocha.Runnable * @public - * @return {string} + * @return {string[]} */ -Runnable.prototype.titlePath = function() { +Runnable.prototype.titlePath = function () { return this.parent.titlePath().concat([this.title]); }; @@ -222,7 +222,7 @@ Runnable.prototype.titlePath = function() { * * @private */ -Runnable.prototype.clearTimeout = function() { +Runnable.prototype.clearTimeout = function () { clearTimeout(this.timer); }; @@ -231,7 +231,7 @@ Runnable.prototype.clearTimeout = function() { * * @private */ -Runnable.prototype.resetTimeout = function() { +Runnable.prototype.resetTimeout = function () { var self = this; var ms = this.timeout(); @@ -239,7 +239,7 @@ Runnable.prototype.resetTimeout = function() { return; } this.clearTimeout(); - this.timer = setTimeout(function() { + this.timer = setTimeout(function () { if (self.timeout() === 0) { return; } @@ -254,7 +254,7 @@ Runnable.prototype.resetTimeout = function() { * @private * @param {string[]} globals */ -Runnable.prototype.globals = function(globals) { +Runnable.prototype.globals = function (globals) { if (!arguments.length) { return this._allowedGlobals; } @@ -267,7 +267,7 @@ Runnable.prototype.globals = function(globals) { * @param {Function} fn * @private */ -Runnable.prototype.run = function(fn) { +Runnable.prototype.run = function (fn) { var self = this; var start = new Date(); var ctx = this.ctx; @@ -367,13 +367,13 @@ Runnable.prototype.run = function(fn) { if (result && typeof result.then === 'function') { self.resetTimeout(); result.then( - function() { + function () { done(); // Return null so libraries like bluebird do not warn about // subsequently constructed Promises. return null; }, - function(reason) { + function (reason) { done(reason || new Error('Promise rejected with no or falsy reason')); } ); @@ -391,7 +391,7 @@ Runnable.prototype.run = function(fn) { } function callFnAsync(fn) { - var result = fn.call(ctx, function(err) { + var result = fn.call(ctx, function (err) { if (err instanceof Error || toString.call(err) === '[object Error]') { return done(err); } @@ -423,7 +423,7 @@ Runnable.prototype.run = function(fn) { * @returns {Error} a "timeout" error * @private */ -Runnable.prototype._timeoutError = function(ms) { +Runnable.prototype._timeoutError = function (ms) { let msg = `Timeout of ${ms}ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.`; if (this.file) { msg += ' (' + this.file + ')'; @@ -463,7 +463,7 @@ var constants = utils.defineConstants( * @returns {*|Error} `value`, otherwise an `Error` * @private */ -Runnable.toValueOrError = function(value) { +Runnable.toValueOrError = function (value) { return ( value || createInvalidExceptionError( diff --git a/node_modules/mocha/lib/runner.js b/node_modules/mocha/lib/runner.js index 9ff3417..60a19f0 100644 --- a/node_modules/mocha/lib/runner.js +++ b/node_modules/mocha/lib/runner.js @@ -4,7 +4,6 @@ * Module dependencies. * @private */ -var util = require('util'); var EventEmitter = require('events').EventEmitter; var Pending = require('./pending'); var utils = require('./utils'); @@ -19,8 +18,6 @@ var EVENT_ROOT_SUITE_RUN = Suite.constants.EVENT_ROOT_SUITE_RUN; var STATE_FAILED = Runnable.constants.STATE_FAILED; var STATE_PASSED = Runnable.constants.STATE_PASSED; var STATE_PENDING = Runnable.constants.STATE_PENDING; -var dQuote = utils.dQuote; -var sQuote = utils.sQuote; var stackFilter = utils.stackTraceFilter(); var stringify = utils.stringify; @@ -138,22 +135,15 @@ class Runner extends EventEmitter { * @public * @class * @param {Suite} suite - Root suite - * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility). - * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready. + * @param {Object} [opts] - Settings object * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done. + * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready. + * @param {boolean} [opts.dryRun] - Whether to report tests without running them. + * @param {boolean} [opts.failZero] - Whether to fail test run if zero tests encountered. */ - constructor(suite, opts) { + constructor(suite, opts = {}) { super(); - if (opts === undefined) { - opts = {}; - } - if (typeof opts === 'boolean') { - // TODO: deprecate this - this._delay = opts; - opts = {}; - } else { - this._delay = opts.delay; - } + var self = this; this._globals = []; this._abort = false; @@ -166,7 +156,7 @@ class Runner extends EventEmitter { * @type {Map>>} */ this._eventListeners = new Map(); - this.on(constants.EVENT_TEST_END, function(test) { + this.on(constants.EVENT_TEST_END, function (test) { if (test.type === 'test' && test.retriedTest() && test.parent) { var idx = test.parent.tests && test.parent.tests.indexOf(test.retriedTest()); @@ -174,7 +164,7 @@ class Runner extends EventEmitter { } self.checkGlobals(test); }); - this.on(constants.EVENT_HOOK_END, function(hook) { + this.on(constants.EVENT_HOOK_END, function (hook) { self.checkGlobals(hook); }); this._defaultGrep = /.*/; @@ -223,7 +213,7 @@ Runner.immediately = global.setImmediate || process.nextTick; * @param {string} fn - Listener function * @private */ -Runner.prototype._addEventListener = function(target, eventName, listener) { +Runner.prototype._addEventListener = function (target, eventName, listener) { debug( '_addEventListener(): adding for event %s; %d current listeners', eventName, @@ -233,10 +223,7 @@ Runner.prototype._addEventListener = function(target, eventName, listener) { if ( this._eventListeners.has(target) && this._eventListeners.get(target).has(eventName) && - this._eventListeners - .get(target) - .get(eventName) - .has(listener) + this._eventListeners.get(target).get(eventName).has(listener) ) { debug( 'warning: tried to attach duplicate event listener for %s', @@ -263,7 +250,7 @@ Runner.prototype._addEventListener = function(target, eventName, listener) { * @param {function} listener - Listener function * @private */ -Runner.prototype._removeEventListener = function(target, eventName, listener) { +Runner.prototype._removeEventListener = function (target, eventName, listener) { target.removeListener(eventName, listener); if (this._eventListeners.has(target)) { @@ -287,7 +274,7 @@ Runner.prototype._removeEventListener = function(target, eventName, listener) { * Removes all event handlers set during a run on this instance. * Remark: this does _not_ clean/dispose the tests or suites themselves. */ -Runner.prototype.dispose = function() { +Runner.prototype.dispose = function () { this.removeAllListeners(); this._eventListeners.forEach((targetListeners, target) => { targetListeners.forEach((targetEventListeners, eventName) => { @@ -309,7 +296,7 @@ Runner.prototype.dispose = function() { * @param {boolean} invert * @return {Runner} Runner instance. */ -Runner.prototype.grep = function(re, invert) { +Runner.prototype.grep = function (re, invert) { debug('grep(): setting to %s', re); this._grep = re; this._invert = invert; @@ -326,11 +313,11 @@ Runner.prototype.grep = function(re, invert) { * @param {Suite} suite * @return {number} */ -Runner.prototype.grepTotal = function(suite) { +Runner.prototype.grepTotal = function (suite) { var self = this; var total = 0; - suite.eachTest(function(test) { + suite.eachTest(function (test) { var match = self._grep.test(test.fullTitle()); if (self._invert) { match = !match; @@ -349,7 +336,7 @@ Runner.prototype.grepTotal = function(suite) { * @return {Array} * @private */ -Runner.prototype.globalProps = function() { +Runner.prototype.globalProps = function () { var props = Object.keys(global); // non-enumerables @@ -371,7 +358,7 @@ Runner.prototype.globalProps = function() { * @param {Array} arr * @return {Runner} Runner instance. */ -Runner.prototype.globals = function(arr) { +Runner.prototype.globals = function (arr) { if (!arguments.length) { return this._globals; } @@ -385,7 +372,7 @@ Runner.prototype.globals = function(arr) { * * @private */ -Runner.prototype.checkGlobals = function(test) { +Runner.prototype.checkGlobals = function (test) { if (!this.checkLeaks) { return; } @@ -407,9 +394,8 @@ Runner.prototype.checkGlobals = function(test) { this._globals = this._globals.concat(leaks); if (leaks.length) { - var msg = 'global leak(s) detected: %s'; - var error = new Error(util.format(msg, leaks.map(sQuote).join(', '))); - this.fail(test, error); + var msg = `global leak(s) detected: ${leaks.map(e => `'${e}'`).join(', ')}`; + this.fail(test, new Error(msg)); } }; @@ -434,7 +420,7 @@ Runner.prototype.checkGlobals = function(test) { * @param {Error} err * @param {boolean} [force=false] - Whether to fail a pending test. */ -Runner.prototype.fail = function(test, err, force) { +Runner.prototype.fail = function (test, err, force) { force = force === true; if (test.isPending() && !force) { return; @@ -457,11 +443,22 @@ Runner.prototype.fail = function(test, err, force) { err = thrown2Error(err); } - try { - err.stack = - this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack); - } catch (ignore) { - // some environments do not take kindly to monkeying with the stack + // Filter the stack traces + if (!this.fullStackTrace) { + const alreadyFiltered = new Set(); + let currentErr = err; + + while (currentErr && currentErr.stack && !alreadyFiltered.has(currentErr)) { + alreadyFiltered.add(currentErr); + + try { + currentErr.stack = stackFilter(currentErr.stack); + } catch (ignore) { + // some environments do not take kindly to monkeying with the stack + } + + currentErr = currentErr.cause; + } } this.emit(constants.EVENT_TEST_FAIL, test, err); @@ -475,7 +472,9 @@ Runner.prototype.fail = function(test, err, force) { * @param {Function} fn */ -Runner.prototype.hook = function(name, fn) { +Runner.prototype.hook = function (name, fn) { + if (this._opts.dryRun) return fn(); + var suite = this.suite; var hooks = suite.getHooks(name); var self = this; @@ -502,7 +501,7 @@ Runner.prototype.hook = function(name, fn) { self.emit(constants.EVENT_HOOK_BEGIN, hook); if (!hook.listeners('error').length) { - self._addEventListener(hook, 'error', function(err) { + self._addEventListener(hook, 'error', function (err) { self.fail(hook, err); }); } @@ -527,10 +526,10 @@ Runner.prototype.hook = function(name, fn) { hook.pending = false; // activates hook for next test return fn(new Error('abort hookDown')); } else if (name === HOOK_TYPE_BEFORE_ALL) { - suite.tests.forEach(function(test) { + suite.tests.forEach(function (test) { test.pending = true; }); - suite.suites.forEach(function(suite) { + suite.suites.forEach(function (suite) { suite.pending = true; }); hooks = []; @@ -554,8 +553,7 @@ Runner.prototype.hook = function(name, fn) { function setHookTitle(hook) { hook.originalTitle = hook.originalTitle || hook.title; if (hook.ctx && hook.ctx.currentTest) { - hook.title = - hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title); + hook.title = `${hook.originalTitle} for "${hook.ctx.currentTest.title}"`; } else { var parentTitle; if (hook.parent.title) { @@ -563,12 +561,12 @@ Runner.prototype.hook = function(name, fn) { } else { parentTitle = hook.parent.root ? '{root}' : ''; } - hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle); + hook.title = `${hook.originalTitle} in "${parentTitle}"`; } } } - Runner.immediately(function() { + Runner.immediately(function () { next(0); }); }; @@ -582,7 +580,7 @@ Runner.prototype.hook = function(name, fn) { * @param {Array} suites * @param {Function} fn */ -Runner.prototype.hooks = function(name, suites, fn) { +Runner.prototype.hooks = function (name, suites, fn) { var self = this; var orig = this.suite; @@ -594,7 +592,7 @@ Runner.prototype.hooks = function(name, suites, fn) { return fn(); } - self.hook(name, function(err) { + self.hook(name, function (err) { if (err) { var errSuite = self.suite; self.suite = orig; @@ -609,25 +607,25 @@ Runner.prototype.hooks = function(name, suites, fn) { }; /** - * Run hooks from the top level down. + * Run 'afterEach' hooks from bottom up. * * @param {String} name * @param {Function} fn * @private */ -Runner.prototype.hookUp = function(name, fn) { +Runner.prototype.hookUp = function (name, fn) { var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; /** - * Run hooks from the bottom up. + * Run 'beforeEach' hooks from top level down. * * @param {String} name * @param {Function} fn * @private */ -Runner.prototype.hookDown = function(name, fn) { +Runner.prototype.hookDown = function (name, fn) { var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; @@ -639,7 +637,7 @@ Runner.prototype.hookDown = function(name, fn) { * @return {Array} * @private */ -Runner.prototype.parents = function() { +Runner.prototype.parents = function () { var suite = this.suite; var suites = []; while (suite.parent) { @@ -655,7 +653,9 @@ Runner.prototype.parents = function() { * @param {Function} fn * @private */ -Runner.prototype.runTest = function(fn) { +Runner.prototype.runTest = function (fn) { + if (this._opts.dryRun) return Runner.immediately(fn); + var self = this; var test = this.test; @@ -666,7 +666,7 @@ Runner.prototype.runTest = function(fn) { if (this.asyncOnly) { test.asyncOnly = true; } - this._addEventListener(test, 'error', function(err) { + this._addEventListener(test, 'error', function (err) { self.fail(test, err); }); if (this.allowUncaught) { @@ -687,7 +687,7 @@ Runner.prototype.runTest = function(fn) { * @param {Suite} suite * @param {Function} fn */ -Runner.prototype.runTests = function(suite, fn) { +Runner.prototype.runTests = function (suite, fn) { var self = this; var tests = suite.tests.slice(); var test; @@ -701,8 +701,7 @@ Runner.prototype.runTests = function(suite, fn) { self.suite = after ? errSuite.parent : errSuite; if (self.suite) { - // call hookUp afterEach - self.hookUp(HOOK_TYPE_AFTER_EACH, function(err2, errSuite2) { + self.hookUp(HOOK_TYPE_AFTER_EACH, function (err2, errSuite2) { self.suite = orig; // some hooks may fail even now if (err2) { @@ -776,7 +775,7 @@ Runner.prototype.runTests = function(suite, fn) { // execute test and hook(s) self.emit(constants.EVENT_TEST_BEGIN, (self.test = test)); - self.hookDown(HOOK_TYPE_BEFORE_EACH, function(err, errSuite) { + self.hookDown(HOOK_TYPE_BEFORE_EACH, function (err, errSuite) { // conditional skip within beforeEach if (test.isPending()) { if (self.forbidPending) { @@ -789,7 +788,7 @@ Runner.prototype.runTests = function(suite, fn) { // skip inner afterEach hooks below errSuite level var origSuite = self.suite; self.suite = errSuite || self.suite; - return self.hookUp(HOOK_TYPE_AFTER_EACH, function(e, eSuite) { + return self.hookUp(HOOK_TYPE_AFTER_EACH, function (e, eSuite) { self.suite = origSuite; next(e, eSuite); }); @@ -798,7 +797,7 @@ Runner.prototype.runTests = function(suite, fn) { return hookErr(err, errSuite, false); } self.currentRunnable = self.test; - self.runTest(function(err) { + self.runTest(function (err) { test = self.test; // conditional skip within it if (test.pending) { @@ -849,7 +848,7 @@ Runner.prototype.runTests = function(suite, fn) { * @param {Suite} suite * @param {Function} fn */ -Runner.prototype.runSuite = function(suite, fn) { +Runner.prototype.runSuite = function (suite, fn) { var i = 0; var self = this; var total = this.grepTotal(suite); @@ -889,7 +888,7 @@ Runner.prototype.runSuite = function(suite, fn) { // huge recursive loop and thus a maximum call stack error. // See comment in `this.runTests()` for more information. if (self._grep !== self._defaultGrep) { - Runner.immediately(function() { + Runner.immediately(function () { self.runSuite(curr, next); }); } else { @@ -904,7 +903,7 @@ Runner.prototype.runSuite = function(suite, fn) { // remove reference to test delete self.test; - self.hook(HOOK_TYPE_AFTER_ALL, function() { + self.hook(HOOK_TYPE_AFTER_ALL, function () { self.emit(constants.EVENT_SUITE_END, suite); fn(errSuite); }); @@ -912,7 +911,7 @@ Runner.prototype.runSuite = function(suite, fn) { this.nextSuite = next; - this.hook(HOOK_TYPE_BEFORE_ALL, function(err) { + this.hook(HOOK_TYPE_BEFORE_ALL, function (err) { if (err) { return done(); } @@ -936,7 +935,7 @@ Runner.prototype.runSuite = function(suite, fn) { * @param {Error} err - Some uncaught error * @private */ -Runner.prototype._uncaught = function(err) { +Runner.prototype._uncaught = function (err) { // this is defensive to prevent future developers from mis-calling this function. // it's more likely that it'd be called with the incorrect context--say, the global // `process` object--than it would to be called with a context that is not a "subclass" @@ -1031,17 +1030,21 @@ Runner.prototype._uncaught = function(err) { * @public * @memberof Runner * @param {Function} fn - Callback when finished - * @param {{files: string[], options: Options}} [opts] - For subclasses + * @param {Object} [opts] - For subclasses + * @param {string[]} opts.files - Files to run + * @param {Options} opts.options - command-line options * @returns {Runner} Runner instance. */ -Runner.prototype.run = function(fn, opts = {}) { +Runner.prototype.run = function (fn, opts = {}) { var rootSuite = this.suite; var options = opts.options || {}; debug('run(): got options: %O', options); - fn = fn || function() {}; + fn = fn || function () {}; const end = () => { + if (!this.total && this._opts.failZero) this.failures = 1; + debug('run(): root suite completed; emitting %s', constants.EVENT_RUN_END); this.emit(constants.EVENT_RUN_END); }; @@ -1062,7 +1065,7 @@ Runner.prototype.run = function(fn, opts = {}) { debug('run(): filtered exclusive Runnables'); } this.state = constants.STATE_RUNNING; - if (this._delay) { + if (this._opts.delay) { this.emit(constants.EVENT_DELAY_END); debug('run(): "delay" ended'); } @@ -1078,7 +1081,7 @@ Runner.prototype.run = function(fn, opts = {}) { } // callback - this.on(constants.EVENT_RUN_END, function() { + this.on(constants.EVENT_RUN_END, function () { this.state = constants.STATE_STOPPED; debug('run(): emitted %s', constants.EVENT_RUN_END); fn(this.failures); @@ -1089,7 +1092,7 @@ Runner.prototype.run = function(fn, opts = {}) { this._addEventListener(process, 'uncaughtException', this.uncaught); this._addEventListener(process, 'unhandledRejection', this.unhandled); - if (this._delay) { + if (this._opts.delay) { // for reporters, I guess. // might be nice to debounce some dots while we wait. this.emit(constants.EVENT_DELAY_BEGIN, rootSuite); @@ -1125,7 +1128,7 @@ Runner.prototype.run = function(fn, opts = {}) { * } * } */ -Runner.prototype.linkPartialObjects = function(value) { +Runner.prototype.linkPartialObjects = function (value) { return this; }; @@ -1150,7 +1153,7 @@ Runner.prototype.runAsync = async function runAsync(opts = {}) { * @public * @return {Runner} Runner instance. */ -Runner.prototype.abort = function() { +Runner.prototype.abort = function () { debug('abort(): aborting'); this._abort = true; @@ -1178,7 +1181,7 @@ Runner.prototype.isParallelMode = function isParallelMode() { * @chainable * @abstract */ -Runner.prototype.workerReporter = function() { +Runner.prototype.workerReporter = function () { throw createUnsupportedError('workerReporter() not supported in serial mode'); }; @@ -1191,7 +1194,7 @@ Runner.prototype.workerReporter = function() { * @return {Array} */ function filterLeaks(ok, globals) { - return globals.filter(function(key) { + return globals.filter(function (key) { // Firefox and Chrome exposes iframes as index inside the window object if (/^\d+/.test(key)) { return false; @@ -1215,7 +1218,7 @@ function filterLeaks(ok, globals) { return false; } - var matched = ok.filter(function(ok) { + var matched = ok.filter(function (ok) { if (~ok.indexOf('*')) { return key.indexOf(ok.split('*')[0]) === 0; } diff --git a/node_modules/mocha/lib/stats-collector.js b/node_modules/mocha/lib/stats-collector.js index 938778f..738fd5d 100644 --- a/node_modules/mocha/lib/stats-collector.js +++ b/node_modules/mocha/lib/stats-collector.js @@ -56,25 +56,25 @@ function createStatsCollector(runner) { runner.stats = stats; - runner.once(EVENT_RUN_BEGIN, function() { + runner.once(EVENT_RUN_BEGIN, function () { stats.start = new Date(); }); - runner.on(EVENT_SUITE_BEGIN, function(suite) { + runner.on(EVENT_SUITE_BEGIN, function (suite) { suite.root || stats.suites++; }); - runner.on(EVENT_TEST_PASS, function() { + runner.on(EVENT_TEST_PASS, function () { stats.passes++; }); - runner.on(EVENT_TEST_FAIL, function() { + runner.on(EVENT_TEST_FAIL, function () { stats.failures++; }); - runner.on(EVENT_TEST_PENDING, function() { + runner.on(EVENT_TEST_PENDING, function () { stats.pending++; }); - runner.on(EVENT_TEST_END, function() { + runner.on(EVENT_TEST_END, function () { stats.tests++; }); - runner.once(EVENT_RUN_END, function() { + runner.once(EVENT_RUN_END, function () { stats.end = new Date(); stats.duration = stats.end - stats.start; }); diff --git a/node_modules/mocha/lib/suite.js b/node_modules/mocha/lib/suite.js index 2f16b2f..64d7183 100644 --- a/node_modules/mocha/lib/suite.js +++ b/node_modules/mocha/lib/suite.js @@ -10,7 +10,6 @@ var { assignNewMochaID, clamp, constants: utilsConstants, - createMap, defineConstants, getMochaID, inherits, @@ -36,7 +35,7 @@ exports = module.exports = Suite; * @param {string} title - Title * @return {Suite} */ -Suite.create = function(parent, title) { +Suite.create = function (parent, title) { var suite = new Suite(title, parent.ctx); suite.parent = parent; title = suite.fullTitle(); @@ -92,16 +91,6 @@ function Suite(title, parentContext, isRoot) { }); this.reset(); - - this.on('newListener', function(event) { - if (deprecatedEvents[event]) { - errors.deprecate( - 'Event "' + - event + - '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm' - ); - } - }); } /** @@ -112,7 +101,7 @@ inherits(Suite, EventEmitter); /** * Resets the state initially or for a next run. */ -Suite.prototype.reset = function() { +Suite.prototype.reset = function () { this.delayed = false; function doReset(thingToReset) { thingToReset.reset(); @@ -131,7 +120,7 @@ Suite.prototype.reset = function() { * @private * @return {Suite} */ -Suite.prototype.clone = function() { +Suite.prototype.clone = function () { var suite = new Suite(this.title); debug('clone'); suite.ctx = this.ctx; @@ -151,7 +140,7 @@ Suite.prototype.clone = function() { * @param {number|string} ms * @return {Suite|number} for chaining */ -Suite.prototype.timeout = function(ms) { +Suite.prototype.timeout = function (ms) { if (!arguments.length) { return this._timeout; } @@ -176,7 +165,7 @@ Suite.prototype.timeout = function(ms) { * @param {number|string} n * @return {Suite|number} for chaining */ -Suite.prototype.retries = function(n) { +Suite.prototype.retries = function (n) { if (!arguments.length) { return this._retries; } @@ -192,7 +181,7 @@ Suite.prototype.retries = function(n) { * @param {number|string} ms * @return {Suite|number} for chaining */ -Suite.prototype.slow = function(ms) { +Suite.prototype.slow = function (ms) { if (!arguments.length) { return this._slow; } @@ -211,7 +200,7 @@ Suite.prototype.slow = function(ms) { * @param {boolean} bail * @return {Suite|number} for chaining */ -Suite.prototype.bail = function(bail) { +Suite.prototype.bail = function (bail) { if (!arguments.length) { return this._bail; } @@ -225,7 +214,7 @@ Suite.prototype.bail = function(bail) { * * @private */ -Suite.prototype.isPending = function() { +Suite.prototype.isPending = function () { return this.pending || (this.parent && this.parent.isPending()); }; @@ -236,7 +225,7 @@ Suite.prototype.isPending = function() { * @param {Function} fn - Hook callback * @returns {Hook} A new hook */ -Suite.prototype._createHook = function(title, fn) { +Suite.prototype._createHook = function (title, fn) { var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); @@ -255,7 +244,7 @@ Suite.prototype._createHook = function(title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.beforeAll = function(title, fn) { +Suite.prototype.beforeAll = function (title, fn) { if (this.isPending()) { return this; } @@ -279,7 +268,7 @@ Suite.prototype.beforeAll = function(title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.afterAll = function(title, fn) { +Suite.prototype.afterAll = function (title, fn) { if (this.isPending()) { return this; } @@ -303,7 +292,7 @@ Suite.prototype.afterAll = function(title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.beforeEach = function(title, fn) { +Suite.prototype.beforeEach = function (title, fn) { if (this.isPending()) { return this; } @@ -327,7 +316,7 @@ Suite.prototype.beforeEach = function(title, fn) { * @param {Function} fn * @return {Suite} for chaining */ -Suite.prototype.afterEach = function(title, fn) { +Suite.prototype.afterEach = function (title, fn) { if (this.isPending()) { return this; } @@ -350,7 +339,7 @@ Suite.prototype.afterEach = function(title, fn) { * @param {Suite} suite * @return {Suite} for chaining */ -Suite.prototype.addSuite = function(suite) { +Suite.prototype.addSuite = function (suite) { suite.parent = this; suite.root = false; suite.timeout(this.timeout()); @@ -369,7 +358,7 @@ Suite.prototype.addSuite = function(suite) { * @param {Test} test * @return {Suite} for chaining */ -Suite.prototype.addTest = function(test) { +Suite.prototype.addTest = function (test) { test.parent = this; test.timeout(this.timeout()); test.retries(this.retries()); @@ -388,7 +377,7 @@ Suite.prototype.addTest = function(test) { * @public * @return {string} */ -Suite.prototype.fullTitle = function() { +Suite.prototype.fullTitle = function () { return this.titlePath().join(' '); }; @@ -398,9 +387,9 @@ Suite.prototype.fullTitle = function() { * * @memberof Suite * @public - * @return {string} + * @return {string[]} */ -Suite.prototype.titlePath = function() { +Suite.prototype.titlePath = function () { var result = []; if (this.parent) { result = result.concat(this.parent.titlePath()); @@ -418,9 +407,9 @@ Suite.prototype.titlePath = function() { * @public * @return {number} */ -Suite.prototype.total = function() { +Suite.prototype.total = function () { return ( - this.suites.reduce(function(sum, suite) { + this.suites.reduce(function (sum, suite) { return sum + suite.total(); }, 0) + this.tests.length ); @@ -434,9 +423,9 @@ Suite.prototype.total = function() { * @param {Function} fn * @return {Suite} */ -Suite.prototype.eachTest = function(fn) { +Suite.prototype.eachTest = function (fn) { this.tests.forEach(fn); - this.suites.forEach(function(suite) { + this.suites.forEach(function (suite) { suite.eachTest(fn); }); return this; @@ -462,7 +451,7 @@ Suite.prototype.hasOnly = function hasOnly() { return ( this._onlyTests.length > 0 || this._onlySuites.length > 0 || - this.suites.some(function(suite) { + this.suites.some(function (suite) { return suite.hasOnly(); }) ); @@ -482,7 +471,7 @@ Suite.prototype.filterOnly = function filterOnly() { } else { // Otherwise, do not run any of the tests in this suite. this.tests = []; - this._onlySuites.forEach(function(onlySuite) { + this._onlySuites.forEach(function (onlySuite) { // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. if (onlySuite.hasOnly()) { @@ -491,7 +480,7 @@ Suite.prototype.filterOnly = function filterOnly() { }); // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. var onlySuites = this._onlySuites; - this.suites = this.suites.filter(function(childSuite) { + this.suites = this.suites.filter(function (childSuite) { return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly(); }); } @@ -505,7 +494,7 @@ Suite.prototype.filterOnly = function filterOnly() { * @private * @param {Suite} suite */ -Suite.prototype.appendOnlySuite = function(suite) { +Suite.prototype.appendOnlySuite = function (suite) { this._onlySuites.push(suite); }; @@ -514,7 +503,7 @@ Suite.prototype.appendOnlySuite = function(suite) { * * @private */ -Suite.prototype.markOnly = function() { +Suite.prototype.markOnly = function () { this.parent && this.parent.appendOnlySuite(this); }; @@ -524,7 +513,7 @@ Suite.prototype.markOnly = function() { * @private * @param {Test} test */ -Suite.prototype.appendOnlyTest = function(test) { +Suite.prototype.appendOnlyTest = function (test) { this._onlyTests.push(test); }; @@ -539,8 +528,8 @@ Suite.prototype.getHooks = function getHooks(name) { /** * cleans all references from this suite and all child suites. */ -Suite.prototype.dispose = function() { - this.suites.forEach(function(suite) { +Suite.prototype.dispose = function () { + this.suites.forEach(function (suite) { suite.dispose(); }); this.cleanReferences(); @@ -594,10 +583,10 @@ Suite.prototype.serialize = function serialize() { return { _bail: this._bail, $$fullTitle: this.fullTitle(), - $$isPending: this.isPending(), + $$isPending: Boolean(this.isPending()), root: this.root, title: this.title, - id: this.id, + [MOCHA_ID_PROP_NAME]: this.id, parent: this.parent ? {[MOCHA_ID_PROP_NAME]: this.parent.id} : null }; }; @@ -614,7 +603,7 @@ var constants = defineConstants( */ { /** - * Event emitted after a test file has been loaded Not emitted in browser. + * Event emitted after a test file has been loaded. Not emitted in browser. */ EVENT_FILE_POST_REQUIRE: 'post-require', /** @@ -626,70 +615,52 @@ var constants = defineConstants( */ EVENT_FILE_REQUIRE: 'require', /** - * Event emitted when `global.run()` is called (use with `delay` option) + * Event emitted when `global.run()` is called (use with `delay` option). */ EVENT_ROOT_SUITE_RUN: 'run', /** - * Namespace for collection of a `Suite`'s "after all" hooks + * Namespace for collection of a `Suite`'s "after all" hooks. */ HOOK_TYPE_AFTER_ALL: 'afterAll', /** - * Namespace for collection of a `Suite`'s "after each" hooks + * Namespace for collection of a `Suite`'s "after each" hooks. */ HOOK_TYPE_AFTER_EACH: 'afterEach', /** - * Namespace for collection of a `Suite`'s "before all" hooks + * Namespace for collection of a `Suite`'s "before all" hooks. */ HOOK_TYPE_BEFORE_ALL: 'beforeAll', /** - * Namespace for collection of a `Suite`'s "before all" hooks + * Namespace for collection of a `Suite`'s "before each" hooks. */ HOOK_TYPE_BEFORE_EACH: 'beforeEach', - // the following events are all deprecated - /** - * Emitted after an "after all" `Hook` has been added to a `Suite`. Deprecated + * Emitted after a child `Suite` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_SUITE: 'suite', + /** + * Emitted after an "after all" `Hook` has been added to a `Suite`. */ EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll', /** - * Emitted after an "after each" `Hook` has been added to a `Suite` Deprecated + * Emitted after an "after each" `Hook` has been added to a `Suite`. */ EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach', /** - * Emitted after an "before all" `Hook` has been added to a `Suite` Deprecated + * Emitted after an "before all" `Hook` has been added to a `Suite`. */ EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll', /** - * Emitted after an "before each" `Hook` has been added to a `Suite` Deprecated + * Emitted after an "before each" `Hook` has been added to a `Suite`. */ EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach', /** - * Emitted after a child `Suite` has been added to a `Suite`. Deprecated - */ - EVENT_SUITE_ADD_SUITE: 'suite', - /** - * Emitted after a `Test` has been added to a `Suite`. Deprecated + * Emitted after a `Test` has been added to a `Suite`. */ EVENT_SUITE_ADD_TEST: 'test' } ); -/** - * @summary There are no known use cases for these events. - * @desc This is a `Set`-like object having all keys being the constant's string value and the value being `true`. - * @todo Remove eventually - * @type {Object} - * @ignore - */ -var deprecatedEvents = Object.keys(constants) - .filter(function(constant) { - return constant.substring(0, 15) === 'EVENT_SUITE_ADD'; - }) - .reduce(function(acc, constant) { - acc[constants[constant]] = true; - return acc; - }, createMap()); - Suite.constants = constants; diff --git a/node_modules/mocha/lib/test.js b/node_modules/mocha/lib/test.js index f2be51b..0b8fe18 100644 --- a/node_modules/mocha/lib/test.js +++ b/node_modules/mocha/lib/test.js @@ -41,7 +41,7 @@ utils.inherits(Test, Runnable); /** * Resets the state initially or for a next run. */ -Test.prototype.reset = function() { +Test.prototype.reset = function () { Runnable.prototype.reset.call(this); this.pending = !this.fn; delete this.state; @@ -52,7 +52,7 @@ Test.prototype.reset = function() { * * @private */ -Test.prototype.retriedTest = function(n) { +Test.prototype.retriedTest = function (n) { if (!arguments.length) { return this._retriedTest; } @@ -64,11 +64,11 @@ Test.prototype.retriedTest = function(n) { * * @private */ -Test.prototype.markOnly = function() { +Test.prototype.markOnly = function () { this.parent.appendOnlyTest(this); }; -Test.prototype.clone = function() { +Test.prototype.clone = function () { var test = new Test(this.title, this.fn); test.timeout(this.timeout()); test.slow(this.slow()); @@ -92,7 +92,7 @@ Test.prototype.serialize = function serialize() { return { $$currentRetry: this._currentRetry, $$fullTitle: this.fullTitle(), - $$isPending: this.pending, + $$isPending: Boolean(this.pending), $$retriedTest: this._retriedTest || null, $$slow: this._slow, $$titlePath: this.titlePath(), diff --git a/node_modules/mocha/lib/utils.js b/node_modules/mocha/lib/utils.js index c2c5a95..fc7271d 100644 --- a/node_modules/mocha/lib/utils.js +++ b/node_modules/mocha/lib/utils.js @@ -8,12 +8,9 @@ /** * Module dependencies. */ - -const {nanoid} = require('nanoid/non-secure'); var path = require('path'); var util = require('util'); var he = require('he'); -const errors = require('./errors'); const MOCHA_ID_PROP_NAME = '__mocha_id__'; @@ -35,7 +32,7 @@ exports.inherits = util.inherits; * @param {string} html * @return {string} */ -exports.escape = function(html) { +exports.escape = function (html) { return he.encode(String(html), {useNamedReferences: false}); }; @@ -46,7 +43,7 @@ exports.escape = function(html) { * @param {Object} obj * @return {boolean} */ -exports.isString = function(obj) { +exports.isString = function (obj) { return typeof obj === 'string'; }; @@ -57,7 +54,7 @@ exports.isString = function(obj) { * @param {string} str * @return {string} */ -exports.slug = function(str) { +exports.slug = function (str) { return str .toLowerCase() .replace(/\s+/g, '-') @@ -71,13 +68,13 @@ exports.slug = function(str) { * @param {string} str * @return {string} */ -exports.clean = function(str) { +exports.clean = function (str) { str = str .replace(/\r\n?|[\n\u2028\u2029]/g, '\n') .replace(/^\uFEFF/, '') // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content .replace( - /^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, + /^function(?:\s*|\s[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\}|((?:.|\n)*))$/, '$1$2$3' ); @@ -213,7 +210,7 @@ exports.type = function type(value) { * @param {*} value * @return {string} */ -exports.stringify = function(value) { +exports.stringify = function (value) { var typeHint = canonicalType(value); if (!~['object', 'array', 'function'].indexOf(typeHint)) { @@ -229,7 +226,7 @@ exports.stringify = function(value) { // IE7/IE8 has a bizarre String constructor; needs to be coerced // into an array and back to obj. if (typeHint === 'string' && typeof value === 'object') { - value = value.split('').reduce(function(acc, char, idx) { + value = value.split('').reduce(function (acc, char, idx) { acc[idx] = char; return acc; }, {}); @@ -384,14 +381,14 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) { canonicalizedObj = value; break; case 'array': - withStack(value, function() { - canonicalizedObj = value.map(function(item) { + withStack(value, function () { + canonicalizedObj = value.map(function (item) { return exports.canonicalize(item, stack); }); }); break; case 'function': - /* eslint-disable-next-line no-unused-vars */ + /* eslint-disable-next-line no-unused-vars, no-unreachable-loop */ for (prop in value) { canonicalizedObj = {}; break; @@ -404,10 +401,10 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) { /* falls through */ case 'object': canonicalizedObj = canonicalizedObj || {}; - withStack(value, function() { + withStack(value, function () { Object.keys(value) .sort() - .forEach(function(key) { + .forEach(function (key) { canonicalizedObj[key] = exports.canonicalize(value[key], stack); }); }); @@ -435,7 +432,7 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) { * (i.e: strip Mocha and internal node functions from stack trace). * @returns {Function} */ -exports.stackTraceFilter = function() { +exports.stackTraceFilter = function () { // TODO: Replace with `process.browser` var is = typeof document === 'undefined' ? {node: true} : {browser: true}; var slash = path.sep; @@ -443,9 +440,8 @@ exports.stackTraceFilter = function() { if (is.node) { cwd = exports.cwd() + slash; } else { - cwd = (typeof location === 'undefined' - ? window.location - : location + cwd = ( + typeof location === 'undefined' ? window.location : location ).href.replace(/\/[^/]*$/, '/'); slash = '/'; } @@ -469,10 +465,10 @@ exports.stackTraceFilter = function() { ); } - return function(stack) { + return function (stack) { stack = stack.split('\n'); - stack = stack.reduce(function(list, line) { + stack = stack.reduce(function (list, line) { if (isMochaInternal(line)) { return list; } @@ -519,49 +515,11 @@ exports.clamp = function clamp(value, range) { return Math.min(Math.max(value, range[0]), range[1]); }; -/** - * Single quote text by combining with undirectional ASCII quotation marks. - * - * @description - * Provides a simple means of markup for quoting text to be used in output. - * Use this to quote names of variables, methods, and packages. - * - * package 'foo' cannot be found - * - * @private - * @param {string} str - Value to be quoted. - * @returns {string} quoted value - * @example - * sQuote('n') // => 'n' - */ -exports.sQuote = function(str) { - return "'" + str + "'"; -}; - -/** - * Double quote text by combining with undirectional ASCII quotation marks. - * - * @description - * Provides a simple means of markup for quoting text to be used in output. - * Use this to quote names of datatypes, classes, pathnames, and strings. - * - * argument 'value' must be "string" or "number" - * - * @private - * @param {string} str - Value to be quoted. - * @returns {string} quoted value - * @example - * dQuote('number') // => "number" - */ -exports.dQuote = function(str) { - return '"' + str + '"'; -}; - /** * It's a noop. * @public */ -exports.noop = function() {}; +exports.noop = function () {}; /** * Creates a map-like object. @@ -578,7 +536,7 @@ exports.noop = function() {}; * @param {...*} [obj] - Arguments to `Object.assign()`. * @returns {Object} An object with no prototype, having `...obj` properties */ -exports.createMap = function(obj) { +exports.createMap = function (obj) { return Object.assign.apply( null, [Object.create(null)].concat(Array.prototype.slice.call(arguments)) @@ -597,39 +555,13 @@ exports.createMap = function(obj) { * @returns {Object} A frozen object with no prototype, having `...obj` properties * @throws {TypeError} if argument is not a non-empty object. */ -exports.defineConstants = function(obj) { +exports.defineConstants = function (obj) { if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) { throw new TypeError('Invalid argument; expected a non-empty object'); } return Object.freeze(exports.createMap(obj)); }; -/** - * Whether current version of Node support ES modules - * - * @description - * Versions prior to 10 did not support ES Modules, and version 10 has an old incompatible version of ESM. - * This function returns whether Node.JS has ES Module supports that is compatible with Mocha's needs, - * which is version >=12.11. - * - * @param {partialSupport} whether the full Node.js ESM support is available (>= 12) or just something that supports the runtime (>= 10) - * - * @returns {Boolean} whether the current version of Node.JS supports ES Modules in a way that is compatible with Mocha - */ -exports.supportsEsModules = function(partialSupport) { - if (!exports.isBrowser() && process.versions && process.versions.node) { - var versionFields = process.versions.node.split('.'); - var major = +versionFields[0]; - var minor = +versionFields[1]; - - if (!partialSupport) { - return major >= 13 || (major === 12 && minor >= 11); - } else { - return major >= 10; - } - } -}; - /** * Returns current working directory * @@ -650,35 +582,6 @@ exports.isBrowser = function isBrowser() { return Boolean(process.browser); }; -/** - * Lookup file names at the given `path`. - * - * @description - * Filenames are returned in _traversal_ order by the OS/filesystem. - * **Make no assumption that the names will be sorted in any fashion.** - * - * @public - * @alias module:lib/cli.lookupFiles - * @param {string} filepath - Base path to start searching from. - * @param {string[]} [extensions=[]] - File extensions to look for. - * @param {boolean} [recursive=false] - Whether to recurse into subdirectories. - * @return {string[]} An array of paths. - * @throws {Error} if no files match pattern. - * @throws {TypeError} if `filepath` is directory and `extensions` not provided. - * @deprecated Moved to {@link module:lib/cli.lookupFiles} - */ -exports.lookupFiles = (...args) => { - if (exports.isBrowser()) { - throw errors.createUnsupportedError( - 'lookupFiles() is only supported in Node.js!' - ); - } - errors.deprecate( - '`lookupFiles()` in module `mocha/lib/utils` has moved to module `mocha/lib/cli` and will be removed in the next major revision of Mocha' - ); - return require('./cli').lookupFiles(...args); -}; - /* * Casts `value` to an array; useful for optionally accepting array parameters * @@ -710,11 +613,22 @@ exports.constants = exports.defineConstants({ MOCHA_ID_PROP_NAME }); +const uniqueIDBase = + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'; + /** * Creates a new unique identifier + * Does not create cryptographically safe ids. + * Trivial copy of nanoid/non-secure * @returns {string} Unique identifier */ -exports.uniqueID = () => nanoid(); +exports.uniqueID = () => { + let id = ''; + for (let i = 0; i < 21; i++) { + id += uniqueIDBase[(Math.random() * 64) | 0]; + } + return id; +}; exports.assignNewMochaID = obj => { const id = exports.uniqueID(); diff --git a/node_modules/mocha/mocha.css b/node_modules/mocha/mocha.css index 4ca8fcb..b4d7e5b 100644 --- a/node_modules/mocha/mocha.css +++ b/node_modules/mocha/mocha.css @@ -1,7 +1,73 @@ @charset "utf-8"; +:root { + --mocha-color: #000; + --mocha-bg-color: #fff; + --mocha-pass-icon-color: #00d6b2; + --mocha-pass-color: #fff; + --mocha-pass-shadow-color: rgba(0,0,0,.2); + --mocha-pass-mediump-color: #c09853; + --mocha-pass-slow-color: #b94a48; + --mocha-test-pending-color: #0b97c4; + --mocha-test-pending-icon-color: #0b97c4; + --mocha-test-fail-color: #c00; + --mocha-test-fail-icon-color: #c00; + --mocha-test-fail-pre-color: #000; + --mocha-test-fail-pre-error-color: #c00; + --mocha-test-html-error-color: #000; + --mocha-box-shadow-color: #eee; + --mocha-box-bottom-color: #ddd; + --mocha-test-replay-color: #000; + --mocha-test-replay-bg-color: #eee; + --mocha-stats-color: #888; + --mocha-stats-em-color: #000; + --mocha-stats-hover-color: #eee; + --mocha-error-color: #c00; + + --mocha-code-comment: #ddd; + --mocha-code-init: #2f6fad; + --mocha-code-string: #5890ad; + --mocha-code-keyword: #8a6343; + --mocha-code-number: #2f6fad; +} + +@media (prefers-color-scheme: dark) { + :root { + --mocha-color: #fff; + --mocha-bg-color: #222; + --mocha-pass-icon-color: #00d6b2; + --mocha-pass-color: #222; + --mocha-pass-shadow-color: rgba(255,255,255,.2); + --mocha-pass-mediump-color: #f1be67; + --mocha-pass-slow-color: #f49896; + --mocha-test-pending-color: #0b97c4; + --mocha-test-pending-icon-color: #0b97c4; + --mocha-test-fail-color: #f44; + --mocha-test-fail-icon-color: #f44; + --mocha-test-fail-pre-color: #fff; + --mocha-test-fail-pre-error-color: #f44; + --mocha-test-html-error-color: #fff; + --mocha-box-shadow-color: #444; + --mocha-box-bottom-color: #555; + --mocha-test-replay-color: #fff; + --mocha-test-replay-bg-color: #444; + --mocha-stats-color: #aaa; + --mocha-stats-em-color: #fff; + --mocha-stats-hover-color: #444; + --mocha-error-color: #f44; + + --mocha-code-comment: #ddd; + --mocha-code-init: #9cc7f1; + --mocha-code-string: #80d4ff; + --mocha-code-keyword: #e3a470; + --mocha-code-number: #4ca7ff; + } +} + body { margin:0; + background-color: var(--mocha-bg-color); + color: var(--mocha-color); } #mocha { @@ -69,11 +135,11 @@ body { } #mocha .test.pass.medium .duration { - background: #c09853; + background: var(--mocha-pass-mediump-color); } #mocha .test.pass.slow .duration { - background: #b94a48; + background: var(--mocha-pass-slow-color); } #mocha .test.pass::before { @@ -82,17 +148,17 @@ body { display: block; float: left; margin-right: 5px; - color: #00d6b2; + color: var(--mocha-pass-icon-color); } #mocha .test.pass .duration { font-size: 9px; margin-left: 5px; padding: 2px 5px; - color: #fff; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + color: var(--mocha-pass-color); + -webkit-box-shadow: inset 0 1px 1px var(--mocha-pass-shadow-color); + -moz-box-shadow: inset 0 1px 1px var(--mocha-pass-shadow-color); + box-shadow: inset 0 1px 1px var(--mocha-pass-shadow-color); -webkit-border-radius: 5px; -moz-border-radius: 5px; -ms-border-radius: 5px; @@ -105,20 +171,20 @@ body { } #mocha .test.pending { - color: #0b97c4; + color: var(--mocha-test-pending-color); } #mocha .test.pending::before { content: '◦'; - color: #0b97c4; + color: var(--mocha-test-pending-icon-color); } #mocha .test.fail { - color: #c00; + color: var(--mocha-test-fail-color); } #mocha .test.fail pre { - color: black; + color: var(--mocha-test-fail-pre-color); } #mocha .test.fail::before { @@ -127,35 +193,35 @@ body { display: block; float: left; margin-right: 5px; - color: #c00; + color: var(--mocha-test-fail-icon-color); } #mocha .test pre.error { - color: #c00; + color: var(--mocha-test-fail-pre-error-color); max-height: 300px; overflow: auto; } #mocha .test .html-error { overflow: auto; - color: black; + color: var(--mocha-test-html-error-color); display: block; float: left; clear: left; font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; - border: 1px solid #eee; + border: 1px solid var(--mocha-box-shadow-color); max-width: 85%; /*(1)*/ max-width: -webkit-calc(100% - 42px); max-width: -moz-calc(100% - 42px); max-width: calc(100% - 42px); /*(2)*/ max-height: 300px; word-wrap: break-word; - border-bottom-color: #ddd; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-box-shadow: 0 1px 3px #eee; - box-shadow: 0 1px 3px #eee; + border-bottom-color: var(--mocha-box-bottom-color); + -webkit-box-shadow: 0 1px 3px var(--mocha-box-shadow-color); + -moz-box-shadow: 0 1px 3px var(--mocha-box-shadow-color); + box-shadow: 0 1px 3px var(--mocha-box-shadow-color); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; @@ -187,16 +253,16 @@ body { font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; - border: 1px solid #eee; + border: 1px solid var(--mocha-box-shadow-color); max-width: 85%; /*(1)*/ max-width: -webkit-calc(100% - 42px); max-width: -moz-calc(100% - 42px); max-width: calc(100% - 42px); /*(2)*/ word-wrap: break-word; - border-bottom-color: #ddd; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-box-shadow: 0 1px 3px #eee; - box-shadow: 0 1px 3px #eee; + border-bottom-color: var(--mocha-box-bottom-color); + -webkit-box-shadow: 0 1px 3px var(--mocha-box-shadow-color); + -moz-box-shadow: 0 1px 3px var(--mocha-box-shadow-color); + box-shadow: 0 1px 3px var(--mocha-box-shadow-color); -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; @@ -217,7 +283,7 @@ body { height: 15px; line-height: 15px; text-align: center; - background: #eee; + background: var(--mocha-test-replay-bg-color); font-size: 15px; -webkit-border-radius: 15px; -moz-border-radius: 15px; @@ -226,11 +292,12 @@ body { -moz-transition:opacity 200ms; -o-transition:opacity 200ms; transition: opacity 200ms; - opacity: 0.3; - color: #888; + opacity: 0.7; + color: var(--mocha-test-replay-color); } #mocha .test:hover a.replay { + box-shadow: 0 0 1px inset var(--mocha-test-replay-color); opacity: 1; } @@ -251,7 +318,7 @@ body { } #mocha-error { - color: #c00; + color: var(--mocha-error-color); font-size: 1.5em; font-weight: 100; letter-spacing: 1px; @@ -263,7 +330,7 @@ body { right: 10px; font-size: 12px; margin: 0; - color: #888; + color: var(--mocha-stats-color); z-index: 1; } @@ -284,7 +351,7 @@ body { } #mocha-stats em { - color: black; + color: var(--mocha-stats-em-color); } #mocha-stats a { @@ -293,7 +360,7 @@ body { } #mocha-stats a:hover { - border-bottom: 1px solid #eee; + border-bottom: 1px solid var(--mocha-stats-hover-color); } #mocha-stats li { @@ -308,11 +375,11 @@ body { height: 40px; } -#mocha code .comment { color: #ddd; } -#mocha code .init { color: #2f6fad; } -#mocha code .string { color: #5890ad; } -#mocha code .keyword { color: #8a6343; } -#mocha code .number { color: #2f6fad; } +#mocha code .comment { color: var(--mocha-code-comment); } +#mocha code .init { color: var(--mocha-code-init); } +#mocha code .string { color: var(--mocha-code-string); } +#mocha code .keyword { color: var(--mocha-code-keyword); } +#mocha code .number { color: var(--mocha-code-number); } @media screen and (max-device-width: 480px) { #mocha { diff --git a/node_modules/mocha/mocha.js b/node_modules/mocha/mocha.js index 53ac33e..c3e0c12 100644 --- a/node_modules/mocha/mocha.js +++ b/node_modules/mocha/mocha.js @@ -1,30114 +1,20678 @@ +// mocha@10.4.0 in javascript ES2018 (function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mocha = factory()); -}(this, (function () { 'use strict'; - - var regeneratorRuntime; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - function createCommonjsModule(fn, basedir, module) { - return module = { - path: basedir, - exports: {}, - require: function (path, base) { - return commonjsRequire(path, (base === undefined || base === null) ? module.path : base); - } - }, fn(module, module.exports), module.exports; - } - - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } - - function commonjsRequire () { - throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs'); - } - - var check = function (it) { - return it && it.Math == Math && it; - }; - - // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 - var global_1 = - // eslint-disable-next-line no-undef - check(typeof globalThis == 'object' && globalThis) || - check(typeof window == 'object' && window) || - check(typeof self == 'object' && self) || - check(typeof commonjsGlobal == 'object' && commonjsGlobal) || - // eslint-disable-next-line no-new-func - (function () { return this; })() || Function('return this')(); - - var fails = function (exec) { - try { - return !!exec(); - } catch (error) { - return true; - } - }; - - // Detect IE8's incomplete defineProperty implementation - var descriptors = !fails(function () { - return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7; - }); - - var nativePropertyIsEnumerable = {}.propertyIsEnumerable; - var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - - // Nashorn ~ JDK8 bug - var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1); - - // `Object.prototype.propertyIsEnumerable` method implementation - // https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable - var f = NASHORN_BUG ? function propertyIsEnumerable(V) { - var descriptor = getOwnPropertyDescriptor(this, V); - return !!descriptor && descriptor.enumerable; - } : nativePropertyIsEnumerable; - - var objectPropertyIsEnumerable = { - f: f - }; - - var createPropertyDescriptor = function (bitmap, value) { - return { - enumerable: !(bitmap & 1), - configurable: !(bitmap & 2), - writable: !(bitmap & 4), - value: value - }; - }; - - var toString = {}.toString; - - var classofRaw = function (it) { - return toString.call(it).slice(8, -1); - }; - - var split = ''.split; - - // fallback for non-array-like ES3 and non-enumerable old V8 strings - var indexedObject = fails(function () { - // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346 - // eslint-disable-next-line no-prototype-builtins - return !Object('z').propertyIsEnumerable(0); - }) ? function (it) { - return classofRaw(it) == 'String' ? split.call(it, '') : Object(it); - } : Object; - - // `RequireObjectCoercible` abstract operation - // https://tc39.es/ecma262/#sec-requireobjectcoercible - var requireObjectCoercible = function (it) { - if (it == undefined) throw TypeError("Can't call method on " + it); - return it; - }; - - // toObject with fallback for non-array-like ES3 strings - - - - var toIndexedObject = function (it) { - return indexedObject(requireObjectCoercible(it)); - }; - - var isObject = function (it) { - return typeof it === 'object' ? it !== null : typeof it === 'function'; - }; - - // `ToPrimitive` abstract operation - // https://tc39.es/ecma262/#sec-toprimitive - // instead of the ES6 spec version, we didn't implement @@toPrimitive case - // and the second argument - flag - preferred type is a string - var toPrimitive = function (input, PREFERRED_STRING) { - if (!isObject(input)) return input; - var fn, val; - if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; - if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val; - if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val; - throw TypeError("Can't convert object to primitive value"); - }; - - var hasOwnProperty = {}.hasOwnProperty; - - var has = function (it, key) { - return hasOwnProperty.call(it, key); - }; - - var document$1 = global_1.document; - // typeof document.createElement is 'object' in old IE - var EXISTS = isObject(document$1) && isObject(document$1.createElement); - - var documentCreateElement = function (it) { - return EXISTS ? document$1.createElement(it) : {}; - }; - - // Thank's IE8 for his funny defineProperty - var ie8DomDefine = !descriptors && !fails(function () { - return Object.defineProperty(documentCreateElement('div'), 'a', { - get: function () { return 7; } - }).a != 7; - }); - - var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; - - // `Object.getOwnPropertyDescriptor` method - // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor - var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) { - O = toIndexedObject(O); - P = toPrimitive(P, true); - if (ie8DomDefine) try { - return nativeGetOwnPropertyDescriptor(O, P); - } catch (error) { /* empty */ } - if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]); - }; - - var objectGetOwnPropertyDescriptor = { - f: f$1 - }; - - var anObject = function (it) { - if (!isObject(it)) { - throw TypeError(String(it) + ' is not an object'); - } return it; - }; - - var nativeDefineProperty = Object.defineProperty; - - // `Object.defineProperty` method - // https://tc39.es/ecma262/#sec-object.defineproperty - var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) { - anObject(O); - P = toPrimitive(P, true); - anObject(Attributes); - if (ie8DomDefine) try { - return nativeDefineProperty(O, P, Attributes); - } catch (error) { /* empty */ } - if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported'); - if ('value' in Attributes) O[P] = Attributes.value; - return O; - }; - - var objectDefineProperty = { - f: f$2 - }; - - var createNonEnumerableProperty = descriptors ? function (object, key, value) { - return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value)); - } : function (object, key, value) { - object[key] = value; - return object; - }; - - var setGlobal = function (key, value) { - try { - createNonEnumerableProperty(global_1, key, value); - } catch (error) { - global_1[key] = value; - } return value; - }; - - var SHARED = '__core-js_shared__'; - var store = global_1[SHARED] || setGlobal(SHARED, {}); - - var sharedStore = store; - - var functionToString = Function.toString; - - // this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper - if (typeof sharedStore.inspectSource != 'function') { - sharedStore.inspectSource = function (it) { - return functionToString.call(it); - }; - } - - var inspectSource = sharedStore.inspectSource; - - var WeakMap = global_1.WeakMap; - - var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap)); - - var shared = createCommonjsModule(function (module) { - (module.exports = function (key, value) { - return sharedStore[key] || (sharedStore[key] = value !== undefined ? value : {}); - })('versions', []).push({ - version: '3.8.3', - mode: 'global', - copyright: '© 2021 Denis Pushkarev (zloirock.ru)' - }); - }); - - var id = 0; - var postfix = Math.random(); - - var uid = function (key) { - return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); - }; - - var keys = shared('keys'); - - var sharedKey = function (key) { - return keys[key] || (keys[key] = uid(key)); - }; - - var hiddenKeys = {}; - - var WeakMap$1 = global_1.WeakMap; - var set, get, has$1; - - var enforce = function (it) { - return has$1(it) ? get(it) : set(it, {}); - }; - - var getterFor = function (TYPE) { - return function (it) { - var state; - if (!isObject(it) || (state = get(it)).type !== TYPE) { - throw TypeError('Incompatible receiver, ' + TYPE + ' required'); - } return state; - }; - }; - - if (nativeWeakMap) { - var store$1 = sharedStore.state || (sharedStore.state = new WeakMap$1()); - var wmget = store$1.get; - var wmhas = store$1.has; - var wmset = store$1.set; - set = function (it, metadata) { - metadata.facade = it; - wmset.call(store$1, it, metadata); - return metadata; - }; - get = function (it) { - return wmget.call(store$1, it) || {}; - }; - has$1 = function (it) { - return wmhas.call(store$1, it); - }; - } else { - var STATE = sharedKey('state'); - hiddenKeys[STATE] = true; - set = function (it, metadata) { - metadata.facade = it; - createNonEnumerableProperty(it, STATE, metadata); - return metadata; - }; - get = function (it) { - return has(it, STATE) ? it[STATE] : {}; - }; - has$1 = function (it) { - return has(it, STATE); - }; - } - - var internalState = { - set: set, - get: get, - has: has$1, - enforce: enforce, - getterFor: getterFor - }; - - var redefine = createCommonjsModule(function (module) { - var getInternalState = internalState.get; - var enforceInternalState = internalState.enforce; - var TEMPLATE = String(String).split('String'); - - (module.exports = function (O, key, value, options) { - var unsafe = options ? !!options.unsafe : false; - var simple = options ? !!options.enumerable : false; - var noTargetGet = options ? !!options.noTargetGet : false; - var state; - if (typeof value == 'function') { - if (typeof key == 'string' && !has(value, 'name')) { - createNonEnumerableProperty(value, 'name', key); - } - state = enforceInternalState(value); - if (!state.source) { - state.source = TEMPLATE.join(typeof key == 'string' ? key : ''); - } - } - if (O === global_1) { - if (simple) O[key] = value; - else setGlobal(key, value); - return; - } else if (!unsafe) { - delete O[key]; - } else if (!noTargetGet && O[key]) { - simple = true; - } - if (simple) O[key] = value; - else createNonEnumerableProperty(O, key, value); - // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative - })(Function.prototype, 'toString', function toString() { - return typeof this == 'function' && getInternalState(this).source || inspectSource(this); - }); - }); - - var path = global_1; - - var aFunction = function (variable) { - return typeof variable == 'function' ? variable : undefined; - }; - - var getBuiltIn = function (namespace, method) { - return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace]) - : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method]; - }; - - var ceil = Math.ceil; - var floor = Math.floor; - - // `ToInteger` abstract operation - // https://tc39.es/ecma262/#sec-tointeger - var toInteger = function (argument) { - return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument); - }; - - var min = Math.min; - - // `ToLength` abstract operation - // https://tc39.es/ecma262/#sec-tolength - var toLength = function (argument) { - return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991 - }; - - var max = Math.max; - var min$1 = Math.min; - - // Helper for a popular repeating case of the spec: - // Let integer be ? ToInteger(index). - // If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length). - var toAbsoluteIndex = function (index, length) { - var integer = toInteger(index); - return integer < 0 ? max(integer + length, 0) : min$1(integer, length); - }; - - // `Array.prototype.{ indexOf, includes }` methods implementation - var createMethod = function (IS_INCLUDES) { - return function ($this, el, fromIndex) { - var O = toIndexedObject($this); - var length = toLength(O.length); - var index = toAbsoluteIndex(fromIndex, length); - var value; - // Array#includes uses SameValueZero equality algorithm - // eslint-disable-next-line no-self-compare - if (IS_INCLUDES && el != el) while (length > index) { - value = O[index++]; - // eslint-disable-next-line no-self-compare - if (value != value) return true; - // Array#indexOf ignores holes, Array#includes - not - } else for (;length > index; index++) { - if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0; - } return !IS_INCLUDES && -1; - }; - }; - - var arrayIncludes = { - // `Array.prototype.includes` method - // https://tc39.es/ecma262/#sec-array.prototype.includes - includes: createMethod(true), - // `Array.prototype.indexOf` method - // https://tc39.es/ecma262/#sec-array.prototype.indexof - indexOf: createMethod(false) - }; - - var indexOf = arrayIncludes.indexOf; - - - var objectKeysInternal = function (object, names) { - var O = toIndexedObject(object); - var i = 0; - var result = []; - var key; - for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key); - // Don't enum bug & hidden keys - while (names.length > i) if (has(O, key = names[i++])) { - ~indexOf(result, key) || result.push(key); - } - return result; - }; - - // IE8- don't enum bug keys - var enumBugKeys = [ - 'constructor', - 'hasOwnProperty', - 'isPrototypeOf', - 'propertyIsEnumerable', - 'toLocaleString', - 'toString', - 'valueOf' - ]; - - var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype'); - - // `Object.getOwnPropertyNames` method - // https://tc39.es/ecma262/#sec-object.getownpropertynames - var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) { - return objectKeysInternal(O, hiddenKeys$1); - }; - - var objectGetOwnPropertyNames = { - f: f$3 - }; - - var f$4 = Object.getOwnPropertySymbols; - - var objectGetOwnPropertySymbols = { - f: f$4 - }; - - // all object keys, includes non-enumerable and symbols - var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) { - var keys = objectGetOwnPropertyNames.f(anObject(it)); - var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; - return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys; - }; - - var copyConstructorProperties = function (target, source) { - var keys = ownKeys(source); - var defineProperty = objectDefineProperty.f; - var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key)); - } - }; - - var replacement = /#|\.prototype\./; - - var isForced = function (feature, detection) { - var value = data[normalize(feature)]; - return value == POLYFILL ? true - : value == NATIVE ? false - : typeof detection == 'function' ? fails(detection) - : !!detection; - }; - - var normalize = isForced.normalize = function (string) { - return String(string).replace(replacement, '.').toLowerCase(); - }; - - var data = isForced.data = {}; - var NATIVE = isForced.NATIVE = 'N'; - var POLYFILL = isForced.POLYFILL = 'P'; - - var isForced_1 = isForced; - - var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; - - - - - - - /* - options.target - name of the target object - options.global - target is the global object - options.stat - export as static methods of target - options.proto - export as prototype methods of target - options.real - real prototype method for the `pure` version - options.forced - export even if the native feature is available - options.bind - bind methods to the target, required for the `pure` version - options.wrap - wrap constructors to preventing global pollution, required for the `pure` version - options.unsafe - use the simple assignment of property instead of delete + defineProperty - options.sham - add a flag to not completely full polyfills - options.enumerable - export as enumerable property - options.noTargetGet - prevent calling a getter on target - */ - var _export = function (options, source) { - var TARGET = options.target; - var GLOBAL = options.global; - var STATIC = options.stat; - var FORCED, target, key, targetProperty, sourceProperty, descriptor; - if (GLOBAL) { - target = global_1; - } else if (STATIC) { - target = global_1[TARGET] || setGlobal(TARGET, {}); - } else { - target = (global_1[TARGET] || {}).prototype; - } - if (target) for (key in source) { - sourceProperty = source[key]; - if (options.noTargetGet) { - descriptor = getOwnPropertyDescriptor$1(target, key); - targetProperty = descriptor && descriptor.value; - } else targetProperty = target[key]; - FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced); - // contained in target - if (!FORCED && targetProperty !== undefined) { - if (typeof sourceProperty === typeof targetProperty) continue; - copyConstructorProperties(sourceProperty, targetProperty); - } - // add a flag to not completely full polyfills - if (options.sham || (targetProperty && targetProperty.sham)) { - createNonEnumerableProperty(sourceProperty, 'sham', true); - } - // extend global - redefine(target, key, sourceProperty, options); - } - }; - - var aFunction$1 = function (it) { - if (typeof it != 'function') { - throw TypeError(String(it) + ' is not a function'); - } return it; - }; - - // optional / simple context binding - var functionBindContext = function (fn, that, length) { - aFunction$1(fn); - if (that === undefined) return fn; - switch (length) { - case 0: return function () { - return fn.call(that); - }; - case 1: return function (a) { - return fn.call(that, a); - }; - case 2: return function (a, b) { - return fn.call(that, a, b); - }; - case 3: return function (a, b, c) { - return fn.call(that, a, b, c); - }; - } - return function (/* ...args */) { - return fn.apply(that, arguments); - }; - }; - - // `ToObject` abstract operation - // https://tc39.es/ecma262/#sec-toobject - var toObject = function (argument) { - return Object(requireObjectCoercible(argument)); - }; - - // `IsArray` abstract operation - // https://tc39.es/ecma262/#sec-isarray - var isArray = Array.isArray || function isArray(arg) { - return classofRaw(arg) == 'Array'; - }; - - var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () { - // Chrome 38 Symbol has incorrect toString conversion - // eslint-disable-next-line no-undef - return !String(Symbol()); - }); - - var useSymbolAsUid = nativeSymbol - // eslint-disable-next-line no-undef - && !Symbol.sham - // eslint-disable-next-line no-undef - && typeof Symbol.iterator == 'symbol'; - - var WellKnownSymbolsStore = shared('wks'); - var Symbol$1 = global_1.Symbol; - var createWellKnownSymbol = useSymbolAsUid ? Symbol$1 : Symbol$1 && Symbol$1.withoutSetter || uid; - - var wellKnownSymbol = function (name) { - if (!has(WellKnownSymbolsStore, name)) { - if (nativeSymbol && has(Symbol$1, name)) WellKnownSymbolsStore[name] = Symbol$1[name]; - else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name); - } return WellKnownSymbolsStore[name]; - }; - - var SPECIES = wellKnownSymbol('species'); - - // `ArraySpeciesCreate` abstract operation - // https://tc39.es/ecma262/#sec-arrayspeciescreate - var arraySpeciesCreate = function (originalArray, length) { - var C; - if (isArray(originalArray)) { - C = originalArray.constructor; - // cross-realm fallback - if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined; - else if (isObject(C)) { - C = C[SPECIES]; - if (C === null) C = undefined; - } - } return new (C === undefined ? Array : C)(length === 0 ? 0 : length); - }; - - var push = [].push; - - // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterOut }` methods implementation - var createMethod$1 = function (TYPE) { - var IS_MAP = TYPE == 1; - var IS_FILTER = TYPE == 2; - var IS_SOME = TYPE == 3; - var IS_EVERY = TYPE == 4; - var IS_FIND_INDEX = TYPE == 6; - var IS_FILTER_OUT = TYPE == 7; - var NO_HOLES = TYPE == 5 || IS_FIND_INDEX; - return function ($this, callbackfn, that, specificCreate) { - var O = toObject($this); - var self = indexedObject(O); - var boundFunction = functionBindContext(callbackfn, that, 3); - var length = toLength(self.length); - var index = 0; - var create = specificCreate || arraySpeciesCreate; - var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_OUT ? create($this, 0) : undefined; - var value, result; - for (;length > index; index++) if (NO_HOLES || index in self) { - value = self[index]; - result = boundFunction(value, index, O); - if (TYPE) { - if (IS_MAP) target[index] = result; // map - else if (result) switch (TYPE) { - case 3: return true; // some - case 5: return value; // find - case 6: return index; // findIndex - case 2: push.call(target, value); // filter - } else switch (TYPE) { - case 4: return false; // every - case 7: push.call(target, value); // filterOut - } - } - } - return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target; - }; - }; - - var arrayIteration = { - // `Array.prototype.forEach` method - // https://tc39.es/ecma262/#sec-array.prototype.foreach - forEach: createMethod$1(0), - // `Array.prototype.map` method - // https://tc39.es/ecma262/#sec-array.prototype.map - map: createMethod$1(1), - // `Array.prototype.filter` method - // https://tc39.es/ecma262/#sec-array.prototype.filter - filter: createMethod$1(2), - // `Array.prototype.some` method - // https://tc39.es/ecma262/#sec-array.prototype.some - some: createMethod$1(3), - // `Array.prototype.every` method - // https://tc39.es/ecma262/#sec-array.prototype.every - every: createMethod$1(4), - // `Array.prototype.find` method - // https://tc39.es/ecma262/#sec-array.prototype.find - find: createMethod$1(5), - // `Array.prototype.findIndex` method - // https://tc39.es/ecma262/#sec-array.prototype.findIndex - findIndex: createMethod$1(6), - // `Array.prototype.filterOut` method - // https://github.com/tc39/proposal-array-filtering - filterOut: createMethod$1(7) - }; - - var engineUserAgent = getBuiltIn('navigator', 'userAgent') || ''; - - var process = global_1.process; - var versions = process && process.versions; - var v8 = versions && versions.v8; - var match, version; - - if (v8) { - match = v8.split('.'); - version = match[0] + match[1]; - } else if (engineUserAgent) { - match = engineUserAgent.match(/Edge\/(\d+)/); - if (!match || match[1] >= 74) { - match = engineUserAgent.match(/Chrome\/(\d+)/); - if (match) version = match[1]; - } - } - - var engineV8Version = version && +version; - - var SPECIES$1 = wellKnownSymbol('species'); - - var arrayMethodHasSpeciesSupport = function (METHOD_NAME) { - // We can't use this feature detection in V8 since it causes - // deoptimization and serious performance degradation - // https://github.com/zloirock/core-js/issues/677 - return engineV8Version >= 51 || !fails(function () { - var array = []; - var constructor = array.constructor = {}; - constructor[SPECIES$1] = function () { - return { foo: 1 }; - }; - return array[METHOD_NAME](Boolean).foo !== 1; - }); - }; - - var defineProperty = Object.defineProperty; - var cache = {}; - - var thrower = function (it) { throw it; }; - - var arrayMethodUsesToLength = function (METHOD_NAME, options) { - if (has(cache, METHOD_NAME)) return cache[METHOD_NAME]; - if (!options) options = {}; - var method = [][METHOD_NAME]; - var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false; - var argument0 = has(options, 0) ? options[0] : thrower; - var argument1 = has(options, 1) ? options[1] : undefined; - - return cache[METHOD_NAME] = !!method && !fails(function () { - if (ACCESSORS && !descriptors) return true; - var O = { length: -1 }; - - if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower }); - else O[1] = 1; - - method.call(O, argument0, argument1); - }); - }; - - var $filter = arrayIteration.filter; - - - - var HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter'); - // Edge 14- issue - var USES_TO_LENGTH = arrayMethodUsesToLength('filter'); - - // `Array.prototype.filter` method - // https://tc39.es/ecma262/#sec-array.prototype.filter - // with adding support of @@species - _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, { - filter: function filter(callbackfn /* , thisArg */) { - return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - var createProperty = function (object, key, value) { - var propertyKey = toPrimitive(key); - if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value)); - else object[propertyKey] = value; - }; - - var HAS_SPECIES_SUPPORT$1 = arrayMethodHasSpeciesSupport('splice'); - var USES_TO_LENGTH$1 = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 }); - - var max$1 = Math.max; - var min$2 = Math.min; - var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; - var MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded'; - - // `Array.prototype.splice` method - // https://tc39.es/ecma262/#sec-array.prototype.splice - // with adding support of @@species - _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$1 || !USES_TO_LENGTH$1 }, { - splice: function splice(start, deleteCount /* , ...items */) { - var O = toObject(this); - var len = toLength(O.length); - var actualStart = toAbsoluteIndex(start, len); - var argumentsLength = arguments.length; - var insertCount, actualDeleteCount, A, k, from, to; - if (argumentsLength === 0) { - insertCount = actualDeleteCount = 0; - } else if (argumentsLength === 1) { - insertCount = 0; - actualDeleteCount = len - actualStart; - } else { - insertCount = argumentsLength - 2; - actualDeleteCount = min$2(max$1(toInteger(deleteCount), 0), len - actualStart); - } - if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) { - throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED); - } - A = arraySpeciesCreate(O, actualDeleteCount); - for (k = 0; k < actualDeleteCount; k++) { - from = actualStart + k; - if (from in O) createProperty(A, k, O[from]); - } - A.length = actualDeleteCount; - if (insertCount < actualDeleteCount) { - for (k = actualStart; k < len - actualDeleteCount; k++) { - from = k + actualDeleteCount; - to = k + insertCount; - if (from in O) O[to] = O[from]; - else delete O[to]; - } - for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1]; - } else if (insertCount > actualDeleteCount) { - for (k = len - actualDeleteCount; k > actualStart; k--) { - from = k + actualDeleteCount - 1; - to = k + insertCount - 1; - if (from in O) O[to] = O[from]; - else delete O[to]; - } - } - for (k = 0; k < insertCount; k++) { - O[k + actualStart] = arguments[k + 2]; - } - O.length = len - actualDeleteCount + insertCount; - return A; - } - }); - - // `Object.keys` method - // https://tc39.es/ecma262/#sec-object.keys - var objectKeys = Object.keys || function keys(O) { - return objectKeysInternal(O, enumBugKeys); - }; - - var nativeAssign = Object.assign; - var defineProperty$1 = Object.defineProperty; - - // `Object.assign` method - // https://tc39.es/ecma262/#sec-object.assign - var objectAssign = !nativeAssign || fails(function () { - // should have correct order of operations (Edge bug) - if (descriptors && nativeAssign({ b: 1 }, nativeAssign(defineProperty$1({}, 'a', { - enumerable: true, - get: function () { - defineProperty$1(this, 'b', { - value: 3, - enumerable: false - }); - } - }), { b: 2 })).b !== 1) return true; - // should work with symbols and should have deterministic property order (V8 bug) - var A = {}; - var B = {}; - // eslint-disable-next-line no-undef - var symbol = Symbol(); - var alphabet = 'abcdefghijklmnopqrst'; - A[symbol] = 7; - alphabet.split('').forEach(function (chr) { B[chr] = chr; }); - return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet; - }) ? function assign(target, source) { // eslint-disable-line no-unused-vars - var T = toObject(target); - var argumentsLength = arguments.length; - var index = 1; - var getOwnPropertySymbols = objectGetOwnPropertySymbols.f; - var propertyIsEnumerable = objectPropertyIsEnumerable.f; - while (argumentsLength > index) { - var S = indexedObject(arguments[index++]); - var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S); - var length = keys.length; - var j = 0; - var key; - while (length > j) { - key = keys[j++]; - if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key]; - } - } return T; - } : nativeAssign; - - // `Object.assign` method - // https://tc39.es/ecma262/#sec-object.assign - _export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, { - assign: objectAssign - }); - - var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); }); - - // `Object.keys` method - // https://tc39.es/ecma262/#sec-object.keys - _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, { - keys: function keys(it) { - return objectKeys(toObject(it)); - } - }); - - // `RegExp.prototype.flags` getter implementation - // https://tc39.es/ecma262/#sec-get-regexp.prototype.flags - var regexpFlags = function () { - var that = anObject(this); - var result = ''; - if (that.global) result += 'g'; - if (that.ignoreCase) result += 'i'; - if (that.multiline) result += 'm'; - if (that.dotAll) result += 's'; - if (that.unicode) result += 'u'; - if (that.sticky) result += 'y'; - return result; - }; - - // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError, - // so we use an intermediate function. - function RE(s, f) { - return RegExp(s, f); - } - - var UNSUPPORTED_Y = fails(function () { - // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError - var re = RE('a', 'y'); - re.lastIndex = 2; - return re.exec('abcd') != null; - }); - - var BROKEN_CARET = fails(function () { - // https://bugzilla.mozilla.org/show_bug.cgi?id=773687 - var re = RE('^r', 'gy'); - re.lastIndex = 2; - return re.exec('str') != null; - }); - - var regexpStickyHelpers = { - UNSUPPORTED_Y: UNSUPPORTED_Y, - BROKEN_CARET: BROKEN_CARET - }; - - var nativeExec = RegExp.prototype.exec; - // This always refers to the native implementation, because the - // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js, - // which loads this file before patching the method. - var nativeReplace = String.prototype.replace; - - var patchedExec = nativeExec; - - var UPDATES_LAST_INDEX_WRONG = (function () { - var re1 = /a/; - var re2 = /b*/g; - nativeExec.call(re1, 'a'); - nativeExec.call(re2, 'a'); - return re1.lastIndex !== 0 || re2.lastIndex !== 0; - })(); - - var UNSUPPORTED_Y$1 = regexpStickyHelpers.UNSUPPORTED_Y || regexpStickyHelpers.BROKEN_CARET; - - // nonparticipating capturing group, copied from es5-shim's String#split patch. - var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined; - - var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y$1; - - if (PATCH) { - patchedExec = function exec(str) { - var re = this; - var lastIndex, reCopy, match, i; - var sticky = UNSUPPORTED_Y$1 && re.sticky; - var flags = regexpFlags.call(re); - var source = re.source; - var charsAdded = 0; - var strCopy = str; - - if (sticky) { - flags = flags.replace('y', ''); - if (flags.indexOf('g') === -1) { - flags += 'g'; - } - - strCopy = String(str).slice(re.lastIndex); - // Support anchored sticky behavior. - if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\n')) { - source = '(?: ' + source + ')'; - strCopy = ' ' + strCopy; - charsAdded++; - } - // ^(? + rx + ) is needed, in combination with some str slicing, to - // simulate the 'y' flag. - reCopy = new RegExp('^(?:' + source + ')', flags); - } - - if (NPCG_INCLUDED) { - reCopy = new RegExp('^' + source + '$(?!\\s)', flags); - } - if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex; - - match = nativeExec.call(sticky ? reCopy : re, strCopy); - - if (sticky) { - if (match) { - match.input = match.input.slice(charsAdded); - match[0] = match[0].slice(charsAdded); - match.index = re.lastIndex; - re.lastIndex += match[0].length; - } else re.lastIndex = 0; - } else if (UPDATES_LAST_INDEX_WRONG && match) { - re.lastIndex = re.global ? match.index + match[0].length : lastIndex; - } - if (NPCG_INCLUDED && match && match.length > 1) { - // Fix browsers whose `exec` methods don't consistently return `undefined` - // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/ - nativeReplace.call(match[0], reCopy, function () { - for (i = 1; i < arguments.length - 2; i++) { - if (arguments[i] === undefined) match[i] = undefined; - } - }); - } - - return match; - }; - } - - var regexpExec = patchedExec; - - // `RegExp.prototype.exec` method - // https://tc39.es/ecma262/#sec-regexp.prototype.exec - _export({ target: 'RegExp', proto: true, forced: /./.exec !== regexpExec }, { - exec: regexpExec - }); - - // TODO: Remove from `core-js@4` since it's moved to entry points - - - - - - - - var SPECIES$2 = wellKnownSymbol('species'); - - var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () { - // #replace needs built-in support for named groups. - // #match works fine because it just return the exec results, even if it has - // a "grops" property. - var re = /./; - re.exec = function () { - var result = []; - result.groups = { a: '7' }; - return result; - }; - return ''.replace(re, '$') !== '7'; - }); - - // IE <= 11 replaces $0 with the whole match, as if it was $& - // https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0 - var REPLACE_KEEPS_$0 = (function () { - return 'a'.replace(/./, '$0') === '$0'; - })(); - - var REPLACE = wellKnownSymbol('replace'); - // Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string - var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () { - if (/./[REPLACE]) { - return /./[REPLACE]('a', '$0') === ''; - } - return false; - })(); - - // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec - // Weex JS has frozen built-in prototypes, so use try / catch wrapper - var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () { - var re = /(?:)/; - var originalExec = re.exec; - re.exec = function () { return originalExec.apply(this, arguments); }; - var result = 'ab'.split(re); - return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b'; - }); - - var fixRegexpWellKnownSymbolLogic = function (KEY, length, exec, sham) { - var SYMBOL = wellKnownSymbol(KEY); - - var DELEGATES_TO_SYMBOL = !fails(function () { - // String methods call symbol-named RegEp methods - var O = {}; - O[SYMBOL] = function () { return 7; }; - return ''[KEY](O) != 7; - }); - - var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () { - // Symbol-named RegExp methods call .exec - var execCalled = false; - var re = /a/; - - if (KEY === 'split') { - // We can't use real regex here since it causes deoptimization - // and serious performance degradation in V8 - // https://github.com/zloirock/core-js/issues/306 - re = {}; - // RegExp[@@split] doesn't call the regex's exec method, but first creates - // a new one. We need to return the patched regex when creating the new one. - re.constructor = {}; - re.constructor[SPECIES$2] = function () { return re; }; - re.flags = ''; - re[SYMBOL] = /./[SYMBOL]; - } - - re.exec = function () { execCalled = true; return null; }; - - re[SYMBOL](''); - return !execCalled; - }); - - if ( - !DELEGATES_TO_SYMBOL || - !DELEGATES_TO_EXEC || - (KEY === 'replace' && !( - REPLACE_SUPPORTS_NAMED_GROUPS && - REPLACE_KEEPS_$0 && - !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE - )) || - (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC) - ) { - var nativeRegExpMethod = /./[SYMBOL]; - var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) { - if (regexp.exec === regexpExec) { - if (DELEGATES_TO_SYMBOL && !forceStringMethod) { - // The native String method already delegates to @@method (this - // polyfilled function), leasing to infinite recursion. - // We avoid it by directly calling the native @@method method. - return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) }; - } - return { done: true, value: nativeMethod.call(str, regexp, arg2) }; - } - return { done: false }; - }, { - REPLACE_KEEPS_$0: REPLACE_KEEPS_$0, - REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE - }); - var stringMethod = methods[0]; - var regexMethod = methods[1]; - - redefine(String.prototype, KEY, stringMethod); - redefine(RegExp.prototype, SYMBOL, length == 2 - // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) - // 21.2.5.11 RegExp.prototype[@@split](string, limit) - ? function (string, arg) { return regexMethod.call(string, this, arg); } - // 21.2.5.6 RegExp.prototype[@@match](string) - // 21.2.5.9 RegExp.prototype[@@search](string) - : function (string) { return regexMethod.call(string, this); } - ); - } - - if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true); - }; - - // `SameValue` abstract operation - // https://tc39.es/ecma262/#sec-samevalue - var sameValue = Object.is || function is(x, y) { - // eslint-disable-next-line no-self-compare - return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; - }; - - // `RegExpExec` abstract operation - // https://tc39.es/ecma262/#sec-regexpexec - var regexpExecAbstract = function (R, S) { - var exec = R.exec; - if (typeof exec === 'function') { - var result = exec.call(R, S); - if (typeof result !== 'object') { - throw TypeError('RegExp exec method returned something other than an Object or null'); - } - return result; - } - - if (classofRaw(R) !== 'RegExp') { - throw TypeError('RegExp#exec called on incompatible receiver'); - } - - return regexpExec.call(R, S); - }; - - // @@search logic - fixRegexpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) { - return [ - // `String.prototype.search` method - // https://tc39.es/ecma262/#sec-string.prototype.search - function search(regexp) { - var O = requireObjectCoercible(this); - var searcher = regexp == undefined ? undefined : regexp[SEARCH]; - return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); - }, - // `RegExp.prototype[@@search]` method - // https://tc39.es/ecma262/#sec-regexp.prototype-@@search - function (regexp) { - var res = maybeCallNative(nativeSearch, regexp, this); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - - var previousLastIndex = rx.lastIndex; - if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0; - var result = regexpExecAbstract(rx, S); - if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex; - return result === null ? -1 : result.index; - } - ]; - }); - - // iterable DOM collections - // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods - var domIterables = { - CSSRuleList: 0, - CSSStyleDeclaration: 0, - CSSValueList: 0, - ClientRectList: 0, - DOMRectList: 0, - DOMStringList: 0, - DOMTokenList: 1, - DataTransferItemList: 0, - FileList: 0, - HTMLAllCollection: 0, - HTMLCollection: 0, - HTMLFormElement: 0, - HTMLSelectElement: 0, - MediaList: 0, - MimeTypeArray: 0, - NamedNodeMap: 0, - NodeList: 1, - PaintRequestList: 0, - Plugin: 0, - PluginArray: 0, - SVGLengthList: 0, - SVGNumberList: 0, - SVGPathSegList: 0, - SVGPointList: 0, - SVGStringList: 0, - SVGTransformList: 0, - SourceBufferList: 0, - StyleSheetList: 0, - TextTrackCueList: 0, - TextTrackList: 0, - TouchList: 0 - }; - - var arrayMethodIsStrict = function (METHOD_NAME, argument) { - var method = [][METHOD_NAME]; - return !!method && fails(function () { - // eslint-disable-next-line no-useless-call,no-throw-literal - method.call(null, argument || function () { throw 1; }, 1); - }); - }; - - var $forEach = arrayIteration.forEach; - - - - var STRICT_METHOD = arrayMethodIsStrict('forEach'); - var USES_TO_LENGTH$2 = arrayMethodUsesToLength('forEach'); - - // `Array.prototype.forEach` method implementation - // https://tc39.es/ecma262/#sec-array.prototype.foreach - var arrayForEach = (!STRICT_METHOD || !USES_TO_LENGTH$2) ? function forEach(callbackfn /* , thisArg */) { - return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } : [].forEach; - - for (var COLLECTION_NAME in domIterables) { - var Collection = global_1[COLLECTION_NAME]; - var CollectionPrototype = Collection && Collection.prototype; - // some Chrome versions have non-configurable methods on DOMTokenList - if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try { - createNonEnumerableProperty(CollectionPrototype, 'forEach', arrayForEach); - } catch (error) { - CollectionPrototype.forEach = arrayForEach; - } - } - - var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable'); - var MAX_SAFE_INTEGER$1 = 0x1FFFFFFFFFFFFF; - var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded'; - - // We can't use this feature detection in V8 since it causes - // deoptimization and serious performance degradation - // https://github.com/zloirock/core-js/issues/679 - var IS_CONCAT_SPREADABLE_SUPPORT = engineV8Version >= 51 || !fails(function () { - var array = []; - array[IS_CONCAT_SPREADABLE] = false; - return array.concat()[0] !== array; - }); - - var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat'); - - var isConcatSpreadable = function (O) { - if (!isObject(O)) return false; - var spreadable = O[IS_CONCAT_SPREADABLE]; - return spreadable !== undefined ? !!spreadable : isArray(O); - }; - - var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT; - - // `Array.prototype.concat` method - // https://tc39.es/ecma262/#sec-array.prototype.concat - // with adding support of @@isConcatSpreadable and @@species - _export({ target: 'Array', proto: true, forced: FORCED }, { - concat: function concat(arg) { // eslint-disable-line no-unused-vars - var O = toObject(this); - var A = arraySpeciesCreate(O, 0); - var n = 0; - var i, k, length, len, E; - for (i = -1, length = arguments.length; i < length; i++) { - E = i === -1 ? O : arguments[i]; - if (isConcatSpreadable(E)) { - len = toLength(E.length); - if (n + len > MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); - for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]); - } else { - if (n >= MAX_SAFE_INTEGER$1) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED); - createProperty(A, n++, E); - } - } - A.length = n; - return A; - } - }); - - var global$1 = typeof global$2 !== "undefined" ? global$2 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; - - var global$2 = typeof global$1 !== "undefined" ? global$1 : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}; - - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - - function defaultClearTimeout() { - throw new Error('clearTimeout has not been defined'); - } - - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - - if (typeof global$2.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - - if (typeof global$2.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } - - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } // if setTimeout wasn't available but was latter defined - - - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - } - - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } // if clearTimeout wasn't available but was latter defined - - - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - } - - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - - draining = false; - - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - - if (queue.length) { - drainQueue(); - } - } - - function drainQueue() { - if (draining) { - return; - } - - var timeout = runTimeout(cleanUpNextTick); - draining = true; - var len = queue.length; - - while (len) { - currentQueue = queue; - queue = []; - - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - - queueIndex = -1; - len = queue.length; - } - - currentQueue = null; - draining = false; - runClearTimeout(timeout); - } - - function nextTick(fun) { - var args = new Array(arguments.length - 1); - - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - - queue.push(new Item(fun, args)); - - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } - } // v8 likes predictible objects - - function Item(fun, array) { - this.fun = fun; - this.array = array; - } - - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - - var title = 'browser'; - var platform = 'browser'; - var browser = true; - var env = {}; - var argv = []; - var version$1 = ''; // empty string to avoid regexp issues - - var versions$1 = {}; - var release = {}; - var config = {}; - - function noop() {} - - var on = noop; - var addListener = noop; - var once = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; - function binding(name) { - throw new Error('process.binding is not supported'); - } - function cwd() { - return '/'; - } - function chdir(dir) { - throw new Error('process.chdir is not supported'); - } - function umask() { - return 0; - } // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - - var performance = global$2.performance || {}; - - var performanceNow = performance.now || performance.mozNow || performance.msNow || performance.oNow || performance.webkitNow || function () { - return new Date().getTime(); - }; // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - - - function hrtime(previousTimestamp) { - var clocktime = performanceNow.call(performance) * 1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor(clocktime % 1 * 1e9); - - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - - if (nanoseconds < 0) { - seconds--; - nanoseconds += 1e9; - } - } - - return [seconds, nanoseconds]; - } - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; - } - var process$1 = { - nextTick: nextTick, - title: title, - browser: browser, - env: env, - argv: argv, - version: version$1, - versions: versions$1, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; - - var TO_STRING_TAG = wellKnownSymbol('toStringTag'); - var test = {}; - - test[TO_STRING_TAG] = 'z'; - - var toStringTagSupport = String(test) === '[object z]'; - - var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag'); - // ES3 wrong here - var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments'; - - // fallback for IE11 Script Access Denied error - var tryGet = function (it, key) { - try { - return it[key]; - } catch (error) { /* empty */ } - }; - - // getting tag from ES6+ `Object.prototype.toString` - var classof = toStringTagSupport ? classofRaw : function (it) { - var O, tag, result; - return it === undefined ? 'Undefined' : it === null ? 'Null' - // @@toStringTag case - : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$1)) == 'string' ? tag - // builtinTag case - : CORRECT_ARGUMENTS ? classofRaw(O) - // ES3 arguments fallback - : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result; - }; - - // `Object.prototype.toString` method implementation - // https://tc39.es/ecma262/#sec-object.prototype.tostring - var objectToString = toStringTagSupport ? {}.toString : function toString() { - return '[object ' + classof(this) + ']'; - }; - - // `Object.prototype.toString` method - // https://tc39.es/ecma262/#sec-object.prototype.tostring - if (!toStringTagSupport) { - redefine(Object.prototype, 'toString', objectToString, { unsafe: true }); - } - - var TO_STRING = 'toString'; - var RegExpPrototype = RegExp.prototype; - var nativeToString = RegExpPrototype[TO_STRING]; - - var NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; }); - // FF44- RegExp#toString has a wrong name - var INCORRECT_NAME = nativeToString.name != TO_STRING; - - // `RegExp.prototype.toString` method - // https://tc39.es/ecma262/#sec-regexp.prototype.tostring - if (NOT_GENERIC || INCORRECT_NAME) { - redefine(RegExp.prototype, TO_STRING, function toString() { - var R = anObject(this); - var p = String(R.source); - var rf = R.flags; - var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? regexpFlags.call(R) : rf); - return '/' + p + '/' + f; - }, { unsafe: true }); - } - - var defineProperty$2 = objectDefineProperty.f; - - var FunctionPrototype = Function.prototype; - var FunctionPrototypeToString = FunctionPrototype.toString; - var nameRE = /^\s*function ([^ (]*)/; - var NAME = 'name'; - - // Function instances `.name` property - // https://tc39.es/ecma262/#sec-function-instances-name - if (descriptors && !(NAME in FunctionPrototype)) { - defineProperty$2(FunctionPrototype, NAME, { - configurable: true, - get: function () { - try { - return FunctionPrototypeToString.call(this).match(nameRE)[1]; - } catch (error) { - return ''; - } - } - }); - } - - var correctPrototypeGetter = !fails(function () { - function F() { /* empty */ } - F.prototype.constructor = null; - return Object.getPrototypeOf(new F()) !== F.prototype; - }); - - var IE_PROTO = sharedKey('IE_PROTO'); - var ObjectPrototype = Object.prototype; - - // `Object.getPrototypeOf` method - // https://tc39.es/ecma262/#sec-object.getprototypeof - var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) { - O = toObject(O); - if (has(O, IE_PROTO)) return O[IE_PROTO]; - if (typeof O.constructor == 'function' && O instanceof O.constructor) { - return O.constructor.prototype; - } return O instanceof Object ? ObjectPrototype : null; - }; - - var FAILS_ON_PRIMITIVES$1 = fails(function () { objectGetPrototypeOf(1); }); - - // `Object.getPrototypeOf` method - // https://tc39.es/ecma262/#sec-object.getprototypeof - _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$1, sham: !correctPrototypeGetter }, { - getPrototypeOf: function getPrototypeOf(it) { - return objectGetPrototypeOf(toObject(it)); - } - }); - - // `Reflect.ownKeys` method - // https://tc39.es/ecma262/#sec-reflect.ownkeys - _export({ target: 'Reflect', stat: true }, { - ownKeys: ownKeys - }); - - var domain; // This constructor is used to store event handlers. Instantiating this is - // faster than explicitly calling `Object.create(null)` to get a "clean" empty - // object (tested with v8 v4.9). - - function EventHandlers() {} - - EventHandlers.prototype = Object.create(null); - - function EventEmitter() { - EventEmitter.init.call(this); - } - // require('events') === require('events').EventEmitter - - EventEmitter.EventEmitter = EventEmitter; - EventEmitter.usingDomains = false; - EventEmitter.prototype.domain = undefined; - EventEmitter.prototype._events = undefined; - EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are - // added to it. This is a useful default which helps finding memory leaks. - - EventEmitter.defaultMaxListeners = 10; - - EventEmitter.init = function () { - this.domain = null; - - if (EventEmitter.usingDomains) { - // if there is an active domain, then attach to it. - if (domain.active ) ; - } - - if (!this._events || this._events === Object.getPrototypeOf(this)._events) { - this._events = new EventHandlers(); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; - }; // Obviously not all Emitters should be limited to 10. This function allows - // that to be increased. Set to zero for unlimited. - - - EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || isNaN(n)) throw new TypeError('"n" argument must be a positive number'); - this._maxListeners = n; - return this; - }; - - function $getMaxListeners(that) { - if (that._maxListeners === undefined) return EventEmitter.defaultMaxListeners; - return that._maxListeners; - } - - EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); - }; // These standalone emit* functions are used to optimize calling of event - // handlers for fast cases because emit() itself often has a variable number of - // arguments and can be deoptimized because of that. These functions always have - // the same number of arguments and thus do not get deoptimized, so the code - // inside them can execute faster. - - - function emitNone(handler, isFn, self) { - if (isFn) handler.call(self);else { - var len = handler.length; - var listeners = arrayClone(handler, len); - - for (var i = 0; i < len; ++i) { - listeners[i].call(self); - } - } - } - - function emitOne(handler, isFn, self, arg1) { - if (isFn) handler.call(self, arg1);else { - var len = handler.length; - var listeners = arrayClone(handler, len); - - for (var i = 0; i < len; ++i) { - listeners[i].call(self, arg1); - } - } - } - - function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) handler.call(self, arg1, arg2);else { - var len = handler.length; - var listeners = arrayClone(handler, len); - - for (var i = 0; i < len; ++i) { - listeners[i].call(self, arg1, arg2); - } - } - } - - function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) handler.call(self, arg1, arg2, arg3);else { - var len = handler.length; - var listeners = arrayClone(handler, len); - - for (var i = 0; i < len; ++i) { - listeners[i].call(self, arg1, arg2, arg3); - } - } - } - - function emitMany(handler, isFn, self, args) { - if (isFn) handler.apply(self, args);else { - var len = handler.length; - var listeners = arrayClone(handler, len); - - for (var i = 0; i < len; ++i) { - listeners[i].apply(self, args); - } - } - } - - EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events, domain; - var doError = type === 'error'; - events = this._events; - if (events) doError = doError && events.error == null;else if (!doError) return false; - domain = this.domain; // If there is no 'error' event listener then throw. - - if (doError) { - er = arguments[1]; - - if (domain) { - if (!er) er = new Error('Uncaught, unspecified "error" event'); - er.domainEmitter = this; - er.domain = domain; - er.domainThrown = false; - domain.emit('error', er); - } else if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); - err.context = er; - throw err; - } - - return false; - } - - handler = events[type]; - if (!handler) return false; - var isFn = typeof handler === 'function'; - len = arguments.length; - - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - - default: - args = new Array(len - 1); - - for (i = 1; i < len; i++) { - args[i - 1] = arguments[i]; - } - - emitMany(handler, isFn, this, args); - } - return true; - }; - - function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); - events = target._events; - - if (!events) { - events = target._events = new EventHandlers(); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener) { - target.emit('newListener', type, listener.listener ? listener.listener : listener); // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - - events = target._events; - } - - existing = events[type]; - } - - if (!existing) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = prepend ? [listener, existing] : [existing, listener]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } // Check for listener leak - - - if (!existing.warned) { - m = $getMaxListeners(target); - - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + existing.length + ' ' + type + ' listeners added. ' + 'Use emitter.setMaxListeners() to increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - emitWarning(w); - } - } - } - - return target; - } - - function emitWarning(e) { - typeof console.warn === 'function' ? console.warn(e) : console.log(e); - } - - EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); - }; - - EventEmitter.prototype.on = EventEmitter.prototype.addListener; - - EventEmitter.prototype.prependListener = function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - - function _onceWrap(target, type, listener) { - var fired = false; - - function g() { - target.removeListener(type, g); - - if (!fired) { - fired = true; - listener.apply(target, arguments); - } - } - - g.listener = listener; - return g; - } - - EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; - }; - - EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { - if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; // emits a 'removeListener' event iff the listener was removed - - - EventEmitter.prototype.removeListener = function removeListener(type, listener) { - var list, events, position, i, originalListener; - if (typeof listener !== 'function') throw new TypeError('"listener" argument must be a function'); - events = this._events; - if (!events) return this; - list = events[type]; - if (!list) return this; - - if (list === listener || list.listener && list.listener === listener) { - if (--this._eventsCount === 0) this._events = new EventHandlers();else { - delete events[type]; - if (events.removeListener) this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length; i-- > 0;) { - if (list[i] === listener || list[i].listener && list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) return this; - - if (list.length === 1) { - list[0] = undefined; - - if (--this._eventsCount === 0) { - this._events = new EventHandlers(); - return this; - } else { - delete events[type]; - } - } else { - spliceOne(list, position); - } - - if (events.removeListener) this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - - EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { - var listeners, events; - events = this._events; - if (!events) return this; // not listening for removeListener, no need to emit - - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = new EventHandlers(); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) this._events = new EventHandlers();else delete events[type]; - } - - return this; - } // emit removeListener for all listeners on all events - - - if (arguments.length === 0) { - var keys = Object.keys(events); - - for (var i = 0, key; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - - this.removeAllListeners('removeListener'); - this._events = new EventHandlers(); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - do { - this.removeListener(type, listeners[listeners.length - 1]); - } while (listeners[0]); - } - - return this; - }; - - EventEmitter.prototype.listeners = function listeners(type) { - var evlistener; - var ret; - var events = this._events; - if (!events) ret = [];else { - evlistener = events[type]; - if (!evlistener) ret = [];else if (typeof evlistener === 'function') ret = [evlistener.listener || evlistener];else ret = unwrapListeners(evlistener); - } - return ret; - }; - - EventEmitter.listenerCount = function (emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } - }; - - EventEmitter.prototype.listenerCount = listenerCount; - - function listenerCount(type) { - var events = this._events; - - if (events) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; - } - - EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; - }; // About 1.5x faster than the two-arg version of Array#splice(). - - - function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) { - list[i] = list[k]; - } - - list.pop(); - } - - function arrayClone(arr, i) { - var copy = new Array(i); - - while (i--) { - copy[i] = arr[i]; - } - - return copy; - } - - function unwrapListeners(arr) { - var ret = new Array(arr.length); - - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - - return ret; - } - - var nativeJoin = [].join; - - var ES3_STRINGS = indexedObject != Object; - var STRICT_METHOD$1 = arrayMethodIsStrict('join', ','); - - // `Array.prototype.join` method - // https://tc39.es/ecma262/#sec-array.prototype.join - _export({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD$1 }, { - join: function join(separator) { - return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator); - } - }); - - var $map = arrayIteration.map; - - - - var HAS_SPECIES_SUPPORT$2 = arrayMethodHasSpeciesSupport('map'); - // FF49- issue - var USES_TO_LENGTH$3 = arrayMethodUsesToLength('map'); - - // `Array.prototype.map` method - // https://tc39.es/ecma262/#sec-array.prototype.map - // with adding support of @@species - _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$2 || !USES_TO_LENGTH$3 }, { - map: function map(callbackfn /* , thisArg */) { - return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - var aPossiblePrototype = function (it) { - if (!isObject(it) && it !== null) { - throw TypeError("Can't set " + String(it) + ' as a prototype'); - } return it; - }; - - // `Object.setPrototypeOf` method - // https://tc39.es/ecma262/#sec-object.setprototypeof - // Works with __proto__ only. Old v8 can't work with null proto objects. - /* eslint-disable no-proto */ - var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () { - var CORRECT_SETTER = false; - var test = {}; - var setter; - try { - setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set; - setter.call(test, []); - CORRECT_SETTER = test instanceof Array; - } catch (error) { /* empty */ } - return function setPrototypeOf(O, proto) { - anObject(O); - aPossiblePrototype(proto); - if (CORRECT_SETTER) setter.call(O, proto); - else O.__proto__ = proto; - return O; - }; - }() : undefined); - - // makes subclassing work correct for wrapped built-ins - var inheritIfRequired = function ($this, dummy, Wrapper) { - var NewTarget, NewTargetPrototype; - if ( - // it can work only with native `setPrototypeOf` - objectSetPrototypeOf && - // we haven't completely correct pre-ES6 way for getting `new.target`, so use this - typeof (NewTarget = dummy.constructor) == 'function' && - NewTarget !== Wrapper && - isObject(NewTargetPrototype = NewTarget.prototype) && - NewTargetPrototype !== Wrapper.prototype - ) objectSetPrototypeOf($this, NewTargetPrototype); - return $this; - }; - - // `Object.defineProperties` method - // https://tc39.es/ecma262/#sec-object.defineproperties - var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) { - anObject(O); - var keys = objectKeys(Properties); - var length = keys.length; - var index = 0; - var key; - while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]); - return O; - }; - - var html = getBuiltIn('document', 'documentElement'); - - var GT = '>'; - var LT = '<'; - var PROTOTYPE = 'prototype'; - var SCRIPT = 'script'; - var IE_PROTO$1 = sharedKey('IE_PROTO'); - - var EmptyConstructor = function () { /* empty */ }; - - var scriptTag = function (content) { - return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT; - }; - - // Create object with fake `null` prototype: use ActiveX Object with cleared prototype - var NullProtoObjectViaActiveX = function (activeXDocument) { - activeXDocument.write(scriptTag('')); - activeXDocument.close(); - var temp = activeXDocument.parentWindow.Object; - activeXDocument = null; // avoid memory leak - return temp; - }; - - // Create object with fake `null` prototype: use iframe Object with cleared prototype - var NullProtoObjectViaIFrame = function () { - // Thrash, waste and sodomy: IE GC bug - var iframe = documentCreateElement('iframe'); - var JS = 'java' + SCRIPT + ':'; - var iframeDocument; - iframe.style.display = 'none'; - html.appendChild(iframe); - // https://github.com/zloirock/core-js/issues/475 - iframe.src = String(JS); - iframeDocument = iframe.contentWindow.document; - iframeDocument.open(); - iframeDocument.write(scriptTag('document.F=Object')); - iframeDocument.close(); - return iframeDocument.F; - }; - - // Check for document.domain and active x support - // No need to use active x approach when document.domain is not set - // see https://github.com/es-shims/es5-shim/issues/150 - // variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346 - // avoid IE GC bug - var activeXDocument; - var NullProtoObject = function () { - try { - /* global ActiveXObject */ - activeXDocument = document.domain && new ActiveXObject('htmlfile'); - } catch (error) { /* ignore */ } - NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame(); - var length = enumBugKeys.length; - while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]]; - return NullProtoObject(); - }; - - hiddenKeys[IE_PROTO$1] = true; - - // `Object.create` method - // https://tc39.es/ecma262/#sec-object.create - var objectCreate = Object.create || function create(O, Properties) { - var result; - if (O !== null) { - EmptyConstructor[PROTOTYPE] = anObject(O); - result = new EmptyConstructor(); - EmptyConstructor[PROTOTYPE] = null; - // add "__proto__" for Object.getPrototypeOf polyfill - result[IE_PROTO$1] = O; - } else result = NullProtoObject(); - return Properties === undefined ? result : objectDefineProperties(result, Properties); - }; - - // a string of all valid unicode whitespaces - // eslint-disable-next-line max-len - var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; - - var whitespace = '[' + whitespaces + ']'; - var ltrim = RegExp('^' + whitespace + whitespace + '*'); - var rtrim = RegExp(whitespace + whitespace + '*$'); - - // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation - var createMethod$2 = function (TYPE) { - return function ($this) { - var string = String(requireObjectCoercible($this)); - if (TYPE & 1) string = string.replace(ltrim, ''); - if (TYPE & 2) string = string.replace(rtrim, ''); - return string; - }; - }; - - var stringTrim = { - // `String.prototype.{ trimLeft, trimStart }` methods - // https://tc39.es/ecma262/#sec-string.prototype.trimstart - start: createMethod$2(1), - // `String.prototype.{ trimRight, trimEnd }` methods - // https://tc39.es/ecma262/#sec-string.prototype.trimend - end: createMethod$2(2), - // `String.prototype.trim` method - // https://tc39.es/ecma262/#sec-string.prototype.trim - trim: createMethod$2(3) - }; - - var getOwnPropertyNames = objectGetOwnPropertyNames.f; - var getOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; - var defineProperty$3 = objectDefineProperty.f; - var trim = stringTrim.trim; - - var NUMBER = 'Number'; - var NativeNumber = global_1[NUMBER]; - var NumberPrototype = NativeNumber.prototype; - - // Opera ~12 has broken Object#toString - var BROKEN_CLASSOF = classofRaw(objectCreate(NumberPrototype)) == NUMBER; - - // `ToNumber` abstract operation - // https://tc39.es/ecma262/#sec-tonumber - var toNumber = function (argument) { - var it = toPrimitive(argument, false); - var first, third, radix, maxCode, digits, length, index, code; - if (typeof it == 'string' && it.length > 2) { - it = trim(it); - first = it.charCodeAt(0); - if (first === 43 || first === 45) { - third = it.charCodeAt(2); - if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix - } else if (first === 48) { - switch (it.charCodeAt(1)) { - case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i - case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i - default: return +it; - } - digits = it.slice(2); - length = digits.length; - for (index = 0; index < length; index++) { - code = digits.charCodeAt(index); - // parseInt parses a string to a first unavailable symbol - // but ToNumber should return NaN if a string contains unavailable symbols - if (code < 48 || code > maxCode) return NaN; - } return parseInt(digits, radix); - } - } return +it; - }; - - // `Number` constructor - // https://tc39.es/ecma262/#sec-number-constructor - if (isForced_1(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) { - var NumberWrapper = function Number(value) { - var it = arguments.length < 1 ? 0 : value; - var dummy = this; - return dummy instanceof NumberWrapper - // check on 1..constructor(foo) case - && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classofRaw(dummy) != NUMBER) - ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it); - }; - for (var keys$1 = descriptors ? getOwnPropertyNames(NativeNumber) : ( - // ES3: - 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + - // ES2015 (in case, if modules with ES2015 Number statics required before): - 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + - 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' + - // ESNext - 'fromString,range' - ).split(','), j = 0, key; keys$1.length > j; j++) { - if (has(NativeNumber, key = keys$1[j]) && !has(NumberWrapper, key)) { - defineProperty$3(NumberWrapper, key, getOwnPropertyDescriptor$2(NativeNumber, key)); - } - } - NumberWrapper.prototype = NumberPrototype; - NumberPrototype.constructor = NumberWrapper; - redefine(global_1, NUMBER, NumberWrapper); - } - - var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f; - - - var FAILS_ON_PRIMITIVES$2 = fails(function () { nativeGetOwnPropertyDescriptor$1(1); }); - var FORCED$1 = !descriptors || FAILS_ON_PRIMITIVES$2; - - // `Object.getOwnPropertyDescriptor` method - // https://tc39.es/ecma262/#sec-object.getownpropertydescriptor - _export({ target: 'Object', stat: true, forced: FORCED$1, sham: !descriptors }, { - getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) { - return nativeGetOwnPropertyDescriptor$1(toIndexedObject(it), key); - } - }); - - var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f; - - var toString$1 = {}.toString; - - var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames - ? Object.getOwnPropertyNames(window) : []; - - var getWindowNames = function (it) { - try { - return nativeGetOwnPropertyNames(it); - } catch (error) { - return windowNames.slice(); - } - }; - - // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window - var f$5 = function getOwnPropertyNames(it) { - return windowNames && toString$1.call(it) == '[object Window]' - ? getWindowNames(it) - : nativeGetOwnPropertyNames(toIndexedObject(it)); - }; - - var objectGetOwnPropertyNamesExternal = { - f: f$5 - }; - - var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f; - - var FAILS_ON_PRIMITIVES$3 = fails(function () { return !Object.getOwnPropertyNames(1); }); - - // `Object.getOwnPropertyNames` method - // https://tc39.es/ecma262/#sec-object.getownpropertynames - _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$3 }, { - getOwnPropertyNames: nativeGetOwnPropertyNames$1 - }); - - var MATCH = wellKnownSymbol('match'); - - // `IsRegExp` abstract operation - // https://tc39.es/ecma262/#sec-isregexp - var isRegexp = function (it) { - var isRegExp; - return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp'); - }; - - var SPECIES$3 = wellKnownSymbol('species'); - - var setSpecies = function (CONSTRUCTOR_NAME) { - var Constructor = getBuiltIn(CONSTRUCTOR_NAME); - var defineProperty = objectDefineProperty.f; - - if (descriptors && Constructor && !Constructor[SPECIES$3]) { - defineProperty(Constructor, SPECIES$3, { - configurable: true, - get: function () { return this; } - }); - } - }; - - var defineProperty$4 = objectDefineProperty.f; - var getOwnPropertyNames$1 = objectGetOwnPropertyNames.f; - - - - - - var setInternalState = internalState.set; - - - - var MATCH$1 = wellKnownSymbol('match'); - var NativeRegExp = global_1.RegExp; - var RegExpPrototype$1 = NativeRegExp.prototype; - var re1 = /a/g; - var re2 = /a/g; - - // "new" should create a new object, old webkit bug - var CORRECT_NEW = new NativeRegExp(re1) !== re1; - - var UNSUPPORTED_Y$2 = regexpStickyHelpers.UNSUPPORTED_Y; - - var FORCED$2 = descriptors && isForced_1('RegExp', (!CORRECT_NEW || UNSUPPORTED_Y$2 || fails(function () { - re2[MATCH$1] = false; - // RegExp constructor can alter flags and IsRegExp works correct with @@match - return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i'; - }))); - - // `RegExp` constructor - // https://tc39.es/ecma262/#sec-regexp-constructor - if (FORCED$2) { - var RegExpWrapper = function RegExp(pattern, flags) { - var thisIsRegExp = this instanceof RegExpWrapper; - var patternIsRegExp = isRegexp(pattern); - var flagsAreUndefined = flags === undefined; - var sticky; - - if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) { - return pattern; - } - - if (CORRECT_NEW) { - if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source; - } else if (pattern instanceof RegExpWrapper) { - if (flagsAreUndefined) flags = regexpFlags.call(pattern); - pattern = pattern.source; - } - - if (UNSUPPORTED_Y$2) { - sticky = !!flags && flags.indexOf('y') > -1; - if (sticky) flags = flags.replace(/y/g, ''); - } - - var result = inheritIfRequired( - CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags), - thisIsRegExp ? this : RegExpPrototype$1, - RegExpWrapper - ); - - if (UNSUPPORTED_Y$2 && sticky) setInternalState(result, { sticky: sticky }); - - return result; - }; - var proxy = function (key) { - key in RegExpWrapper || defineProperty$4(RegExpWrapper, key, { - configurable: true, - get: function () { return NativeRegExp[key]; }, - set: function (it) { NativeRegExp[key] = it; } - }); - }; - var keys$2 = getOwnPropertyNames$1(NativeRegExp); - var index = 0; - while (keys$2.length > index) proxy(keys$2[index++]); - RegExpPrototype$1.constructor = RegExpWrapper; - RegExpWrapper.prototype = RegExpPrototype$1; - redefine(global_1, 'RegExp', RegExpWrapper); - } - - // https://tc39.es/ecma262/#sec-get-regexp-@@species - setSpecies('RegExp'); - - // `String.prototype.{ codePointAt, at }` methods implementation - var createMethod$3 = function (CONVERT_TO_STRING) { - return function ($this, pos) { - var S = String(requireObjectCoercible($this)); - var position = toInteger(pos); - var size = S.length; - var first, second; - if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined; - first = S.charCodeAt(position); - return first < 0xD800 || first > 0xDBFF || position + 1 === size - || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF - ? CONVERT_TO_STRING ? S.charAt(position) : first - : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000; - }; - }; - - var stringMultibyte = { - // `String.prototype.codePointAt` method - // https://tc39.es/ecma262/#sec-string.prototype.codepointat - codeAt: createMethod$3(false), - // `String.prototype.at` method - // https://github.com/mathiasbynens/String.prototype.at - charAt: createMethod$3(true) - }; - - var charAt = stringMultibyte.charAt; - - // `AdvanceStringIndex` abstract operation - // https://tc39.es/ecma262/#sec-advancestringindex - var advanceStringIndex = function (S, index, unicode) { - return index + (unicode ? charAt(S, index).length : 1); - }; - - // @@match logic - fixRegexpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) { - return [ - // `String.prototype.match` method - // https://tc39.es/ecma262/#sec-string.prototype.match - function match(regexp) { - var O = requireObjectCoercible(this); - var matcher = regexp == undefined ? undefined : regexp[MATCH]; - return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); - }, - // `RegExp.prototype[@@match]` method - // https://tc39.es/ecma262/#sec-regexp.prototype-@@match - function (regexp) { - var res = maybeCallNative(nativeMatch, regexp, this); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - - if (!rx.global) return regexpExecAbstract(rx, S); - - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - var A = []; - var n = 0; - var result; - while ((result = regexpExecAbstract(rx, S)) !== null) { - var matchStr = String(result[0]); - A[n] = matchStr; - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - n++; - } - return n === 0 ? null : A; - } - ]; - }); - - var floor$1 = Math.floor; - var replace = ''.replace; - var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g; - var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g; - - // https://tc39.es/ecma262/#sec-getsubstitution - var getSubstitution = function (matched, str, position, captures, namedCaptures, replacement) { - var tailPos = position + matched.length; - var m = captures.length; - var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED; - if (namedCaptures !== undefined) { - namedCaptures = toObject(namedCaptures); - symbols = SUBSTITUTION_SYMBOLS; - } - return replace.call(replacement, symbols, function (match, ch) { - var capture; - switch (ch.charAt(0)) { - case '$': return '$'; - case '&': return matched; - case '`': return str.slice(0, position); - case "'": return str.slice(tailPos); - case '<': - capture = namedCaptures[ch.slice(1, -1)]; - break; - default: // \d\d? - var n = +ch; - if (n === 0) return match; - if (n > m) { - var f = floor$1(n / 10); - if (f === 0) return match; - if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1); - return match; - } - capture = captures[n - 1]; - } - return capture === undefined ? '' : capture; - }); - }; - - var max$2 = Math.max; - var min$3 = Math.min; - - var maybeToString = function (it) { - return it === undefined ? it : String(it); - }; - - // @@replace logic - fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) { - var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE; - var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0; - var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0'; - - return [ - // `String.prototype.replace` method - // https://tc39.es/ecma262/#sec-string.prototype.replace - function replace(searchValue, replaceValue) { - var O = requireObjectCoercible(this); - var replacer = searchValue == undefined ? undefined : searchValue[REPLACE]; - return replacer !== undefined - ? replacer.call(searchValue, O, replaceValue) - : nativeReplace.call(String(O), searchValue, replaceValue); - }, - // `RegExp.prototype[@@replace]` method - // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace - function (regexp, replaceValue) { - if ( - (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) || - (typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1) - ) { - var res = maybeCallNative(nativeReplace, regexp, this, replaceValue); - if (res.done) return res.value; - } - - var rx = anObject(regexp); - var S = String(this); - - var functionalReplace = typeof replaceValue === 'function'; - if (!functionalReplace) replaceValue = String(replaceValue); - - var global = rx.global; - if (global) { - var fullUnicode = rx.unicode; - rx.lastIndex = 0; - } - var results = []; - while (true) { - var result = regexpExecAbstract(rx, S); - if (result === null) break; - - results.push(result); - if (!global) break; - - var matchStr = String(result[0]); - if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode); - } - - var accumulatedResult = ''; - var nextSourcePosition = 0; - for (var i = 0; i < results.length; i++) { - result = results[i]; - - var matched = String(result[0]); - var position = max$2(min$3(toInteger(result.index), S.length), 0); - var captures = []; - // NOTE: This is equivalent to - // captures = result.slice(1).map(maybeToString) - // but for some reason `nativeSlice.call(result, 1, result.length)` (called in - // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and - // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it. - for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j])); - var namedCaptures = result.groups; - if (functionalReplace) { - var replacerArgs = [matched].concat(captures, position, S); - if (namedCaptures !== undefined) replacerArgs.push(namedCaptures); - var replacement = String(replaceValue.apply(undefined, replacerArgs)); - } else { - replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue); - } - if (position >= nextSourcePosition) { - accumulatedResult += S.slice(nextSourcePosition, position) + replacement; - nextSourcePosition = position + matched.length; - } - } - return accumulatedResult + S.slice(nextSourcePosition); - } - ]; - }); - - var SPECIES$4 = wellKnownSymbol('species'); - - // `SpeciesConstructor` abstract operation - // https://tc39.es/ecma262/#sec-speciesconstructor - var speciesConstructor = function (O, defaultConstructor) { - var C = anObject(O).constructor; - var S; - return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aFunction$1(S); - }; - - var arrayPush = [].push; - var min$4 = Math.min; - var MAX_UINT32 = 0xFFFFFFFF; - - // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError - var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); }); - - // @@split logic - fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) { - var internalSplit; - if ( - 'abbc'.split(/(b)*/)[1] == 'c' || - 'test'.split(/(?:)/, -1).length != 4 || - 'ab'.split(/(?:ab)*/).length != 2 || - '.'.split(/(.?)(.?)/).length != 4 || - '.'.split(/()()/).length > 1 || - ''.split(/.?/).length - ) { - // based on es5-shim implementation, need to rework it - internalSplit = function (separator, limit) { - var string = String(requireObjectCoercible(this)); - var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; - if (lim === 0) return []; - if (separator === undefined) return [string]; - // If `separator` is not a regex, use native split - if (!isRegexp(separator)) { - return nativeSplit.call(string, separator, lim); - } - var output = []; - var flags = (separator.ignoreCase ? 'i' : '') + - (separator.multiline ? 'm' : '') + - (separator.unicode ? 'u' : '') + - (separator.sticky ? 'y' : ''); - var lastLastIndex = 0; - // Make `global` and avoid `lastIndex` issues by working with a copy - var separatorCopy = new RegExp(separator.source, flags + 'g'); - var match, lastIndex, lastLength; - while (match = regexpExec.call(separatorCopy, string)) { - lastIndex = separatorCopy.lastIndex; - if (lastIndex > lastLastIndex) { - output.push(string.slice(lastLastIndex, match.index)); - if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1)); - lastLength = match[0].length; - lastLastIndex = lastIndex; - if (output.length >= lim) break; - } - if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop - } - if (lastLastIndex === string.length) { - if (lastLength || !separatorCopy.test('')) output.push(''); - } else output.push(string.slice(lastLastIndex)); - return output.length > lim ? output.slice(0, lim) : output; - }; - // Chakra, V8 - } else if ('0'.split(undefined, 0).length) { - internalSplit = function (separator, limit) { - return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit); - }; - } else internalSplit = nativeSplit; - - return [ - // `String.prototype.split` method - // https://tc39.es/ecma262/#sec-string.prototype.split - function split(separator, limit) { - var O = requireObjectCoercible(this); - var splitter = separator == undefined ? undefined : separator[SPLIT]; - return splitter !== undefined - ? splitter.call(separator, O, limit) - : internalSplit.call(String(O), separator, limit); - }, - // `RegExp.prototype[@@split]` method - // https://tc39.es/ecma262/#sec-regexp.prototype-@@split - // - // NOTE: This cannot be properly polyfilled in engines that don't support - // the 'y' flag. - function (regexp, limit) { - var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit); - if (res.done) return res.value; - - var rx = anObject(regexp); - var S = String(this); - var C = speciesConstructor(rx, RegExp); - - var unicodeMatching = rx.unicode; - var flags = (rx.ignoreCase ? 'i' : '') + - (rx.multiline ? 'm' : '') + - (rx.unicode ? 'u' : '') + - (SUPPORTS_Y ? 'y' : 'g'); - - // ^(? + rx + ) is needed, in combination with some S slicing, to - // simulate the 'y' flag. - var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags); - var lim = limit === undefined ? MAX_UINT32 : limit >>> 0; - if (lim === 0) return []; - if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : []; - var p = 0; - var q = 0; - var A = []; - while (q < S.length) { - splitter.lastIndex = SUPPORTS_Y ? q : 0; - var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q)); - var e; - if ( - z === null || - (e = min$4(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p - ) { - q = advanceStringIndex(S, q, unicodeMatching); - } else { - A.push(S.slice(p, q)); - if (A.length === lim) return A; - for (var i = 1; i <= z.length - 1; i++) { - A.push(z[i]); - if (A.length === lim) return A; - } - q = p = e; - } - } - A.push(S.slice(p)); - return A; - } - ]; - }, !SUPPORTS_Y); - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _asyncIterator(iterable) { - var method; - - if (typeof Symbol !== "undefined") { - if (Symbol.asyncIterator) { - method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - method = iterable[Symbol.iterator]; - if (method != null) return method.call(iterable); - } - } - - throw new TypeError("Object is not async iterable"); - } - - 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); - }); - }; - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function ownKeys$1(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys$1(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys$1(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var f$6 = wellKnownSymbol; - - var wellKnownSymbolWrapped = { - f: f$6 - }; - - var defineProperty$5 = objectDefineProperty.f; - - var defineWellKnownSymbol = function (NAME) { - var Symbol = path.Symbol || (path.Symbol = {}); - if (!has(Symbol, NAME)) defineProperty$5(Symbol, NAME, { - value: wellKnownSymbolWrapped.f(NAME) - }); - }; - - var defineProperty$6 = objectDefineProperty.f; - - - - var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag'); - - var setToStringTag = function (it, TAG, STATIC) { - if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG$2)) { - defineProperty$6(it, TO_STRING_TAG$2, { configurable: true, value: TAG }); - } - }; - - var $forEach$1 = arrayIteration.forEach; - - var HIDDEN = sharedKey('hidden'); - var SYMBOL = 'Symbol'; - var PROTOTYPE$1 = 'prototype'; - var TO_PRIMITIVE = wellKnownSymbol('toPrimitive'); - var setInternalState$1 = internalState.set; - var getInternalState = internalState.getterFor(SYMBOL); - var ObjectPrototype$1 = Object[PROTOTYPE$1]; - var $Symbol = global_1.Symbol; - var $stringify = getBuiltIn('JSON', 'stringify'); - var nativeGetOwnPropertyDescriptor$2 = objectGetOwnPropertyDescriptor.f; - var nativeDefineProperty$1 = objectDefineProperty.f; - var nativeGetOwnPropertyNames$2 = objectGetOwnPropertyNamesExternal.f; - var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f; - var AllSymbols = shared('symbols'); - var ObjectPrototypeSymbols = shared('op-symbols'); - var StringToSymbolRegistry = shared('string-to-symbol-registry'); - var SymbolToStringRegistry = shared('symbol-to-string-registry'); - var WellKnownSymbolsStore$1 = shared('wks'); - var QObject = global_1.QObject; - // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 - var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild; - - // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 - var setSymbolDescriptor = descriptors && fails(function () { - return objectCreate(nativeDefineProperty$1({}, 'a', { - get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; } - })).a != 7; - }) ? function (O, P, Attributes) { - var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$2(ObjectPrototype$1, P); - if (ObjectPrototypeDescriptor) delete ObjectPrototype$1[P]; - nativeDefineProperty$1(O, P, Attributes); - if (ObjectPrototypeDescriptor && O !== ObjectPrototype$1) { - nativeDefineProperty$1(ObjectPrototype$1, P, ObjectPrototypeDescriptor); - } - } : nativeDefineProperty$1; - - var wrap = function (tag, description) { - var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]); - setInternalState$1(symbol, { - type: SYMBOL, - tag: tag, - description: description - }); - if (!descriptors) symbol.description = description; - return symbol; - }; - - var isSymbol = useSymbolAsUid ? function (it) { - return typeof it == 'symbol'; - } : function (it) { - return Object(it) instanceof $Symbol; - }; - - var $defineProperty = function defineProperty(O, P, Attributes) { - if (O === ObjectPrototype$1) $defineProperty(ObjectPrototypeSymbols, P, Attributes); - anObject(O); - var key = toPrimitive(P, true); - anObject(Attributes); - if (has(AllSymbols, key)) { - if (!Attributes.enumerable) { - if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {})); - O[HIDDEN][key] = true; - } else { - if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false; - Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) }); - } return setSymbolDescriptor(O, key, Attributes); - } return nativeDefineProperty$1(O, key, Attributes); - }; - - var $defineProperties = function defineProperties(O, Properties) { - anObject(O); - var properties = toIndexedObject(Properties); - var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties)); - $forEach$1(keys, function (key) { - if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]); - }); - return O; - }; - - var $create = function create(O, Properties) { - return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties); - }; - - var $propertyIsEnumerable = function propertyIsEnumerable(V) { - var P = toPrimitive(V, true); - var enumerable = nativePropertyIsEnumerable$1.call(this, P); - if (this === ObjectPrototype$1 && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false; - return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true; - }; - - var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) { - var it = toIndexedObject(O); - var key = toPrimitive(P, true); - if (it === ObjectPrototype$1 && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return; - var descriptor = nativeGetOwnPropertyDescriptor$2(it, key); - if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) { - descriptor.enumerable = true; - } - return descriptor; - }; - - var $getOwnPropertyNames = function getOwnPropertyNames(O) { - var names = nativeGetOwnPropertyNames$2(toIndexedObject(O)); - var result = []; - $forEach$1(names, function (key) { - if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key); - }); - return result; - }; - - var $getOwnPropertySymbols = function getOwnPropertySymbols(O) { - var IS_OBJECT_PROTOTYPE = O === ObjectPrototype$1; - var names = nativeGetOwnPropertyNames$2(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O)); - var result = []; - $forEach$1(names, function (key) { - if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype$1, key))) { - result.push(AllSymbols[key]); - } - }); - return result; - }; - - // `Symbol` constructor - // https://tc39.es/ecma262/#sec-symbol-constructor - if (!nativeSymbol) { - $Symbol = function Symbol() { - if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor'); - var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]); - var tag = uid(description); - var setter = function (value) { - if (this === ObjectPrototype$1) setter.call(ObjectPrototypeSymbols, value); - if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false; - setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value)); - }; - if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype$1, tag, { configurable: true, set: setter }); - return wrap(tag, description); - }; - - redefine($Symbol[PROTOTYPE$1], 'toString', function toString() { - return getInternalState(this).tag; - }); - - redefine($Symbol, 'withoutSetter', function (description) { - return wrap(uid(description), description); - }); - - objectPropertyIsEnumerable.f = $propertyIsEnumerable; - objectDefineProperty.f = $defineProperty; - objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor; - objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames; - objectGetOwnPropertySymbols.f = $getOwnPropertySymbols; - - wellKnownSymbolWrapped.f = function (name) { - return wrap(wellKnownSymbol(name), name); - }; - - if (descriptors) { - // https://github.com/tc39/proposal-Symbol-description - nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', { - configurable: true, - get: function description() { - return getInternalState(this).description; - } - }); - { - redefine(ObjectPrototype$1, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true }); - } - } - } - - _export({ global: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, { - Symbol: $Symbol - }); - - $forEach$1(objectKeys(WellKnownSymbolsStore$1), function (name) { - defineWellKnownSymbol(name); - }); - - _export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, { - // `Symbol.for` method - // https://tc39.es/ecma262/#sec-symbol.for - 'for': function (key) { - var string = String(key); - if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string]; - var symbol = $Symbol(string); - StringToSymbolRegistry[string] = symbol; - SymbolToStringRegistry[symbol] = string; - return symbol; - }, - // `Symbol.keyFor` method - // https://tc39.es/ecma262/#sec-symbol.keyfor - keyFor: function keyFor(sym) { - if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol'); - if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym]; - }, - useSetter: function () { USE_SETTER = true; }, - useSimple: function () { USE_SETTER = false; } - }); - - _export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, { - // `Object.create` method - // https://tc39.es/ecma262/#sec-object.create - create: $create, - // `Object.defineProperty` method - // https://tc39.es/ecma262/#sec-object.defineproperty - defineProperty: $defineProperty, - // `Object.defineProperties` method - // https://tc39.es/ecma262/#sec-object.defineproperties - defineProperties: $defineProperties, - // `Object.getOwnPropertyDescriptor` method - // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors - getOwnPropertyDescriptor: $getOwnPropertyDescriptor - }); - - _export({ target: 'Object', stat: true, forced: !nativeSymbol }, { - // `Object.getOwnPropertyNames` method - // https://tc39.es/ecma262/#sec-object.getownpropertynames - getOwnPropertyNames: $getOwnPropertyNames, - // `Object.getOwnPropertySymbols` method - // https://tc39.es/ecma262/#sec-object.getownpropertysymbols - getOwnPropertySymbols: $getOwnPropertySymbols - }); - - // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives - // https://bugs.chromium.org/p/v8/issues/detail?id=3443 - _export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, { - getOwnPropertySymbols: function getOwnPropertySymbols(it) { - return objectGetOwnPropertySymbols.f(toObject(it)); - } - }); - - // `JSON.stringify` method behavior with symbols - // https://tc39.es/ecma262/#sec-json.stringify - if ($stringify) { - var FORCED_JSON_STRINGIFY = !nativeSymbol || fails(function () { - var symbol = $Symbol(); - // MS Edge converts symbol values to JSON as {} - return $stringify([symbol]) != '[null]' - // WebKit converts symbol values to JSON as null - || $stringify({ a: symbol }) != '{}' - // V8 throws on boxed symbols - || $stringify(Object(symbol)) != '{}'; - }); - - _export({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, { - // eslint-disable-next-line no-unused-vars - stringify: function stringify(it, replacer, space) { - var args = [it]; - var index = 1; - var $replacer; - while (arguments.length > index) args.push(arguments[index++]); - $replacer = replacer; - if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined - if (!isArray(replacer)) replacer = function (key, value) { - if (typeof $replacer == 'function') value = $replacer.call(this, key, value); - if (!isSymbol(value)) return value; - }; - args[1] = replacer; - return $stringify.apply(null, args); - } - }); - } - - // `Symbol.prototype[@@toPrimitive]` method - // https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive - if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) { - createNonEnumerableProperty($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf); - } - // `Symbol.prototype[@@toStringTag]` property - // https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag - setToStringTag($Symbol, SYMBOL); - - hiddenKeys[HIDDEN] = true; - - var defineProperty$7 = objectDefineProperty.f; - - - var NativeSymbol = global_1.Symbol; - - if (descriptors && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) || - // Safari 12 bug - NativeSymbol().description !== undefined - )) { - var EmptyStringDescriptionStore = {}; - // wrap Symbol constructor for correct work with undefined description - var SymbolWrapper = function Symbol() { - var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]); - var result = this instanceof SymbolWrapper - ? new NativeSymbol(description) - // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)' - : description === undefined ? NativeSymbol() : NativeSymbol(description); - if (description === '') EmptyStringDescriptionStore[result] = true; - return result; - }; - copyConstructorProperties(SymbolWrapper, NativeSymbol); - var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype; - symbolPrototype.constructor = SymbolWrapper; - - var symbolToString = symbolPrototype.toString; - var native = String(NativeSymbol('test')) == 'Symbol(test)'; - var regexp = /^Symbol\((.*)\)[^)]+$/; - defineProperty$7(symbolPrototype, 'description', { - configurable: true, - get: function description() { - var symbol = isObject(this) ? this.valueOf() : this; - var string = symbolToString.call(symbol); - if (has(EmptyStringDescriptionStore, symbol)) return ''; - var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1'); - return desc === '' ? undefined : desc; - } - }); - - _export({ global: true, forced: true }, { - Symbol: SymbolWrapper - }); - } - - // `Symbol.species` well-known symbol - // https://tc39.es/ecma262/#sec-symbol.species - defineWellKnownSymbol('species'); - - // `Array.prototype.fill` method implementation - // https://tc39.es/ecma262/#sec-array.prototype.fill - var arrayFill = function fill(value /* , start = 0, end = @length */) { - var O = toObject(this); - var length = toLength(O.length); - var argumentsLength = arguments.length; - var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length); - var end = argumentsLength > 2 ? arguments[2] : undefined; - var endPos = end === undefined ? length : toAbsoluteIndex(end, length); - while (endPos > index) O[index++] = value; - return O; - }; - - var UNSCOPABLES = wellKnownSymbol('unscopables'); - var ArrayPrototype = Array.prototype; - - // Array.prototype[@@unscopables] - // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables - if (ArrayPrototype[UNSCOPABLES] == undefined) { - objectDefineProperty.f(ArrayPrototype, UNSCOPABLES, { - configurable: true, - value: objectCreate(null) - }); - } - - // add a key to Array.prototype[@@unscopables] - var addToUnscopables = function (key) { - ArrayPrototype[UNSCOPABLES][key] = true; - }; - - // `Array.prototype.fill` method - // https://tc39.es/ecma262/#sec-array.prototype.fill - _export({ target: 'Array', proto: true }, { - fill: arrayFill - }); - - // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables - addToUnscopables('fill'); - - var $includes = arrayIncludes.includes; - - - - var USES_TO_LENGTH$4 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); - - // `Array.prototype.includes` method - // https://tc39.es/ecma262/#sec-array.prototype.includes - _export({ target: 'Array', proto: true, forced: !USES_TO_LENGTH$4 }, { - includes: function includes(el /* , fromIndex = 0 */) { - return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); - } - }); - - // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables - addToUnscopables('includes'); - - var iterators = {}; - - var ITERATOR = wellKnownSymbol('iterator'); - var BUGGY_SAFARI_ITERATORS = false; - - var returnThis = function () { return this; }; - - // `%IteratorPrototype%` object - // https://tc39.es/ecma262/#sec-%iteratorprototype%-object - var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator; - - if ([].keys) { - arrayIterator = [].keys(); - // Safari 8 has buggy iterators w/o `next` - if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true; - else { - PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator)); - if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype; - } - } - - var NEW_ITERATOR_PROTOTYPE = IteratorPrototype == undefined || fails(function () { - var test = {}; - // FF44- legacy iterators case - return IteratorPrototype[ITERATOR].call(test) !== test; - }); - - if (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {}; - - // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() - if ( !has(IteratorPrototype, ITERATOR)) { - createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis); - } - - var iteratorsCore = { - IteratorPrototype: IteratorPrototype, - BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS - }; - - var IteratorPrototype$1 = iteratorsCore.IteratorPrototype; - - - - - - var returnThis$1 = function () { return this; }; - - var createIteratorConstructor = function (IteratorConstructor, NAME, next) { - var TO_STRING_TAG = NAME + ' Iterator'; - IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) }); - setToStringTag(IteratorConstructor, TO_STRING_TAG, false); - iterators[TO_STRING_TAG] = returnThis$1; - return IteratorConstructor; - }; - - var IteratorPrototype$2 = iteratorsCore.IteratorPrototype; - var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS; - var ITERATOR$1 = wellKnownSymbol('iterator'); - var KEYS = 'keys'; - var VALUES = 'values'; - var ENTRIES = 'entries'; - - var returnThis$2 = function () { return this; }; - - var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) { - createIteratorConstructor(IteratorConstructor, NAME, next); - - var getIterationMethod = function (KIND) { - if (KIND === DEFAULT && defaultIterator) return defaultIterator; - if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND]; - switch (KIND) { - case KEYS: return function keys() { return new IteratorConstructor(this, KIND); }; - case VALUES: return function values() { return new IteratorConstructor(this, KIND); }; - case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); }; - } return function () { return new IteratorConstructor(this); }; - }; - - var TO_STRING_TAG = NAME + ' Iterator'; - var INCORRECT_VALUES_NAME = false; - var IterablePrototype = Iterable.prototype; - var nativeIterator = IterablePrototype[ITERATOR$1] - || IterablePrototype['@@iterator'] - || DEFAULT && IterablePrototype[DEFAULT]; - var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT); - var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator; - var CurrentIteratorPrototype, methods, KEY; - - // fix native - if (anyNativeIterator) { - CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable())); - if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) { - if ( objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) { - if (objectSetPrototypeOf) { - objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2); - } else if (typeof CurrentIteratorPrototype[ITERATOR$1] != 'function') { - createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR$1, returnThis$2); - } - } - // Set @@toStringTag to native iterators - setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true); - } - } - - // fix Array#{values, @@iterator}.name in V8 / FF - if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) { - INCORRECT_VALUES_NAME = true; - defaultIterator = function values() { return nativeIterator.call(this); }; - } - - // define iterator - if ( IterablePrototype[ITERATOR$1] !== defaultIterator) { - createNonEnumerableProperty(IterablePrototype, ITERATOR$1, defaultIterator); - } - iterators[NAME] = defaultIterator; - - // export additional methods - if (DEFAULT) { - methods = { - values: getIterationMethod(VALUES), - keys: IS_SET ? defaultIterator : getIterationMethod(KEYS), - entries: getIterationMethod(ENTRIES) - }; - if (FORCED) for (KEY in methods) { - if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) { - redefine(IterablePrototype, KEY, methods[KEY]); - } - } else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods); - } - - return methods; - }; - - var ARRAY_ITERATOR = 'Array Iterator'; - var setInternalState$2 = internalState.set; - var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR); - - // `Array.prototype.entries` method - // https://tc39.es/ecma262/#sec-array.prototype.entries - // `Array.prototype.keys` method - // https://tc39.es/ecma262/#sec-array.prototype.keys - // `Array.prototype.values` method - // https://tc39.es/ecma262/#sec-array.prototype.values - // `Array.prototype[@@iterator]` method - // https://tc39.es/ecma262/#sec-array.prototype-@@iterator - // `CreateArrayIterator` internal method - // https://tc39.es/ecma262/#sec-createarrayiterator - var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) { - setInternalState$2(this, { - type: ARRAY_ITERATOR, - target: toIndexedObject(iterated), // target - index: 0, // next index - kind: kind // kind - }); - // `%ArrayIteratorPrototype%.next` method - // https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next - }, function () { - var state = getInternalState$1(this); - var target = state.target; - var kind = state.kind; - var index = state.index++; - if (!target || index >= target.length) { - state.target = undefined; - return { value: undefined, done: true }; - } - if (kind == 'keys') return { value: index, done: false }; - if (kind == 'values') return { value: target[index], done: false }; - return { value: [index, target[index]], done: false }; - }, 'values'); - - // argumentsList[@@iterator] is %ArrayProto_values% - // https://tc39.es/ecma262/#sec-createunmappedargumentsobject - // https://tc39.es/ecma262/#sec-createmappedargumentsobject - iterators.Arguments = iterators.Array; - - // https://tc39.es/ecma262/#sec-array.prototype-@@unscopables - addToUnscopables('keys'); - addToUnscopables('values'); - addToUnscopables('entries'); - - var HAS_SPECIES_SUPPORT$3 = arrayMethodHasSpeciesSupport('slice'); - var USES_TO_LENGTH$5 = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 }); - - var SPECIES$5 = wellKnownSymbol('species'); - var nativeSlice = [].slice; - var max$3 = Math.max; - - // `Array.prototype.slice` method - // https://tc39.es/ecma262/#sec-array.prototype.slice - // fallback for not array-like ES3 strings and DOM objects - _export({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT$3 || !USES_TO_LENGTH$5 }, { - slice: function slice(start, end) { - var O = toIndexedObject(this); - var length = toLength(O.length); - var k = toAbsoluteIndex(start, length); - var fin = toAbsoluteIndex(end === undefined ? length : end, length); - // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible - var Constructor, result, n; - if (isArray(O)) { - Constructor = O.constructor; - // cross-realm fallback - if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) { - Constructor = undefined; - } else if (isObject(Constructor)) { - Constructor = Constructor[SPECIES$5]; - if (Constructor === null) Constructor = undefined; - } - if (Constructor === Array || Constructor === undefined) { - return nativeSlice.call(O, k, fin); - } - } - result = new (Constructor === undefined ? Array : Constructor)(max$3(fin - k, 0)); - for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]); - result.length = n; - return result; - } - }); - - // `Array[@@species]` getter - // https://tc39.es/ecma262/#sec-get-array-@@species - setSpecies('Array'); - - var arrayBufferNative = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined'; - - var redefineAll = function (target, src, options) { - for (var key in src) redefine(target, key, src[key], options); - return target; - }; - - var anInstance = function (it, Constructor, name) { - if (!(it instanceof Constructor)) { - throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation'); - } return it; - }; - - // `ToIndex` abstract operation - // https://tc39.es/ecma262/#sec-toindex - var toIndex = function (it) { - if (it === undefined) return 0; - var number = toInteger(it); - var length = toLength(number); - if (number !== length) throw RangeError('Wrong length or index'); - return length; - }; - - // IEEE754 conversions based on https://github.com/feross/ieee754 - // eslint-disable-next-line no-shadow-restricted-names - var Infinity$1 = 1 / 0; - var abs = Math.abs; - var pow = Math.pow; - var floor$2 = Math.floor; - var log = Math.log; - var LN2 = Math.LN2; - - var pack = function (number, mantissaLength, bytes) { - var buffer = new Array(bytes); - var exponentLength = bytes * 8 - mantissaLength - 1; - var eMax = (1 << exponentLength) - 1; - var eBias = eMax >> 1; - var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0; - var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0; - var index = 0; - var exponent, mantissa, c; - number = abs(number); - // eslint-disable-next-line no-self-compare - if (number != number || number === Infinity$1) { - // eslint-disable-next-line no-self-compare - mantissa = number != number ? 1 : 0; - exponent = eMax; - } else { - exponent = floor$2(log(number) / LN2); - if (number * (c = pow(2, -exponent)) < 1) { - exponent--; - c *= 2; - } - if (exponent + eBias >= 1) { - number += rt / c; - } else { - number += rt * pow(2, 1 - eBias); - } - if (number * c >= 2) { - exponent++; - c /= 2; - } - if (exponent + eBias >= eMax) { - mantissa = 0; - exponent = eMax; - } else if (exponent + eBias >= 1) { - mantissa = (number * c - 1) * pow(2, mantissaLength); - exponent = exponent + eBias; - } else { - mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength); - exponent = 0; - } - } - for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8); - exponent = exponent << mantissaLength | mantissa; - exponentLength += mantissaLength; - for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8); - buffer[--index] |= sign * 128; - return buffer; - }; - - var unpack = function (buffer, mantissaLength) { - var bytes = buffer.length; - var exponentLength = bytes * 8 - mantissaLength - 1; - var eMax = (1 << exponentLength) - 1; - var eBias = eMax >> 1; - var nBits = exponentLength - 7; - var index = bytes - 1; - var sign = buffer[index--]; - var exponent = sign & 127; - var mantissa; - sign >>= 7; - for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8); - mantissa = exponent & (1 << -nBits) - 1; - exponent >>= -nBits; - nBits += mantissaLength; - for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8); - if (exponent === 0) { - exponent = 1 - eBias; - } else if (exponent === eMax) { - return mantissa ? NaN : sign ? -Infinity$1 : Infinity$1; - } else { - mantissa = mantissa + pow(2, mantissaLength); - exponent = exponent - eBias; - } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength); - }; - - var ieee754 = { - pack: pack, - unpack: unpack - }; - - var getOwnPropertyNames$2 = objectGetOwnPropertyNames.f; - var defineProperty$8 = objectDefineProperty.f; - - - - - var getInternalState$2 = internalState.get; - var setInternalState$3 = internalState.set; - var ARRAY_BUFFER = 'ArrayBuffer'; - var DATA_VIEW = 'DataView'; - var PROTOTYPE$2 = 'prototype'; - var WRONG_LENGTH = 'Wrong length'; - var WRONG_INDEX = 'Wrong index'; - var NativeArrayBuffer = global_1[ARRAY_BUFFER]; - var $ArrayBuffer = NativeArrayBuffer; - var $DataView = global_1[DATA_VIEW]; - var $DataViewPrototype = $DataView && $DataView[PROTOTYPE$2]; - var ObjectPrototype$2 = Object.prototype; - var RangeError$1 = global_1.RangeError; - - var packIEEE754 = ieee754.pack; - var unpackIEEE754 = ieee754.unpack; - - var packInt8 = function (number) { - return [number & 0xFF]; - }; - - var packInt16 = function (number) { - return [number & 0xFF, number >> 8 & 0xFF]; - }; - - var packInt32 = function (number) { - return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF]; - }; - - var unpackInt32 = function (buffer) { - return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0]; - }; - - var packFloat32 = function (number) { - return packIEEE754(number, 23, 4); - }; - - var packFloat64 = function (number) { - return packIEEE754(number, 52, 8); - }; - - var addGetter = function (Constructor, key) { - defineProperty$8(Constructor[PROTOTYPE$2], key, { get: function () { return getInternalState$2(this)[key]; } }); - }; - - var get$1 = function (view, count, index, isLittleEndian) { - var intIndex = toIndex(index); - var store = getInternalState$2(view); - if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX); - var bytes = getInternalState$2(store.buffer).bytes; - var start = intIndex + store.byteOffset; - var pack = bytes.slice(start, start + count); - return isLittleEndian ? pack : pack.reverse(); - }; - - var set$1 = function (view, count, index, conversion, value, isLittleEndian) { - var intIndex = toIndex(index); - var store = getInternalState$2(view); - if (intIndex + count > store.byteLength) throw RangeError$1(WRONG_INDEX); - var bytes = getInternalState$2(store.buffer).bytes; - var start = intIndex + store.byteOffset; - var pack = conversion(+value); - for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1]; - }; - - if (!arrayBufferNative) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer, ARRAY_BUFFER); - var byteLength = toIndex(length); - setInternalState$3(this, { - bytes: arrayFill.call(new Array(byteLength), 0), - byteLength: byteLength - }); - if (!descriptors) this.byteLength = byteLength; - }; - - $DataView = function DataView(buffer, byteOffset, byteLength) { - anInstance(this, $DataView, DATA_VIEW); - anInstance(buffer, $ArrayBuffer, DATA_VIEW); - var bufferLength = getInternalState$2(buffer).byteLength; - var offset = toInteger(byteOffset); - if (offset < 0 || offset > bufferLength) throw RangeError$1('Wrong offset'); - byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); - if (offset + byteLength > bufferLength) throw RangeError$1(WRONG_LENGTH); - setInternalState$3(this, { - buffer: buffer, - byteLength: byteLength, - byteOffset: offset - }); - if (!descriptors) { - this.buffer = buffer; - this.byteLength = byteLength; - this.byteOffset = offset; - } - }; - - if (descriptors) { - addGetter($ArrayBuffer, 'byteLength'); - addGetter($DataView, 'buffer'); - addGetter($DataView, 'byteLength'); - addGetter($DataView, 'byteOffset'); - } - - redefineAll($DataView[PROTOTYPE$2], { - getInt8: function getInt8(byteOffset) { - return get$1(this, 1, byteOffset)[0] << 24 >> 24; - }, - getUint8: function getUint8(byteOffset) { - return get$1(this, 1, byteOffset)[0]; - }, - getInt16: function getInt16(byteOffset /* , littleEndian */) { - var bytes = get$1(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); - return (bytes[1] << 8 | bytes[0]) << 16 >> 16; - }, - getUint16: function getUint16(byteOffset /* , littleEndian */) { - var bytes = get$1(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined); - return bytes[1] << 8 | bytes[0]; - }, - getInt32: function getInt32(byteOffset /* , littleEndian */) { - return unpackInt32(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)); - }, - getUint32: function getUint32(byteOffset /* , littleEndian */) { - return unpackInt32(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0; - }, - getFloat32: function getFloat32(byteOffset /* , littleEndian */) { - return unpackIEEE754(get$1(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23); - }, - getFloat64: function getFloat64(byteOffset /* , littleEndian */) { - return unpackIEEE754(get$1(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52); - }, - setInt8: function setInt8(byteOffset, value) { - set$1(this, 1, byteOffset, packInt8, value); - }, - setUint8: function setUint8(byteOffset, value) { - set$1(this, 1, byteOffset, packInt8, value); - }, - setInt16: function setInt16(byteOffset, value /* , littleEndian */) { - set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); - }, - setUint16: function setUint16(byteOffset, value /* , littleEndian */) { - set$1(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined); - }, - setInt32: function setInt32(byteOffset, value /* , littleEndian */) { - set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); - }, - setUint32: function setUint32(byteOffset, value /* , littleEndian */) { - set$1(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined); - }, - setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) { - set$1(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined); - }, - setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) { - set$1(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined); - } - }); - } else { - if (!fails(function () { - NativeArrayBuffer(1); - }) || !fails(function () { - new NativeArrayBuffer(-1); // eslint-disable-line no-new - }) || fails(function () { - new NativeArrayBuffer(); // eslint-disable-line no-new - new NativeArrayBuffer(1.5); // eslint-disable-line no-new - new NativeArrayBuffer(NaN); // eslint-disable-line no-new - return NativeArrayBuffer.name != ARRAY_BUFFER; - })) { - $ArrayBuffer = function ArrayBuffer(length) { - anInstance(this, $ArrayBuffer); - return new NativeArrayBuffer(toIndex(length)); - }; - var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE$2] = NativeArrayBuffer[PROTOTYPE$2]; - for (var keys$3 = getOwnPropertyNames$2(NativeArrayBuffer), j$1 = 0, key$1; keys$3.length > j$1;) { - if (!((key$1 = keys$3[j$1++]) in $ArrayBuffer)) { - createNonEnumerableProperty($ArrayBuffer, key$1, NativeArrayBuffer[key$1]); - } - } - ArrayBufferPrototype.constructor = $ArrayBuffer; - } - - // WebKit bug - the same parent prototype for typed arrays and data view - if (objectSetPrototypeOf && objectGetPrototypeOf($DataViewPrototype) !== ObjectPrototype$2) { - objectSetPrototypeOf($DataViewPrototype, ObjectPrototype$2); - } - - // iOS Safari 7.x bug - var testView = new $DataView(new $ArrayBuffer(2)); - var nativeSetInt8 = $DataViewPrototype.setInt8; - testView.setInt8(0, 2147483648); - testView.setInt8(1, 2147483649); - if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, { - setInt8: function setInt8(byteOffset, value) { - nativeSetInt8.call(this, byteOffset, value << 24 >> 24); - }, - setUint8: function setUint8(byteOffset, value) { - nativeSetInt8.call(this, byteOffset, value << 24 >> 24); - } - }, { unsafe: true }); - } - - setToStringTag($ArrayBuffer, ARRAY_BUFFER); - setToStringTag($DataView, DATA_VIEW); - - var arrayBuffer = { - ArrayBuffer: $ArrayBuffer, - DataView: $DataView - }; - - var ARRAY_BUFFER$1 = 'ArrayBuffer'; - var ArrayBuffer$1 = arrayBuffer[ARRAY_BUFFER$1]; - var NativeArrayBuffer$1 = global_1[ARRAY_BUFFER$1]; - - // `ArrayBuffer` constructor - // https://tc39.es/ecma262/#sec-arraybuffer-constructor - _export({ global: true, forced: NativeArrayBuffer$1 !== ArrayBuffer$1 }, { - ArrayBuffer: ArrayBuffer$1 - }); - - setSpecies(ARRAY_BUFFER$1); - - var notARegexp = function (it) { - if (isRegexp(it)) { - throw TypeError("The method doesn't accept regular expressions"); - } return it; - }; - - var MATCH$2 = wellKnownSymbol('match'); - - var correctIsRegexpLogic = function (METHOD_NAME) { - var regexp = /./; - try { - '/./'[METHOD_NAME](regexp); - } catch (error1) { - try { - regexp[MATCH$2] = false; - return '/./'[METHOD_NAME](regexp); - } catch (error2) { /* empty */ } - } return false; - }; - - // `String.prototype.includes` method - // https://tc39.es/ecma262/#sec-string.prototype.includes - _export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, { - includes: function includes(searchString /* , position = 0 */) { - return !!~String(requireObjectCoercible(this)) - .indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined); - } - }); - - var non = '\u200B\u0085\u180E'; - - // check that a method works with the correct list - // of whitespaces and has a correct name - var stringTrimForced = function (METHOD_NAME) { - return fails(function () { - return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME; - }); - }; - - var $trim = stringTrim.trim; - - - // `String.prototype.trim` method - // https://tc39.es/ecma262/#sec-string.prototype.trim - _export({ target: 'String', proto: true, forced: stringTrimForced('trim') }, { - trim: function trim() { - return $trim(this); - } - }); - - var ITERATOR$2 = wellKnownSymbol('iterator'); - var SAFE_CLOSING = false; - - try { - var called = 0; - var iteratorWithReturn = { - next: function () { - return { done: !!called++ }; - }, - 'return': function () { - SAFE_CLOSING = true; - } - }; - iteratorWithReturn[ITERATOR$2] = function () { - return this; - }; - // eslint-disable-next-line no-throw-literal - Array.from(iteratorWithReturn, function () { throw 2; }); - } catch (error) { /* empty */ } - - var checkCorrectnessOfIteration = function (exec, SKIP_CLOSING) { - if (!SKIP_CLOSING && !SAFE_CLOSING) return false; - var ITERATION_SUPPORT = false; - try { - var object = {}; - object[ITERATOR$2] = function () { - return { - next: function () { - return { done: ITERATION_SUPPORT = true }; - } - }; - }; - exec(object); - } catch (error) { /* empty */ } - return ITERATION_SUPPORT; - }; - - var defineProperty$9 = objectDefineProperty.f; - - - - - - var Int8Array$1 = global_1.Int8Array; - var Int8ArrayPrototype = Int8Array$1 && Int8Array$1.prototype; - var Uint8ClampedArray = global_1.Uint8ClampedArray; - var Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype; - var TypedArray = Int8Array$1 && objectGetPrototypeOf(Int8Array$1); - var TypedArrayPrototype = Int8ArrayPrototype && objectGetPrototypeOf(Int8ArrayPrototype); - var ObjectPrototype$3 = Object.prototype; - var isPrototypeOf = ObjectPrototype$3.isPrototypeOf; - - var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag'); - var TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG'); - // Fixing native typed arrays in Opera Presto crashes the browser, see #595 - var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferNative && !!objectSetPrototypeOf && classof(global_1.opera) !== 'Opera'; - var TYPED_ARRAY_TAG_REQIRED = false; - var NAME$1; - - var TypedArrayConstructorsList = { - Int8Array: 1, - Uint8Array: 1, - Uint8ClampedArray: 1, - Int16Array: 2, - Uint16Array: 2, - Int32Array: 4, - Uint32Array: 4, - Float32Array: 4, - Float64Array: 8 - }; - - var BigIntArrayConstructorsList = { - BigInt64Array: 8, - BigUint64Array: 8 - }; - - var isView = function isView(it) { - if (!isObject(it)) return false; - var klass = classof(it); - return klass === 'DataView' - || has(TypedArrayConstructorsList, klass) - || has(BigIntArrayConstructorsList, klass); - }; - - var isTypedArray = function (it) { - if (!isObject(it)) return false; - var klass = classof(it); - return has(TypedArrayConstructorsList, klass) - || has(BigIntArrayConstructorsList, klass); - }; - - var aTypedArray = function (it) { - if (isTypedArray(it)) return it; - throw TypeError('Target is not a typed array'); - }; - - var aTypedArrayConstructor = function (C) { - if (objectSetPrototypeOf) { - if (isPrototypeOf.call(TypedArray, C)) return C; - } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME$1)) { - var TypedArrayConstructor = global_1[ARRAY]; - if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) { - return C; - } - } throw TypeError('Target is not a typed array constructor'); - }; - - var exportTypedArrayMethod = function (KEY, property, forced) { - if (!descriptors) return; - if (forced) for (var ARRAY in TypedArrayConstructorsList) { - var TypedArrayConstructor = global_1[ARRAY]; - if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) { - delete TypedArrayConstructor.prototype[KEY]; - } - } - if (!TypedArrayPrototype[KEY] || forced) { - redefine(TypedArrayPrototype, KEY, forced ? property - : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property); - } - }; - - var exportTypedArrayStaticMethod = function (KEY, property, forced) { - var ARRAY, TypedArrayConstructor; - if (!descriptors) return; - if (objectSetPrototypeOf) { - if (forced) for (ARRAY in TypedArrayConstructorsList) { - TypedArrayConstructor = global_1[ARRAY]; - if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) { - delete TypedArrayConstructor[KEY]; - } - } - if (!TypedArray[KEY] || forced) { - // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable - try { - return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array$1[KEY] || property); - } catch (error) { /* empty */ } - } else return; - } - for (ARRAY in TypedArrayConstructorsList) { - TypedArrayConstructor = global_1[ARRAY]; - if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) { - redefine(TypedArrayConstructor, KEY, property); - } - } - }; - - for (NAME$1 in TypedArrayConstructorsList) { - if (!global_1[NAME$1]) NATIVE_ARRAY_BUFFER_VIEWS = false; - } - - // WebKit bug - typed arrays constructors prototype is Object.prototype - if (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) { - // eslint-disable-next-line no-shadow - TypedArray = function TypedArray() { - throw TypeError('Incorrect invocation'); - }; - if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME$1 in TypedArrayConstructorsList) { - if (global_1[NAME$1]) objectSetPrototypeOf(global_1[NAME$1], TypedArray); - } - } - - if (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype$3) { - TypedArrayPrototype = TypedArray.prototype; - if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME$1 in TypedArrayConstructorsList) { - if (global_1[NAME$1]) objectSetPrototypeOf(global_1[NAME$1].prototype, TypedArrayPrototype); - } - } - - // WebKit bug - one more object in Uint8ClampedArray prototype chain - if (NATIVE_ARRAY_BUFFER_VIEWS && objectGetPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) { - objectSetPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype); - } - - if (descriptors && !has(TypedArrayPrototype, TO_STRING_TAG$3)) { - TYPED_ARRAY_TAG_REQIRED = true; - defineProperty$9(TypedArrayPrototype, TO_STRING_TAG$3, { get: function () { - return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined; - } }); - for (NAME$1 in TypedArrayConstructorsList) if (global_1[NAME$1]) { - createNonEnumerableProperty(global_1[NAME$1], TYPED_ARRAY_TAG, NAME$1); - } - } - - var arrayBufferViewCore = { - NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS, - TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG, - aTypedArray: aTypedArray, - aTypedArrayConstructor: aTypedArrayConstructor, - exportTypedArrayMethod: exportTypedArrayMethod, - exportTypedArrayStaticMethod: exportTypedArrayStaticMethod, - isView: isView, - isTypedArray: isTypedArray, - TypedArray: TypedArray, - TypedArrayPrototype: TypedArrayPrototype - }; - - /* eslint-disable no-new */ - - - - var NATIVE_ARRAY_BUFFER_VIEWS$1 = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; - - var ArrayBuffer$2 = global_1.ArrayBuffer; - var Int8Array$2 = global_1.Int8Array; - - var typedArrayConstructorsRequireWrappers = !NATIVE_ARRAY_BUFFER_VIEWS$1 || !fails(function () { - Int8Array$2(1); - }) || !fails(function () { - new Int8Array$2(-1); - }) || !checkCorrectnessOfIteration(function (iterable) { - new Int8Array$2(); - new Int8Array$2(null); - new Int8Array$2(1.5); - new Int8Array$2(iterable); - }, true) || fails(function () { - // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill - return new Int8Array$2(new ArrayBuffer$2(2), 1, undefined).length !== 1; - }); - - var toPositiveInteger = function (it) { - var result = toInteger(it); - if (result < 0) throw RangeError("The argument can't be less than 0"); - return result; - }; - - var toOffset = function (it, BYTES) { - var offset = toPositiveInteger(it); - if (offset % BYTES) throw RangeError('Wrong offset'); - return offset; - }; - - var ITERATOR$3 = wellKnownSymbol('iterator'); - - var getIteratorMethod = function (it) { - if (it != undefined) return it[ITERATOR$3] - || it['@@iterator'] - || iterators[classof(it)]; - }; - - var ITERATOR$4 = wellKnownSymbol('iterator'); - var ArrayPrototype$1 = Array.prototype; - - // check on default Array iterator - var isArrayIteratorMethod = function (it) { - return it !== undefined && (iterators.Array === it || ArrayPrototype$1[ITERATOR$4] === it); - }; - - var aTypedArrayConstructor$1 = arrayBufferViewCore.aTypedArrayConstructor; - - var typedArrayFrom = function from(source /* , mapfn, thisArg */) { - var O = toObject(source); - var argumentsLength = arguments.length; - var mapfn = argumentsLength > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iteratorMethod = getIteratorMethod(O); - var i, length, result, step, iterator, next; - if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) { - iterator = iteratorMethod.call(O); - next = iterator.next; - O = []; - while (!(step = next.call(iterator)).done) { - O.push(step.value); - } - } - if (mapping && argumentsLength > 2) { - mapfn = functionBindContext(mapfn, arguments[2], 2); - } - length = toLength(O.length); - result = new (aTypedArrayConstructor$1(this))(length); - for (i = 0; length > i; i++) { - result[i] = mapping ? mapfn(O[i], i) : O[i]; - } - return result; - }; - - var typedArrayConstructor = createCommonjsModule(function (module) { - - - - - - - - - - - - - - - - - - - var getOwnPropertyNames = objectGetOwnPropertyNames.f; - - var forEach = arrayIteration.forEach; - - - - - - - var getInternalState = internalState.get; - var setInternalState = internalState.set; - var nativeDefineProperty = objectDefineProperty.f; - var nativeGetOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f; - var round = Math.round; - var RangeError = global_1.RangeError; - var ArrayBuffer = arrayBuffer.ArrayBuffer; - var DataView = arrayBuffer.DataView; - var NATIVE_ARRAY_BUFFER_VIEWS = arrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS; - var TYPED_ARRAY_TAG = arrayBufferViewCore.TYPED_ARRAY_TAG; - var TypedArray = arrayBufferViewCore.TypedArray; - var TypedArrayPrototype = arrayBufferViewCore.TypedArrayPrototype; - var aTypedArrayConstructor = arrayBufferViewCore.aTypedArrayConstructor; - var isTypedArray = arrayBufferViewCore.isTypedArray; - var BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'; - var WRONG_LENGTH = 'Wrong length'; - - var fromList = function (C, list) { - var index = 0; - var length = list.length; - var result = new (aTypedArrayConstructor(C))(length); - while (length > index) result[index] = list[index++]; - return result; - }; - - var addGetter = function (it, key) { - nativeDefineProperty(it, key, { get: function () { - return getInternalState(this)[key]; - } }); - }; - - var isArrayBuffer = function (it) { - var klass; - return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer'; - }; - - var isTypedArrayIndex = function (target, key) { - return isTypedArray(target) - && typeof key != 'symbol' - && key in target - && String(+key) == String(key); - }; - - var wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) { - return isTypedArrayIndex(target, key = toPrimitive(key, true)) - ? createPropertyDescriptor(2, target[key]) - : nativeGetOwnPropertyDescriptor(target, key); - }; - - var wrappedDefineProperty = function defineProperty(target, key, descriptor) { - if (isTypedArrayIndex(target, key = toPrimitive(key, true)) - && isObject(descriptor) - && has(descriptor, 'value') - && !has(descriptor, 'get') - && !has(descriptor, 'set') - // TODO: add validation descriptor w/o calling accessors - && !descriptor.configurable - && (!has(descriptor, 'writable') || descriptor.writable) - && (!has(descriptor, 'enumerable') || descriptor.enumerable) - ) { - target[key] = descriptor.value; - return target; - } return nativeDefineProperty(target, key, descriptor); - }; - - if (descriptors) { - if (!NATIVE_ARRAY_BUFFER_VIEWS) { - objectGetOwnPropertyDescriptor.f = wrappedGetOwnPropertyDescriptor; - objectDefineProperty.f = wrappedDefineProperty; - addGetter(TypedArrayPrototype, 'buffer'); - addGetter(TypedArrayPrototype, 'byteOffset'); - addGetter(TypedArrayPrototype, 'byteLength'); - addGetter(TypedArrayPrototype, 'length'); - } - - _export({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, { - getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor, - defineProperty: wrappedDefineProperty - }); - - module.exports = function (TYPE, wrapper, CLAMPED) { - var BYTES = TYPE.match(/\d+$/)[0] / 8; - var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array'; - var GETTER = 'get' + TYPE; - var SETTER = 'set' + TYPE; - var NativeTypedArrayConstructor = global_1[CONSTRUCTOR_NAME]; - var TypedArrayConstructor = NativeTypedArrayConstructor; - var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype; - var exported = {}; - - var getter = function (that, index) { - var data = getInternalState(that); - return data.view[GETTER](index * BYTES + data.byteOffset, true); - }; - - var setter = function (that, index, value) { - var data = getInternalState(that); - if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF; - data.view[SETTER](index * BYTES + data.byteOffset, value, true); - }; - - var addElement = function (that, index) { - nativeDefineProperty(that, index, { - get: function () { - return getter(this, index); - }, - set: function (value) { - return setter(this, index, value); - }, - enumerable: true - }); - }; - - if (!NATIVE_ARRAY_BUFFER_VIEWS) { - TypedArrayConstructor = wrapper(function (that, data, offset, $length) { - anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME); - var index = 0; - var byteOffset = 0; - var buffer, byteLength, length; - if (!isObject(data)) { - length = toIndex(data); - byteLength = length * BYTES; - buffer = new ArrayBuffer(byteLength); - } else if (isArrayBuffer(data)) { - buffer = data; - byteOffset = toOffset(offset, BYTES); - var $len = data.byteLength; - if ($length === undefined) { - if ($len % BYTES) throw RangeError(WRONG_LENGTH); - byteLength = $len - byteOffset; - if (byteLength < 0) throw RangeError(WRONG_LENGTH); - } else { - byteLength = toLength($length) * BYTES; - if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH); - } - length = byteLength / BYTES; - } else if (isTypedArray(data)) { - return fromList(TypedArrayConstructor, data); - } else { - return typedArrayFrom.call(TypedArrayConstructor, data); - } - setInternalState(that, { - buffer: buffer, - byteOffset: byteOffset, - byteLength: byteLength, - length: length, - view: new DataView(buffer) - }); - while (index < length) addElement(that, index++); - }); - - if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray); - TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = objectCreate(TypedArrayPrototype); - } else if (typedArrayConstructorsRequireWrappers) { - TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) { - anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME); - return inheritIfRequired(function () { - if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data)); - if (isArrayBuffer(data)) return $length !== undefined - ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length) - : typedArrayOffset !== undefined - ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES)) - : new NativeTypedArrayConstructor(data); - if (isTypedArray(data)) return fromList(TypedArrayConstructor, data); - return typedArrayFrom.call(TypedArrayConstructor, data); - }(), dummy, TypedArrayConstructor); - }); - - if (objectSetPrototypeOf) objectSetPrototypeOf(TypedArrayConstructor, TypedArray); - forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) { - if (!(key in TypedArrayConstructor)) { - createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]); - } - }); - TypedArrayConstructor.prototype = TypedArrayConstructorPrototype; - } - - if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor); - } - - if (TYPED_ARRAY_TAG) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME); - } - - exported[CONSTRUCTOR_NAME] = TypedArrayConstructor; - - _export({ - global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS - }, exported); - - if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) { - createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES); - } - - if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) { - createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES); - } - - setSpecies(CONSTRUCTOR_NAME); - }; - } else module.exports = function () { /* empty */ }; - }); - - // `Uint8Array` constructor - // https://tc39.es/ecma262/#sec-typedarray-objects - typedArrayConstructor('Uint8', function (init) { - return function Uint8Array(data, byteOffset, length) { - return init(this, data, byteOffset, length); - }; - }); - - var min$5 = Math.min; - - // `Array.prototype.copyWithin` method implementation - // https://tc39.es/ecma262/#sec-array.prototype.copywithin - var arrayCopyWithin = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) { - var O = toObject(this); - var len = toLength(O.length); - var to = toAbsoluteIndex(target, len); - var from = toAbsoluteIndex(start, len); - var end = arguments.length > 2 ? arguments[2] : undefined; - var count = min$5((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to); - var inc = 1; - if (from < to && to < from + count) { - inc = -1; - from += count - 1; - to += count - 1; - } - while (count-- > 0) { - if (from in O) O[to] = O[from]; - else delete O[to]; - to += inc; - from += inc; - } return O; - }; - - var aTypedArray$1 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$1 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.copyWithin` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin - exportTypedArrayMethod$1('copyWithin', function copyWithin(target, start /* , end */) { - return arrayCopyWithin.call(aTypedArray$1(this), target, start, arguments.length > 2 ? arguments[2] : undefined); - }); - - var $every = arrayIteration.every; - - var aTypedArray$2 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$2 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.every` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.every - exportTypedArrayMethod$2('every', function every(callbackfn /* , thisArg */) { - return $every(aTypedArray$2(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }); - - var aTypedArray$3 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$3 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.fill` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill - // eslint-disable-next-line no-unused-vars - exportTypedArrayMethod$3('fill', function fill(value /* , start, end */) { - return arrayFill.apply(aTypedArray$3(this), arguments); - }); - - var $filter$1 = arrayIteration.filter; - - - var aTypedArray$4 = arrayBufferViewCore.aTypedArray; - var aTypedArrayConstructor$2 = arrayBufferViewCore.aTypedArrayConstructor; - var exportTypedArrayMethod$4 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.filter` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter - exportTypedArrayMethod$4('filter', function filter(callbackfn /* , thisArg */) { - var list = $filter$1(aTypedArray$4(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - var C = speciesConstructor(this, this.constructor); - var index = 0; - var length = list.length; - var result = new (aTypedArrayConstructor$2(C))(length); - while (length > index) result[index] = list[index++]; - return result; - }); - - var $find = arrayIteration.find; - - var aTypedArray$5 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$5 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.find` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.find - exportTypedArrayMethod$5('find', function find(predicate /* , thisArg */) { - return $find(aTypedArray$5(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }); - - var $findIndex = arrayIteration.findIndex; - - var aTypedArray$6 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$6 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.findIndex` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex - exportTypedArrayMethod$6('findIndex', function findIndex(predicate /* , thisArg */) { - return $findIndex(aTypedArray$6(this), predicate, arguments.length > 1 ? arguments[1] : undefined); - }); - - var $forEach$2 = arrayIteration.forEach; - - var aTypedArray$7 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$7 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.forEach` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach - exportTypedArrayMethod$7('forEach', function forEach(callbackfn /* , thisArg */) { - $forEach$2(aTypedArray$7(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }); - - var $includes$1 = arrayIncludes.includes; - - var aTypedArray$8 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$8 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.includes` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes - exportTypedArrayMethod$8('includes', function includes(searchElement /* , fromIndex */) { - return $includes$1(aTypedArray$8(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }); - - var $indexOf = arrayIncludes.indexOf; - - var aTypedArray$9 = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$9 = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.indexOf` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof - exportTypedArrayMethod$9('indexOf', function indexOf(searchElement /* , fromIndex */) { - return $indexOf(aTypedArray$9(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); - }); - - var ITERATOR$5 = wellKnownSymbol('iterator'); - var Uint8Array$1 = global_1.Uint8Array; - var arrayValues = es_array_iterator.values; - var arrayKeys = es_array_iterator.keys; - var arrayEntries = es_array_iterator.entries; - var aTypedArray$a = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$a = arrayBufferViewCore.exportTypedArrayMethod; - var nativeTypedArrayIterator = Uint8Array$1 && Uint8Array$1.prototype[ITERATOR$5]; - - var CORRECT_ITER_NAME = !!nativeTypedArrayIterator - && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined); - - var typedArrayValues = function values() { - return arrayValues.call(aTypedArray$a(this)); - }; - - // `%TypedArray%.prototype.entries` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries - exportTypedArrayMethod$a('entries', function entries() { - return arrayEntries.call(aTypedArray$a(this)); - }); - // `%TypedArray%.prototype.keys` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys - exportTypedArrayMethod$a('keys', function keys() { - return arrayKeys.call(aTypedArray$a(this)); - }); - // `%TypedArray%.prototype.values` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.values - exportTypedArrayMethod$a('values', typedArrayValues, !CORRECT_ITER_NAME); - // `%TypedArray%.prototype[@@iterator]` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator - exportTypedArrayMethod$a(ITERATOR$5, typedArrayValues, !CORRECT_ITER_NAME); - - var aTypedArray$b = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$b = arrayBufferViewCore.exportTypedArrayMethod; - var $join = [].join; - - // `%TypedArray%.prototype.join` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.join - // eslint-disable-next-line no-unused-vars - exportTypedArrayMethod$b('join', function join(separator) { - return $join.apply(aTypedArray$b(this), arguments); - }); - - var min$6 = Math.min; - var nativeLastIndexOf = [].lastIndexOf; - var NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0; - var STRICT_METHOD$2 = arrayMethodIsStrict('lastIndexOf'); - // For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method - var USES_TO_LENGTH$6 = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 }); - var FORCED$3 = NEGATIVE_ZERO || !STRICT_METHOD$2 || !USES_TO_LENGTH$6; - - // `Array.prototype.lastIndexOf` method implementation - // https://tc39.es/ecma262/#sec-array.prototype.lastindexof - var arrayLastIndexOf = FORCED$3 ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) { - // convert -0 to +0 - if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0; - var O = toIndexedObject(this); - var length = toLength(O.length); - var index = length - 1; - if (arguments.length > 1) index = min$6(index, toInteger(arguments[1])); - if (index < 0) index = length + index; - for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0; - return -1; - } : nativeLastIndexOf; - - var aTypedArray$c = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$c = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.lastIndexOf` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof - // eslint-disable-next-line no-unused-vars - exportTypedArrayMethod$c('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) { - return arrayLastIndexOf.apply(aTypedArray$c(this), arguments); - }); - - var $map$1 = arrayIteration.map; - - - var aTypedArray$d = arrayBufferViewCore.aTypedArray; - var aTypedArrayConstructor$3 = arrayBufferViewCore.aTypedArrayConstructor; - var exportTypedArrayMethod$d = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.map` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.map - exportTypedArrayMethod$d('map', function map(mapfn /* , thisArg */) { - return $map$1(aTypedArray$d(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) { - return new (aTypedArrayConstructor$3(speciesConstructor(O, O.constructor)))(length); - }); - }); - - // `Array.prototype.{ reduce, reduceRight }` methods implementation - var createMethod$4 = function (IS_RIGHT) { - return function (that, callbackfn, argumentsLength, memo) { - aFunction$1(callbackfn); - var O = toObject(that); - var self = indexedObject(O); - var length = toLength(O.length); - var index = IS_RIGHT ? length - 1 : 0; - var i = IS_RIGHT ? -1 : 1; - if (argumentsLength < 2) while (true) { - if (index in self) { - memo = self[index]; - index += i; - break; - } - index += i; - if (IS_RIGHT ? index < 0 : length <= index) { - throw TypeError('Reduce of empty array with no initial value'); - } - } - for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) { - memo = callbackfn(memo, self[index], index, O); - } - return memo; - }; - }; - - var arrayReduce = { - // `Array.prototype.reduce` method - // https://tc39.es/ecma262/#sec-array.prototype.reduce - left: createMethod$4(false), - // `Array.prototype.reduceRight` method - // https://tc39.es/ecma262/#sec-array.prototype.reduceright - right: createMethod$4(true) - }; - - var $reduce = arrayReduce.left; - - var aTypedArray$e = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$e = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.reduce` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce - exportTypedArrayMethod$e('reduce', function reduce(callbackfn /* , initialValue */) { - return $reduce(aTypedArray$e(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); - }); - - var $reduceRight = arrayReduce.right; - - var aTypedArray$f = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$f = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.reduceRicht` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright - exportTypedArrayMethod$f('reduceRight', function reduceRight(callbackfn /* , initialValue */) { - return $reduceRight(aTypedArray$f(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined); - }); - - var aTypedArray$g = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$g = arrayBufferViewCore.exportTypedArrayMethod; - var floor$3 = Math.floor; - - // `%TypedArray%.prototype.reverse` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse - exportTypedArrayMethod$g('reverse', function reverse() { - var that = this; - var length = aTypedArray$g(that).length; - var middle = floor$3(length / 2); - var index = 0; - var value; - while (index < middle) { - value = that[index]; - that[index++] = that[--length]; - that[length] = value; - } return that; - }); - - var aTypedArray$h = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$h = arrayBufferViewCore.exportTypedArrayMethod; - - var FORCED$4 = fails(function () { - // eslint-disable-next-line no-undef - new Int8Array(1).set({}); - }); - - // `%TypedArray%.prototype.set` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.set - exportTypedArrayMethod$h('set', function set(arrayLike /* , offset */) { - aTypedArray$h(this); - var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1); - var length = this.length; - var src = toObject(arrayLike); - var len = toLength(src.length); - var index = 0; - if (len + offset > length) throw RangeError('Wrong length'); - while (index < len) this[offset + index] = src[index++]; - }, FORCED$4); - - var aTypedArray$i = arrayBufferViewCore.aTypedArray; - var aTypedArrayConstructor$4 = arrayBufferViewCore.aTypedArrayConstructor; - var exportTypedArrayMethod$i = arrayBufferViewCore.exportTypedArrayMethod; - var $slice = [].slice; - - var FORCED$5 = fails(function () { - // eslint-disable-next-line no-undef - new Int8Array(1).slice(); - }); - - // `%TypedArray%.prototype.slice` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice - exportTypedArrayMethod$i('slice', function slice(start, end) { - var list = $slice.call(aTypedArray$i(this), start, end); - var C = speciesConstructor(this, this.constructor); - var index = 0; - var length = list.length; - var result = new (aTypedArrayConstructor$4(C))(length); - while (length > index) result[index] = list[index++]; - return result; - }, FORCED$5); - - var $some = arrayIteration.some; - - var aTypedArray$j = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$j = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.some` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.some - exportTypedArrayMethod$j('some', function some(callbackfn /* , thisArg */) { - return $some(aTypedArray$j(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); - }); - - var aTypedArray$k = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$k = arrayBufferViewCore.exportTypedArrayMethod; - var $sort = [].sort; - - // `%TypedArray%.prototype.sort` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort - exportTypedArrayMethod$k('sort', function sort(comparefn) { - return $sort.call(aTypedArray$k(this), comparefn); - }); - - var aTypedArray$l = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$l = arrayBufferViewCore.exportTypedArrayMethod; - - // `%TypedArray%.prototype.subarray` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray - exportTypedArrayMethod$l('subarray', function subarray(begin, end) { - var O = aTypedArray$l(this); - var length = O.length; - var beginIndex = toAbsoluteIndex(begin, length); - return new (speciesConstructor(O, O.constructor))( - O.buffer, - O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT, - toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex) - ); - }); - - var Int8Array$3 = global_1.Int8Array; - var aTypedArray$m = arrayBufferViewCore.aTypedArray; - var exportTypedArrayMethod$m = arrayBufferViewCore.exportTypedArrayMethod; - var $toLocaleString = [].toLocaleString; - var $slice$1 = [].slice; - - // iOS Safari 6.x fails here - var TO_LOCALE_STRING_BUG = !!Int8Array$3 && fails(function () { - $toLocaleString.call(new Int8Array$3(1)); - }); - - var FORCED$6 = fails(function () { - return [1, 2].toLocaleString() != new Int8Array$3([1, 2]).toLocaleString(); - }) || !fails(function () { - Int8Array$3.prototype.toLocaleString.call([1, 2]); - }); - - // `%TypedArray%.prototype.toLocaleString` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring - exportTypedArrayMethod$m('toLocaleString', function toLocaleString() { - return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice$1.call(aTypedArray$m(this)) : aTypedArray$m(this), arguments); - }, FORCED$6); - - var exportTypedArrayMethod$n = arrayBufferViewCore.exportTypedArrayMethod; - - - - var Uint8Array$2 = global_1.Uint8Array; - var Uint8ArrayPrototype = Uint8Array$2 && Uint8Array$2.prototype || {}; - var arrayToString = [].toString; - var arrayJoin = [].join; - - if (fails(function () { arrayToString.call({}); })) { - arrayToString = function toString() { - return arrayJoin.call(this); - }; - } - - var IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString; - - // `%TypedArray%.prototype.toString` method - // https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring - exportTypedArrayMethod$n('toString', arrayToString, IS_NOT_ARRAY_METHOD); - - // `URL.prototype.toJSON` method - // https://url.spec.whatwg.org/#dom-url-tojson - _export({ target: 'URL', proto: true, enumerable: true }, { - toJSON: function toJSON() { - return URL.prototype.toString.call(this); - } - }); - - var lookup = []; - var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited = false; - - function init() { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } - - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; - } - - function toByteArray(b64) { - if (!inited) { - init(); - } - - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4'); - } // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - - - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data - - arr = new Arr(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars - - l = placeHolders > 0 ? len - 4 : len; - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = tmp >> 16 & 0xFF; - arr[L++] = tmp >> 8 & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; - arr[L++] = tmp >> 8 & 0xFF; - arr[L++] = tmp & 0xFF; - } - - return arr; - } - - function tripletToBase64(num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]; - } - - function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; - output.push(tripletToBase64(tmp)); - } - - return output.join(''); - } - - function fromByteArray(uint8) { - if (!inited) { - init(); - } - - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } // pad the end with zeros, but make sure to not forget the extra bytes - - - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[tmp << 4 & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - output += lookup[tmp >> 10]; - output += lookup[tmp >> 4 & 0x3F]; - output += lookup[tmp << 2 & 0x3F]; - output += '='; - } - - parts.push(output); - return parts.join(''); - } - - function read(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - } - function write(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = e << mLen | m; - eLen += mLen; - - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - } - - var toString$2 = {}.toString; - var isArray$1 = Array.isArray || function (arr) { - return toString$2.call(arr) == '[object Array]'; - }; - - var INSPECT_MAX_BYTES = 50; - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - - Buffer.TYPED_ARRAY_SUPPORT = global$2.TYPED_ARRAY_SUPPORT !== undefined ? global$2.TYPED_ARRAY_SUPPORT : true; - - function kMaxLength() { - return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; - } - - function createBuffer(that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length'); - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer(length); - } - - that.length = length; - } - - return that; - } - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - - function Buffer(arg, encodingOrOffset, length) { - if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { - return new Buffer(arg, encodingOrOffset, length); - } // Common case. - - - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error('If encoding is specified then the first argument must be a string'); - } - - return allocUnsafe(this, arg); - } - - return from(this, arg, encodingOrOffset, length); - } - Buffer.poolSize = 8192; // not used by this implementation - // TODO: Legacy, not needed anymore. Remove in next major version. - - Buffer._augment = function (arr) { - arr.__proto__ = Buffer.prototype; - return arr; - }; - - function from(that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length); - } - - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset); - } - - return fromObject(that, value); - } - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - - - Buffer.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length); - }; - - if (Buffer.TYPED_ARRAY_SUPPORT) { - Buffer.prototype.__proto__ = Uint8Array.prototype; - Buffer.__proto__ = Uint8Array; - } - - function assertSize(size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number'); - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative'); - } - } - - function alloc(that, size, fill, encoding) { - assertSize(size); - - if (size <= 0) { - return createBuffer(that, size); - } - - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); - } - - return createBuffer(that, size); - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - - - Buffer.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding); - }; - - function allocUnsafe(that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - - if (!Buffer.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - - return that; - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - - - Buffer.allocUnsafe = function (size) { - return allocUnsafe(null, size); - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - - - Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size); - }; - - function fromString(that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } - - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); - var actual = that.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that; - } - - function fromArrayLike(that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - - return that; - } - - function fromArrayBuffer(that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds'); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds'); - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - - return that; - } - - function fromObject(that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); - - if (that.length === 0) { - return that; - } - - obj.copy(that, 0, 0, len); - return that; - } - - if (obj) { - if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0); - } - - return fromArrayLike(that, obj); - } - - if (obj.type === 'Buffer' && isArray$1(obj.data)) { - return fromArrayLike(that, obj.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); - } - - function checked(length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes'); - } - - return length | 0; - } - Buffer.isBuffer = isBuffer; - - function internalIsBuffer(b) { - return !!(b != null && b._isBuffer); - } - - Buffer.compare = function compare(a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers'); - } - - if (a === b) return 0; - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true; - - default: - return false; - } - }; - - Buffer.concat = function concat(list, length) { - if (!isArray$1(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - if (list.length === 0) { - return Buffer.alloc(0); - } - - var i; - - if (length === undefined) { - length = 0; - - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer.allocUnsafe(length); - var pos = 0; - - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - buf.copy(buffer, pos); - pos += buf.length; - } - - return buffer; - }; - - function byteLength(string, encoding) { - if (internalIsBuffer(string)) { - return string.length; - } - - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength; - } - - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0; // Use a for loop to avoid recursion - - var loweredCase = false; - - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len; - - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length; - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2; - - case 'hex': - return len >>> 1; - - case 'base64': - return base64ToBytes(string).length; - - default: - if (loweredCase) return utf8ToBytes(string).length; // assume utf8 - - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - - Buffer.byteLength = byteLength; - - function slowToString(encoding, start, end) { - var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - - if (start === undefined || start < 0) { - start = 0; - } // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - - - if (start > this.length) { - return ''; - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return ''; - } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - - - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return ''; - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end); - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end); - - case 'ascii': - return asciiSlice(this, start, end); - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end); - - case 'base64': - return base64Slice(this, start, end); - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end); - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } - } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - - - Buffer.prototype._isBuffer = true; - - function swap(b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer.prototype.swap16 = function swap16() { - var len = this.length; - - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits'); - } - - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - - return this; - }; - - Buffer.prototype.swap32 = function swap32() { - var len = this.length; - - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits'); - } - - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - - return this; - }; - - Buffer.prototype.swap64 = function swap64() { - var len = this.length; - - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits'); - } - - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - - return this; - }; - - Buffer.prototype.toString = function toString() { - var length = this.length | 0; - if (length === 0) return ''; - if (arguments.length === 0) return utf8Slice(this, 0, length); - return slowToString.apply(this, arguments); - }; - - Buffer.prototype.equals = function equals(b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer'); - if (this === b) return true; - return Buffer.compare(this, b) === 0; - }; - - Buffer.prototype.inspect = function inspect() { - var str = ''; - var max = INSPECT_MAX_BYTES; - - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - - return ''; - }; - - Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer'); - } - - if (start === undefined) { - start = 0; - } - - if (end === undefined) { - end = target ? target.length : 0; - } - - if (thisStart === undefined) { - thisStart = 0; - } - - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index'); - } - - if (thisStart >= thisEnd && start >= end) { - return 0; - } - - if (thisStart >= thisEnd) { - return -1; - } - - if (start >= end) { - return 1; - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) return 0; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - - - function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1; // Normalize byteOffset - - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - - byteOffset = +byteOffset; // Coerce to Number. - - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } // Normalize byteOffset: negative offsets start from the end of the buffer - - - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - - if (byteOffset >= buffer.length) { - if (dir) return -1;else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0;else return -1; - } // Normalize val - - - if (typeof val === 'string') { - val = Buffer.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf - - - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - - return arrayIndexOf(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - - if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - - return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); - } - - throw new TypeError('val must be string, number or Buffer'); - } - - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - - if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1; - } - - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read(buf, i) { - if (indexSize === 1) { - return buf[i]; - } else { - return buf.readUInt16BE(i * indexSize); - } - } - - var i; - - if (dir) { - var foundIndex = -1; - - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - - for (i = byteOffset; i >= 0; i--) { - var found = true; - - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - - if (found) return i; - } - } - - return -1; - } - - Buffer.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - - Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - - function hexWrite(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - - if (!length) { - length = remaining; - } else { - length = Number(length); - - if (length > remaining) { - length = remaining; - } - } // must be an even number of digits - - - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); - - if (length > strLen / 2) { - length = strLen / 2; - } - - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i; - buf[offset + i] = parsed; - } - - return i; - } - - function utf8Write(buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); - } - - function asciiWrite(buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length); - } - - function latin1Write(buf, string, offset, length) { - return asciiWrite(buf, string, offset, length); - } - - function base64Write(buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length); - } - - function ucs2Write(buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); - } - - Buffer.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } // legacy write(string, encoding, offset, length) - remove in v0.13 - - } else { - throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds'); - } - - if (!encoding) encoding = 'utf8'; - var loweredCase = false; - - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length); - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length); - - case 'ascii': - return asciiWrite(this, string, offset, length); - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length); - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length); - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length); - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer.prototype.toJSON = function toJSON() { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf); - } else { - return fromByteArray(buf.slice(start, end)); - } - } - - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - - break; - - case 2: - secondByte = buf[i + 1]; - - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; - - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - - break; - - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; - - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - - break; - - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; - - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - - - var MAX_ARGUMENTS_LENGTH = 0x1000; - - function decodeCodePointsArray(codePoints) { - var len = codePoints.length; - - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } // Decode in chunks to avoid "call stack size exceeded". - - - var res = ''; - var i = 0; - - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)); - } - - return res; - } - - function asciiSlice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - - return ret; - } - - function latin1Slice(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - - return ret; - } - - function hexSlice(buf, start, end) { - var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - var out = ''; - - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - - return out; - } - - function utf16leSlice(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - - return res; - } - - Buffer.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - var newBuf; - - if (Buffer.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer(sliceLen, undefined); - - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - return newBuf; - }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - - - function checkOffset(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); - } - - Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val; - }; - - Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - - Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - - Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - - Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; - }; - - Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - - Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val; - }; - - Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val; - }; - - Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return this[offset]; - return (0xff - this[offset] + 1) * -1; - }; - - Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | this[offset + 1] << 8; - return val & 0x8000 ? val | 0xFFFF0000 : val; - }; - - Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | this[offset] << 8; - return val & 0x8000 ? val | 0xFFFF0000 : val; - }; - - Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - - Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - - Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4); - }; - - Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4); - }; - - Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8); - }; - - Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8); - }; - - function checkInt(buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - } - - Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = value & 0xff; - return offset + 1; - }; - - function objectWriteUInt16(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - } else { - objectWriteUInt16(this, value, offset, true); - } - - return offset + 2; - }; - - Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - } else { - objectWriteUInt16(this, value, offset, false); - } - - return offset + 2; - }; - - function objectWriteUInt32(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; - } - } - - Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - } else { - objectWriteUInt32(this, value, offset, true); - } - - return offset + 4; - }; - - Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - } else { - objectWriteUInt32(this, value, offset, false); - } - - return offset + 4; - }; - - Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - } else { - objectWriteUInt16(this, value, offset, true); - } - - return offset + 2; - }; - - Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - } else { - objectWriteUInt16(this, value, offset, false); - } - - return offset + 2; - }; - - Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - } else { - objectWriteUInt32(this, value, offset, true); - } - - return offset + 4; - }; - - Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - - if (Buffer.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - } else { - objectWriteUInt32(this, value, offset, false); - } - - return offset + 4; - }; - - function checkIEEE754(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - if (offset < 0) throw new RangeError('Index out of range'); - } - - function writeFloat(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - - Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert); - }; - - Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert); - }; - - function writeDouble(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - - Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert); - }; - - Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - - - Buffer.prototype.copy = function copy(target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done - - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions - - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds'); - } - - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); - if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? - - if (end > this.length) end = this.length; - - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); - } - - return len; - }; // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - - - Buffer.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - - if (val.length === 1) { - var code = val.charCodeAt(0); - - if (code < 256) { - val = code; - } - } - - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string'); - } - - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding); - } - } else if (typeof val === 'number') { - val = val & 255; - } // Invalid ranges are not set to a default, so can range check early. - - - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index'); - } - - if (end <= start) { - return this; - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) val = 0; - var i; - - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); - var len = bytes.length; - - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this; - }; // HELPER FUNCTIONS - // ================ - - - var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - - function base64clean(str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); // Node converts strings with length < 2 to '' - - if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - - while (str.length % 4 !== 0) { - str = str + '='; - } - - return str; - } - - function stringtrim(str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); - } - - function toHex(n) { - if (n < 16) return '0' + n.toString(16); - return n.toString(16); - } - - function utf8ToBytes(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component - - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } // valid lead - - - leadSurrogate = codePoint; - continue; - } // 2 leads in a row - - - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue; - } // valid surrogate pair - - - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; // encode utf8 - - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else { - throw new Error('Invalid code point'); - } - } - - return bytes; - } - - function asciiToBytes(str) { - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - - return byteArray; - } - - function utf16leToBytes(str, units) { - var c, hi, lo; - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray; - } - - function base64ToBytes(str) { - return toByteArray(base64clean(str)); - } - - function blitBuffer(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - - return i; - } - - function isnan(val) { - return val !== val; // eslint-disable-line no-self-compare - } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - - - function isBuffer(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); - } - - function isFastBuffer(obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); - } // For Node v0.10 support. Remove this eventually. - - - function isSlowBuffer(obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)); - } - - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js - - function defaultSetTimout$1() { - throw new Error('setTimeout has not been defined'); - } - - function defaultClearTimeout$1() { - throw new Error('clearTimeout has not been defined'); - } - - var cachedSetTimeout$1 = defaultSetTimout$1; - var cachedClearTimeout$1 = defaultClearTimeout$1; - - if (typeof global$2.setTimeout === 'function') { - cachedSetTimeout$1 = setTimeout; - } - - if (typeof global$2.clearTimeout === 'function') { - cachedClearTimeout$1 = clearTimeout; - } - - function runTimeout$1(fun) { - if (cachedSetTimeout$1 === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } // if setTimeout wasn't available but was latter defined - - - if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) { - cachedSetTimeout$1 = setTimeout; - return setTimeout(fun, 0); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout$1(fun, 0); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout$1.call(null, fun, 0); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout$1.call(this, fun, 0); - } - } - } - - function runClearTimeout$1(marker) { - if (cachedClearTimeout$1 === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } // if clearTimeout wasn't available but was latter defined - - - if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) { - cachedClearTimeout$1 = clearTimeout; - return clearTimeout(marker); - } - - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout$1(marker); - } catch (e) { - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout$1.call(null, marker); - } catch (e) { - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout$1.call(this, marker); - } - } - } - - var queue$1 = []; - var draining$1 = false; - var currentQueue$1; - var queueIndex$1 = -1; - - function cleanUpNextTick$1() { - if (!draining$1 || !currentQueue$1) { - return; - } - - draining$1 = false; - - if (currentQueue$1.length) { - queue$1 = currentQueue$1.concat(queue$1); - } else { - queueIndex$1 = -1; - } - - if (queue$1.length) { - drainQueue$1(); - } - } - - function drainQueue$1() { - if (draining$1) { - return; - } - - var timeout = runTimeout$1(cleanUpNextTick$1); - draining$1 = true; - var len = queue$1.length; - - while (len) { - currentQueue$1 = queue$1; - queue$1 = []; - - while (++queueIndex$1 < len) { - if (currentQueue$1) { - currentQueue$1[queueIndex$1].run(); - } - } - - queueIndex$1 = -1; - len = queue$1.length; - } - - currentQueue$1 = null; - draining$1 = false; - runClearTimeout$1(timeout); - } - - function nextTick$1(fun) { - var args = new Array(arguments.length - 1); - - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - - queue$1.push(new Item$1(fun, args)); - - if (queue$1.length === 1 && !draining$1) { - runTimeout$1(drainQueue$1); - } - } // v8 likes predictible objects - - - function Item$1(fun, array) { - this.fun = fun; - this.array = array; - } - - Item$1.prototype.run = function () { - this.fun.apply(null, this.array); - }; - - - var performance$1 = global$2.performance || {}; - - performance$1.now || performance$1.mozNow || performance$1.msNow || performance$1.oNow || performance$1.webkitNow || function () { - return new Date().getTime(); - }; // generate timestamp or delta - - var inherits; - - if (typeof Object.create === 'function') { - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - - var TempCtor = function TempCtor() {}; - - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; - } - - var inherits$1 = inherits; - - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString(f)) { - var objects = []; - - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function (x) { - if (x === '%%') return '%'; - if (i >= len) return x; - - switch (x) { - case '%s': - return String(args[i++]); - - case '%d': - return Number(args[i++]); - - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - - default: - return x; - } - }); - - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject$1(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - - return str; - } - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$2.process)) { - return function () { - return deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - - function deprecated() { - if (!warned) { - { - console.error(msg); - } - - warned = true; - } - - return fn.apply(this, arguments); - } - - return deprecated; - } - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) debugEnviron = ''; - set = set.toUpperCase(); - - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - - debugs[set] = function () { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function () {}; - } - } - - return debugs[set]; - } - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - - /* legacy: obj, showHidden, depth, colors*/ - - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; // legacy... - - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } // set default options - - - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); - } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - - inspect.colors = { - 'bold': [1, 22], - 'italic': [3, 23], - 'underline': [4, 24], - 'inverse': [7, 27], - 'white': [37, 39], - 'grey': [90, 39], - 'black': [30, 39], - 'blue': [34, 39], - 'cyan': [36, 39], - 'green': [32, 39], - 'magenta': [35, 39], - 'red': [31, 39], - 'yellow': [33, 39] - }; // Don't use 'blue' not visible on cmd.exe - - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; - - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return "\x1B[" + inspect.colors[style][0] + 'm' + str + "\x1B[" + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } - - function stylizeNoColor(str, styleType) { - return str; - } - - function arrayToHash(array) { - var hash = {}; - array.forEach(function (val, idx) { - hash[val] = true; - }); - return hash; - } - - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special - value.inspect !== inspect && // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - - return ret; - } // Primitive types cannot have properties - - - var primitive = formatPrimitive(ctx, value); - - if (primitive) { - return primitive; - } // Look up the keys of the object. - - - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - - - if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } // Some type of object without properties can be shortcutted. - - - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - - if (isError(value)) { - return formatError(value); - } - } - - var base = '', - array = false, - braces = ['{', '}']; // Make Array say that they are Array - - if (isArray$2(value)) { - array = true; - braces = ['[', ']']; - } // Make functions say that they are functions - - - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } // Make RegExps say that they are RegExps - - - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } // Make dates with properties first say the date - - - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } // Make error with message first say the error - - - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - var output; - - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function (key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - return reduceToSingleString(output, base, braces); - } - - function formatPrimitive(ctx, value) { - if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); - - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '').replace(/'/g, "\\'").replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - - if (isNumber(value)) return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. - - if (isNull(value)) return ctx.stylize('null', 'null'); - } - - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } - - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty$1(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); - } else { - output.push(''); - } - } - - keys.forEach(function (key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); - } - }); - return output; - } - - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { - value: value[key] - }; - - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - - if (!hasOwnProperty$1(visibleKeys, key)) { - name = '[' + key + ']'; - } - - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function (line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - - name = JSON.stringify('' + key); - - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'").replace(/\\"/g, '"').replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; - } - - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function (prev, cur) { - if (cur.indexOf('\n') >= 0) ; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - - - function isArray$2(ar) { - return Array.isArray(ar); - } - function isBoolean(arg) { - return typeof arg === 'boolean'; - } - function isNull(arg) { - return arg === null; - } - function isNullOrUndefined(arg) { - return arg == null; - } - function isNumber(arg) { - return typeof arg === 'number'; - } - function isString(arg) { - return typeof arg === 'string'; - } - function isSymbol$1(arg) { - return _typeof(arg) === 'symbol'; - } - function isUndefined(arg) { - return arg === void 0; - } - function isRegExp(re) { - return isObject$1(re) && objectToString$1(re) === '[object RegExp]'; - } - function isObject$1(arg) { - return _typeof(arg) === 'object' && arg !== null; - } - function isDate(d) { - return isObject$1(d) && objectToString$1(d) === '[object Date]'; - } - function isError(e) { - return isObject$1(e) && (objectToString$1(e) === '[object Error]' || e instanceof Error); - } - function isFunction(arg) { - return typeof arg === 'function'; - } - function isPrimitive(arg) { - return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || _typeof(arg) === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; - } - function isBuffer$1(maybeBuf) { - return isBuffer(maybeBuf); - } - - function objectToString$1(o) { - return Object.prototype.toString.call(o); - } - - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 - - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } // log is just a thin wrapper to console.log that prepends a timestamp - - - function log$1() { - console.log('%s - %s', timestamp(), format.apply(null, arguments)); - } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject$1(add)) return origin; - var keys = Object.keys(add); - var i = keys.length; - - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - - return origin; - } - - function hasOwnProperty$1(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); - } - - var util = { - inherits: inherits$1, - _extend: _extend, - log: log$1, - isBuffer: isBuffer$1, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject$1, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol$1, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray$2, - inspect: inspect, - deprecate: deprecate, - format: format, - debuglog: debuglog - }; - - var lookup$1 = []; - var revLookup$1 = []; - var Arr$1 = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; - var inited$1 = false; - - function init$1() { - inited$1 = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - - for (var i = 0, len = code.length; i < len; ++i) { - lookup$1[i] = code[i]; - revLookup$1[code.charCodeAt(i)] = i; - } - - revLookup$1['-'.charCodeAt(0)] = 62; - revLookup$1['_'.charCodeAt(0)] = 63; - } - - function toByteArray$1(b64) { - if (!inited$1) { - init$1(); - } - - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4'); - } // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - - - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; // base64 is 4/3 + up to two characters of the original data - - arr = new Arr$1(len * 3 / 4 - placeHolders); // if there are placeholders, only get up to the last complete 4 chars - - l = placeHolders > 0 ? len - 4 : len; - var L = 0; - - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = revLookup$1[b64.charCodeAt(i)] << 18 | revLookup$1[b64.charCodeAt(i + 1)] << 12 | revLookup$1[b64.charCodeAt(i + 2)] << 6 | revLookup$1[b64.charCodeAt(i + 3)]; - arr[L++] = tmp >> 16 & 0xFF; - arr[L++] = tmp >> 8 & 0xFF; - arr[L++] = tmp & 0xFF; - } - - if (placeHolders === 2) { - tmp = revLookup$1[b64.charCodeAt(i)] << 2 | revLookup$1[b64.charCodeAt(i + 1)] >> 4; - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = revLookup$1[b64.charCodeAt(i)] << 10 | revLookup$1[b64.charCodeAt(i + 1)] << 4 | revLookup$1[b64.charCodeAt(i + 2)] >> 2; - arr[L++] = tmp >> 8 & 0xFF; - arr[L++] = tmp & 0xFF; - } - - return arr; - } - - function tripletToBase64$1(num) { - return lookup$1[num >> 18 & 0x3F] + lookup$1[num >> 12 & 0x3F] + lookup$1[num >> 6 & 0x3F] + lookup$1[num & 0x3F]; - } - - function encodeChunk$1(uint8, start, end) { - var tmp; - var output = []; - - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; - output.push(tripletToBase64$1(tmp)); - } - - return output.join(''); - } - - function fromByteArray$1(uint8) { - if (!inited$1) { - init$1(); - } - - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - // go through the array every three bytes, we'll deal with trailing stuff later - - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk$1(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } // pad the end with zeros, but make sure to not forget the extra bytes - - - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup$1[tmp >> 2]; - output += lookup$1[tmp << 4 & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - output += lookup$1[tmp >> 10]; - output += lookup$1[tmp >> 4 & 0x3F]; - output += lookup$1[tmp << 2 & 0x3F]; - output += '='; - } - - parts.push(output); - return parts.join(''); - } - - function read$1(buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); - } - - function write$1(buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0; - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = e << mLen | m; - eLen += mLen; - - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128; - } - - var toString$3 = {}.toString; - - var isArray$3 = Array.isArray || function (arr) { - return toString$3.call(arr) == '[object Array]'; - }; - /*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ - - - var INSPECT_MAX_BYTES$1 = 50; - /** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Use Object implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * Due to various browser bugs, sometimes the Object implementation will be used even - * when the browser supports typed arrays. - * - * Note: - * - * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, - * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. - * - * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. - * - * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of - * incorrect length in some situations. - - * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they - * get the Object implementation, which is slower but behaves correctly. - */ - - Buffer$1.TYPED_ARRAY_SUPPORT = global$2.TYPED_ARRAY_SUPPORT !== undefined ? global$2.TYPED_ARRAY_SUPPORT : true; - - function kMaxLength$1() { - return Buffer$1.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; - } - - function createBuffer$1(that, length) { - if (kMaxLength$1() < length) { - throw new RangeError('Invalid typed array length'); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - - that.length = length; - } - - return that; - } - /** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - - - function Buffer$1(arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length); - } // Common case. - - - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error('If encoding is specified then the first argument must be a string'); - } - - return allocUnsafe$1(this, arg); - } - - return from$1(this, arg, encodingOrOffset, length); - } - - Buffer$1.poolSize = 8192; // not used by this implementation - // TODO: Legacy, not needed anymore. Remove in next major version. - - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr; - }; - - function from$1(that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number'); - } - - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer$1(that, value, encodingOrOffset, length); - } - - if (typeof value === 'string') { - return fromString$1(that, value, encodingOrOffset); - } - - return fromObject$1(that, value); - } - /** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ - - - Buffer$1.from = function (value, encodingOrOffset, length) { - return from$1(null, value, encodingOrOffset, length); - }; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - } - - function assertSize$1(size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number'); - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative'); - } - } - - function alloc$1(that, size, fill, encoding) { - assertSize$1(size); - - if (size <= 0) { - return createBuffer$1(that, size); - } - - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' ? createBuffer$1(that, size).fill(fill, encoding) : createBuffer$1(that, size).fill(fill); - } - - return createBuffer$1(that, size); - } - /** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ - - - Buffer$1.alloc = function (size, fill, encoding) { - return alloc$1(null, size, fill, encoding); - }; - - function allocUnsafe$1(that, size) { - assertSize$1(size); - that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0); - - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - - return that; - } - /** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ - - - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe$1(null, size); - }; - /** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ - - - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe$1(null, size); - }; - - function fromString$1(that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } - - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding'); - } - - var length = byteLength$1(string, encoding) | 0; - that = createBuffer$1(that, length); - var actual = that.write(string, encoding); - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } - - return that; - } - - function fromArrayLike$1(that, array) { - var length = array.length < 0 ? 0 : checked$1(array.length) | 0; - that = createBuffer$1(that, length); - - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - - return that; - } - - function fromArrayBuffer$1(that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer - - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds'); - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds'); - } - - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike$1(that, array); - } - - return that; - } - - function fromObject$1(that, obj) { - if (internalIsBuffer$1(obj)) { - var len = checked$1(obj.length) | 0; - that = createBuffer$1(that, len); - - if (that.length === 0) { - return that; - } - - obj.copy(that, 0, 0, len); - return that; - } - - if (obj) { - if (typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan$1(obj.length)) { - return createBuffer$1(that, 0); - } - - return fromArrayLike$1(that, obj); - } - - if (obj.type === 'Buffer' && isArray$3(obj.data)) { - return fromArrayLike$1(that, obj.data); - } - } - - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.'); - } - - function checked$1(length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength$1()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength$1().toString(16) + ' bytes'); - } - - return length | 0; - } - - Buffer$1.isBuffer = isBuffer$2; - - function internalIsBuffer$1(b) { - return !!(b != null && b._isBuffer); - } - - Buffer$1.compare = function compare(a, b) { - if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) { - throw new TypeError('Arguments must be Buffers'); - } - - if (a === b) return 0; - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - - Buffer$1.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true; - - default: - return false; - } - }; - - Buffer$1.concat = function concat(list, length) { - if (!isArray$3(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - if (list.length === 0) { - return Buffer$1.alloc(0); - } - - var i; - - if (length === undefined) { - length = 0; - - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } - - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - - if (!internalIsBuffer$1(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - - buf.copy(buffer, pos); - pos += buf.length; - } - - return buffer; - }; - - function byteLength$1(string, encoding) { - if (internalIsBuffer$1(string)) { - return string.length; - } - - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength; - } - - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0; // Use a for loop to avoid recursion - - var loweredCase = false; - - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len; - - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes$1(string).length; - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2; - - case 'hex': - return len >>> 1; - - case 'base64': - return base64ToBytes$1(string).length; - - default: - if (loweredCase) return utf8ToBytes$1(string).length; // assume utf8 - - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - } - - Buffer$1.byteLength = byteLength$1; - - function slowToString$1(encoding, start, end) { - var loweredCase = false; // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - - if (start === undefined || start < 0) { - start = 0; - } // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - - - if (start > this.length) { - return ''; - } - - if (end === undefined || end > this.length) { - end = this.length; - } - - if (end <= 0) { - return ''; - } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - - - end >>>= 0; - start >>>= 0; - - if (end <= start) { - return ''; - } - - if (!encoding) encoding = 'utf8'; - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice$1(this, start, end); - - case 'utf8': - case 'utf-8': - return utf8Slice$1(this, start, end); - - case 'ascii': - return asciiSlice$1(this, start, end); - - case 'latin1': - case 'binary': - return latin1Slice$1(this, start, end); - - case 'base64': - return base64Slice$1(this, start, end); - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice$1(this, start, end); - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } - } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect - // Buffer instances. - - - Buffer$1.prototype._isBuffer = true; - - function swap$1(b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; - } - - Buffer$1.prototype.swap16 = function swap16() { - var len = this.length; - - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits'); - } - - for (var i = 0; i < len; i += 2) { - swap$1(this, i, i + 1); - } - - return this; - }; - - Buffer$1.prototype.swap32 = function swap32() { - var len = this.length; - - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits'); - } - - for (var i = 0; i < len; i += 4) { - swap$1(this, i, i + 3); - swap$1(this, i + 1, i + 2); - } - - return this; - }; - - Buffer$1.prototype.swap64 = function swap64() { - var len = this.length; - - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits'); - } - - for (var i = 0; i < len; i += 8) { - swap$1(this, i, i + 7); - swap$1(this, i + 1, i + 6); - swap$1(this, i + 2, i + 5); - swap$1(this, i + 3, i + 4); - } - - return this; - }; - - Buffer$1.prototype.toString = function toString() { - var length = this.length | 0; - if (length === 0) return ''; - if (arguments.length === 0) return utf8Slice$1(this, 0, length); - return slowToString$1.apply(this, arguments); - }; - - Buffer$1.prototype.equals = function equals(b) { - if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer'); - if (this === b) return true; - return Buffer$1.compare(this, b) === 0; - }; - - Buffer$1.prototype.inspect = function inspect() { - var str = ''; - var max = INSPECT_MAX_BYTES$1; - - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - - return ''; - }; - - Buffer$1.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer$1(target)) { - throw new TypeError('Argument must be a Buffer'); - } - - if (start === undefined) { - start = 0; - } - - if (end === undefined) { - end = target ? target.length : 0; - } - - if (thisStart === undefined) { - thisStart = 0; - } - - if (thisEnd === undefined) { - thisEnd = this.length; - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index'); - } - - if (thisStart >= thisEnd && start >= end) { - return 0; - } - - if (thisStart >= thisEnd) { - return -1; - } - - if (start >= end) { - return 1; - } - - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) return 0; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, - // OR the last index of `val` in `buffer` at offset <= `byteOffset`. - // - // Arguments: - // - buffer - a Buffer to search - // - val - a string, Buffer, or number - // - byteOffset - an index into `buffer`; will be clamped to an int32 - // - encoding - an optional encoding, relevant is val is a string - // - dir - true for indexOf, false for lastIndexOf - - - function bidirectionalIndexOf$1(buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1; // Normalize byteOffset - - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - - byteOffset = +byteOffset; // Coerce to Number. - - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : buffer.length - 1; - } // Normalize byteOffset: negative offsets start from the end of the buffer - - - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - - if (byteOffset >= buffer.length) { - if (dir) return -1;else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0;else return -1; - } // Normalize val - - - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } // Finally, search either indexOf (if dir is true) or lastIndexOf - - - if (internalIsBuffer$1(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1; - } - - return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir); - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - - if (Buffer$1.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); - } - } - - return arrayIndexOf$1(buffer, [val], byteOffset, encoding, dir); - } - - throw new TypeError('val must be string, number or Buffer'); - } - - function arrayIndexOf$1(arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - - if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1; - } - - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - - function read(buf, i) { - if (indexSize === 1) { - return buf[i]; - } else { - return buf.readUInt16BE(i * indexSize); - } - } - - var i; - - if (dir) { - var foundIndex = -1; - - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - - for (i = byteOffset; i >= 0; i--) { - var found = true; - - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - - if (found) return i; - } - } - - return -1; - } - - Buffer$1.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - - Buffer$1.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true); - }; - - Buffer$1.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false); - }; - - function hexWrite$1(buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - - if (!length) { - length = remaining; - } else { - length = Number(length); - - if (length > remaining) { - length = remaining; - } - } // must be an even number of digits - - - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string'); - - if (length > strLen / 2) { - length = strLen / 2; - } - - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i; - buf[offset + i] = parsed; - } - - return i; - } - - function utf8Write$1(buf, string, offset, length) { - return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length); - } - - function asciiWrite$1(buf, string, offset, length) { - return blitBuffer$1(asciiToBytes$1(string), buf, offset, length); - } - - function latin1Write$1(buf, string, offset, length) { - return asciiWrite$1(buf, string, offset, length); - } - - function base64Write$1(buf, string, offset, length) { - return blitBuffer$1(base64ToBytes$1(string), buf, offset, length); - } - - function ucs2Write$1(buf, string, offset, length) { - return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length); - } - - Buffer$1.prototype.write = function write(string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } // legacy write(string, encoding, offset, length) - remove in v0.13 - - } else { - throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported'); - } - - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; - - if (string.length > 0 && (length < 0 || offset < 0) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds'); - } - - if (!encoding) encoding = 'utf8'; - var loweredCase = false; - - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite$1(this, string, offset, length); - - case 'utf8': - case 'utf-8': - return utf8Write$1(this, string, offset, length); - - case 'ascii': - return asciiWrite$1(this, string, offset, length); - - case 'latin1': - case 'binary': - return latin1Write$1(this, string, offset, length); - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write$1(this, string, offset, length); - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write$1(this, string, offset, length); - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding); - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - - Buffer$1.prototype.toJSON = function toJSON() { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - - function base64Slice$1(buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray$1(buf); - } else { - return fromByteArray$1(buf.slice(start, end)); - } - } - - function utf8Slice$1(buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - var i = start; - - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = firstByte > 0xEF ? 4 : firstByte > 0xDF ? 3 : firstByte > 0xBF ? 2 : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - - break; - - case 2: - secondByte = buf[i + 1]; - - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | secondByte & 0x3F; - - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - - break; - - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | thirdByte & 0x3F; - - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - - break; - - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | fourthByte & 0x3F; - - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } - - return decodeCodePointsArray$1(res); - } // Based on http://stackoverflow.com/a/22747272/680742, the browser with - // the lowest limit is Chrome, with 0x10000 args. - // We go 1 magnitude less, for safety - - - var MAX_ARGUMENTS_LENGTH$1 = 0x1000; - - function decodeCodePointsArray$1(codePoints) { - var len = codePoints.length; - - if (len <= MAX_ARGUMENTS_LENGTH$1) { - return String.fromCharCode.apply(String, codePoints); // avoid extra slice() - } // Decode in chunks to avoid "call stack size exceeded". - - - var res = ''; - var i = 0; - - while (i < len) { - res += String.fromCharCode.apply(String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1)); - } - - return res; - } - - function asciiSlice$1(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - - return ret; - } - - function latin1Slice$1(buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - - return ret; - } - - function hexSlice$1(buf, start, end) { - var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - var out = ''; - - for (var i = start; i < end; ++i) { - out += toHex$1(buf[i]); - } - - return out; - } - - function utf16leSlice$1(buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - - return res; - } - - Buffer$1.prototype.slice = function slice(start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - - if (end < start) end = start; - var newBuf; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } - - return newBuf; - }; - /* - * Need to make sure that buffer isn't trying to write out of bounds. - */ - - - function checkOffset$1(offset, ext, length) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError('offset is not uint'); - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length'); - } - - Buffer$1.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - return val; - }; - - Buffer$1.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - checkOffset$1(offset, byteLength, this.length); - } - - var val = this[offset + --byteLength]; - var mul = 1; - - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } - - return val; - }; - - Buffer$1.prototype.readUInt8 = function readUInt8(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 1, this.length); - return this[offset]; - }; - - Buffer$1.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - - Buffer$1.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - - Buffer$1.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 0x1000000; - }; - - Buffer$1.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return this[offset] * 0x1000000 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - - Buffer$1.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val; - }; - - Buffer$1.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset$1(offset, byteLength, this.length); - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - - mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val; - }; - - Buffer$1.prototype.readInt8 = function readInt8(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 1, this.length); - if (!(this[offset] & 0x80)) return this[offset]; - return (0xff - this[offset] + 1) * -1; - }; - - Buffer$1.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - var val = this[offset] | this[offset + 1] << 8; - return val & 0x8000 ? val | 0xFFFF0000 : val; - }; - - Buffer$1.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 2, this.length); - var val = this[offset + 1] | this[offset] << 8; - return val & 0x8000 ? val | 0xFFFF0000 : val; - }; - - Buffer$1.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - - Buffer$1.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - - Buffer$1.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return read$1(this, offset, true, 23, 4); - }; - - Buffer$1.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 4, this.length); - return read$1(this, offset, false, 23, 4); - }; - - Buffer$1.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 8, this.length); - return read$1(this, offset, true, 52, 8); - }; - - Buffer$1.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - if (!noAssert) checkOffset$1(offset, 8, this.length); - return read$1(this, offset, false, 52, 8); - }; - - function checkInt$1(buf, value, offset, ext, max, min) { - if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - } - - Buffer$1.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt$1(this, value, offset, byteLength, maxBytes, 0); - } - - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer$1.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt$1(this, value, offset, byteLength, maxBytes, 0); - } - - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = value / mul & 0xFF; - } - - return offset + byteLength; - }; - - Buffer$1.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = value & 0xff; - return offset + 1; - }; - - function objectWriteUInt16$1(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & 0xff << 8 * (littleEndian ? i : 1 - i)) >>> (littleEndian ? i : 1 - i) * 8; - } - } - - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - } else { - objectWriteUInt16$1(this, value, offset, true); - } - - return offset + 2; - }; - - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - } else { - objectWriteUInt16$1(this, value, offset, false); - } - - return offset + 2; - }; - - function objectWriteUInt32$1(buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = value >>> (littleEndian ? i : 3 - i) * 8 & 0xff; - } - } - - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = value >>> 24; - this[offset + 2] = value >>> 16; - this[offset + 1] = value >>> 8; - this[offset] = value & 0xff; - } else { - objectWriteUInt32$1(this, value, offset, true); - } - - return offset + 4; - }; - - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - } else { - objectWriteUInt32$1(this, value, offset, false); - } - - return offset + 4; - }; - - Buffer$1.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - checkInt$1(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer$1.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); - checkInt$1(this, value, offset, byteLength, limit - 1, -limit); - } - - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - - this[offset + i] = (value / mul >> 0) - sub & 0xFF; - } - - return offset + byteLength; - }; - - Buffer$1.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = value & 0xff; - return offset + 1; - }; - - Buffer$1.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - } else { - objectWriteUInt16$1(this, value, offset, true); - } - - return offset + 2; - }; - - Buffer$1.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 8; - this[offset + 1] = value & 0xff; - } else { - objectWriteUInt16$1(this, value, offset, false); - } - - return offset + 2; - }; - - Buffer$1.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value & 0xff; - this[offset + 1] = value >>> 8; - this[offset + 2] = value >>> 16; - this[offset + 3] = value >>> 24; - } else { - objectWriteUInt32$1(this, value, offset, true); - } - - return offset + 4; - }; - - Buffer$1.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = value >>> 24; - this[offset + 1] = value >>> 16; - this[offset + 2] = value >>> 8; - this[offset + 3] = value & 0xff; - } else { - objectWriteUInt32$1(this, value, offset, false); - } - - return offset + 4; - }; - - function checkIEEE754$1(buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range'); - if (offset < 0) throw new RangeError('Index out of range'); - } - - function writeFloat$1(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754$1(buf, value, offset, 4); - } - - write$1(buf, value, offset, littleEndian, 23, 4); - return offset + 4; - } - - Buffer$1.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { - return writeFloat$1(this, value, offset, true, noAssert); - }; - - Buffer$1.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { - return writeFloat$1(this, value, offset, false, noAssert); - }; - - function writeDouble$1(buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754$1(buf, value, offset, 8); - } - - write$1(buf, value, offset, littleEndian, 52, 8); - return offset + 8; - } - - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { - return writeDouble$1(this, value, offset, true, noAssert); - }; - - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { - return writeDouble$1(this, value, offset, false, noAssert); - }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - - - Buffer$1.prototype.copy = function copy(target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; // Copy 0 bytes; we're done - - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; // Fatal error conditions - - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds'); - } - - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds'); - if (end < 0) throw new RangeError('sourceEnd out of bounds'); // Are we oob? - - if (end > this.length) end = this.length; - - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - - var len = end - start; - var i; - - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); - } - - return len; - }; // Usage: - // buffer.fill(number[, offset[, end]]) - // buffer.fill(buffer[, offset[, end]]) - // buffer.fill(string[, offset[, end]][, encoding]) - - - Buffer$1.prototype.fill = function fill(val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - - if (val.length === 1) { - var code = val.charCodeAt(0); - - if (code < 256) { - val = code; - } - } - - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string'); - } - - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding); - } - } else if (typeof val === 'number') { - val = val & 255; - } // Invalid ranges are not set to a default, so can range check early. - - - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index'); - } - - if (end <= start) { - return this; - } - - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; - if (!val) val = 0; - var i; - - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer$1(val) ? val : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - - return this; - }; // HELPER FUNCTIONS - // ================ - - - var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g; - - function base64clean$1(str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); // Node converts strings with length < 2 to '' - - if (str.length < 2) return ''; // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - - while (str.length % 4 !== 0) { - str = str + '='; - } - - return str; - } - - function stringtrim$1(str) { - if (str.trim) return str.trim(); - return str.replace(/^\s+|\s+$/g, ''); - } - - function toHex$1(n) { - if (n < 16) return '0' + n.toString(16); - return n.toString(16); - } - - function utf8ToBytes$1(string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); // is surrogate component - - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue; - } // valid lead - - - leadSurrogate = codePoint; - continue; - } // 2 leads in a row - - - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue; - } // valid surrogate pair - - - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } - - leadSurrogate = null; // encode utf8 - - if (codePoint < 0x80) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break; - bytes.push(codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break; - bytes.push(codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break; - bytes.push(codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80); - } else { - throw new Error('Invalid code point'); - } - } - - return bytes; - } - - function asciiToBytes$1(str) { - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - - return byteArray; - } - - function utf16leToBytes$1(str, units) { - var c, hi, lo; - var byteArray = []; - - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break; - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - - return byteArray; - } - - function base64ToBytes$1(str) { - return toByteArray$1(base64clean$1(str)); - } - - function blitBuffer$1(src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if (i + offset >= dst.length || i >= src.length) break; - dst[i + offset] = src[i]; - } - - return i; - } - - function isnan$1(val) { - return val !== val; // eslint-disable-line no-self-compare - } // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence - // The _isBuffer check is for Safari 5-7 support, because it's missing - // Object.prototype.constructor. Remove this eventually - - - function isBuffer$2(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj)); - } - - function isFastBuffer$1(obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj); - } // For Node v0.10 support. Remove this eventually. - - - function isSlowBuffer$1(obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0)); - } - - function BufferList() { - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function (v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function (v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function () { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function () { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function (s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - }; - - BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer$1.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer$1.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - p.data.copy(ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - }; - - var isBufferEncoding = Buffer$1.isEncoding || function (encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - case 'raw': - return true; - - default: - return false; - } - }; - - function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } - } // StringDecoder provides an interface for efficiently splitting a series of - // buffers into a series of JS strings without breaking apart multi-byte - // characters. CESU-8 is handled as part of the UTF-8 encoding. - // - // @TODO Handling all encodings inside a single object makes it very difficult - // to reason about this code, so it should be split up in the future. - // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code - // points as used by CESU-8. - - - function StringDecoder(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - - default: - this.write = passThroughWrite; - return; - } // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - - - this.charBuffer = new Buffer$1(6); // Number of bytes received for the current incomplete multi-byte character. - - this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. - - this.charLength = 0; - } - // guaranteed to not contain any partial multi-byte characters. Any partial - // character found at the end of the buffer is buffered up, and will be - // returned when calling write again with the remaining bytes. - // - // Note: Converting a Buffer containing an orphan surrogate to a String - // currently works, but converting a String to a Buffer (via `new Buffer`, or - // Buffer#write) will replace incomplete surrogates with the unicode - // replacement character. See https://codereview.chromium.org/121173009/ . - - StringDecoder.prototype.write = function (buffer) { - var charStr = ''; // if our last write ended with an incomplete multibyte character - - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = buffer.length >= this.charLength - this.charReceived ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer - - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } // remove bytes belonging to the current character from the buffer - - - buffer = buffer.slice(available, buffer.length); // get the character that was split - - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - - var charCode = charStr.charCodeAt(charStr.length - 1); - - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - - this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char - - if (buffer.length === 0) { - return charStr; - } - - break; - } // determine and set charLength / charReceived - - - this.detectIncompleteChar(buffer); - var end = buffer.length; - - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } // or just emit the charStr - - - return charStr; - }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at - // the end of the given buffer. If so, it sets this.charLength to the byte - // length that character, and sets this.charReceived to the number of bytes - // that are available for this character. - - - StringDecoder.prototype.detectIncompleteChar = function (buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = buffer.length >= 3 ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description - // 110XXXXX - - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } // 1110XXXX - - - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } // 11110XXX - - - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - - this.charReceived = i; - }; - - StringDecoder.prototype.end = function (buffer) { - var res = ''; - if (buffer && buffer.length) res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; - }; - - function passThroughWrite(buffer) { - return buffer.toString(this.encoding); - } - - function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; - } - - function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; - } - - Readable.ReadableState = ReadableState; - var debug = debuglog('stream'); - inherits$1(Readable, EventEmitter); - - function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') { - return emitter.prependListener(event, fn); - } else { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; - } - } - - function listenerCount$1(emitter, type) { - return emitter.listeners(type).length; - } - - function ReadableState(options, stream) { - options = options || {}; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. - - this.highWaterMark = ~~this.highWaterMark; // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - - this.ranOut = false; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } - } - function Readable(options) { - if (!(this instanceof Readable)) return new Readable(options); - this._readableState = new ReadableState(options, this); // legacy - - this.readable = true; - if (options && typeof options.read === 'function') this._read = options.read; - EventEmitter.call(this); - } // Manually shove something into the read() buffer. - // This returns true if the highWaterMark has not been hit yet, - // similar to how Writable.write() returns true if you should - // write() some more. - - Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - - if (!state.objectMode && typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); - }; // Unshift should *always* be something directly out of read() - - - Readable.prototype.unshift = function (chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); - }; - - Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; - }; - - function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - - if (er) { - stream.emit('error', er); - } else if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var _e = new Error('stream.unshift() after end event'); - - stream.emit('error', _e); - } else { - var skipAdd; - - if (state.decoder && !addToFront && !encoding) { - chunk = state.decoder.write(chunk); - skipAdd = !state.objectMode && chunk.length === 0; - } - - if (!addToFront) state.reading = false; // Don't add to the buffer if we've decoded to an empty string chunk and - // we're not in object mode - - if (!skipAdd) { - // if we want the data now, just emit it. - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - } - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); - } // if it's past the high water mark, we can push in some more. - // Also, if we have no data yet, we can stand some - // more bytes. This is to work around cases where hwm=0, - // such as the repl. Also, if the push() triggered a - // readable event, and the user called read(largeNumber) such that - // needReadable was set, then we ought to push more, so that another - // 'readable' event will be triggered. - - - function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); - } // backwards compatibility. - - - Readable.prototype.setEncoding = function (enc) { - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; - }; // Don't raise the hwm > 8MB - - - var MAX_HWM = 0x800000; - - function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; - } // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; - } // you can override either this method, or the async _read(n) below. - - - Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; - }; - - function chunkInvalid(state, chunk) { - var er = null; - - if (!isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - - return er; - } - - function onEofChunk(stream, state) { - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; // emit 'readable' now to make sure it gets picked up. - - emitReadable(stream); - } // Don't emit readable right away in sync mode, because this can trigger - // another read() call => stack overflow. This way, it might trigger - // a nextTick recursion warning, but that's not so bad. - - - function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) nextTick$1(emitReadable_, stream);else emitReadable_(stream); - } - } - - function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); - } // at this point, the user has presumably seen the 'readable' event, - // and called read() to consume some data. that may have triggered - // in turn another _read(n) call, in which case reading = true if - // it's in progress. - // However, if we're not ended, or reading, and the length < hwm, - // then go ahead and try to read some more preemptively. - - - function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - nextTick$1(maybeReadMore_, stream, state); - } - } - - function maybeReadMore_(stream, state) { - var len = state.length; - - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break;else len = state.length; - } - - state.readingMore = false; - } // abstract method. to be overridden in specific implementation classes. - // call cb(er, data) where data is <= n in length. - // for virtual (non-string, non-buffer) streams, "length" is somewhat - // arbitrary, and perhaps not very meaningful. - - - Readable.prototype._read = function (n) { - this.emit('error', new Error('not implemented')); - }; - - Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = !pipeOpts || pipeOpts.end !== false; - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) nextTick$1(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable) { - debug('onunpipe'); - - if (readable === src) { - cleanup(); - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - - - var increasedAwaitDrain = false; - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf$1(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (listenerCount$1(dest, 'error') === 0) dest.emit('error', er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; - }; - - function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && src.listeners('data').length) { - state.flowing = true; - flow(src); - } - }; - } - - Readable.prototype.unpipe = function (dest) { - var state = this._readableState; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var _i = 0; _i < len; _i++) { - dests[_i].emit('unpipe', this); - } - - return this; - } // try to find the right one. - - - var i = indexOf$1(state.pipes, dest); - if (i === -1) return this; - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this); - return this; - }; // set up data events if they are asked for - // Ensure readable listeners eventually get something - - - Readable.prototype.on = function (ev, fn) { - var res = EventEmitter.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - - if (!state.reading) { - nextTick$1(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; - }; - - Readable.prototype.addListener = Readable.prototype.on; - - function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); - } // pause() and resume() are remnants of the legacy readable stream API - // If the user uses them, then switch into old mode. - - - Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - - return this; - }; - - function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - nextTick$1(resume_, stream, state); - } - } - - function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); - } - - Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - return this; - }; - - function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) {} - } // wrap an old-style stream as the async data source. - // This is *not* part of the readable stream interface. - // It is an ugly unfortunate mess of history. - - - Readable.prototype.wrap = function (stream) { - var state = this._readableState; - var paused = false; - var self = this; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) self.push(chunk); - } - - self.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - var ret = self.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function (ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); // when we try to consume some more bytes, simply unpause the - // underlying stream. - - self._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; - }; // exposed for testing purposes only. - - - Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. - // Length is the combined lengths of all the buffers in the list. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - return ret; - } // Extracts only enough buffered data to satisfy the amount requested. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function fromListPartial(n, list, hasStrings) { - var ret; - - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - - return ret; - } // Copies a specified amount of characters from the list of buffered data - // chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - list.length -= c; - return ret; - } // Copies a specified amount of bytes from the list of buffered data chunks. - // This function is designed to be inlinable, so please take care when making - // changes to the function body. - - - function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - list.length -= c; - return ret; - } - - function endReadable(stream) { - var state = stream._readableState; // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - nextTick$1(endReadableNT, state, stream); - } - } - - function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - } - - function forEach(xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } - } - - function indexOf$1(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; - } - - // A bit simpler than readable streams. - Writable.WritableState = WritableState; - inherits$1(Writable, EventEmitter); - - function nop() {} - - function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; - } - - function WritableState(options, stream) { - Object.defineProperty(this, 'buffer', { - get: deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') - }); - options = options || {}; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - var hwm = options.highWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. - - this.highWaterMark = ~~this.highWaterMark; - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); - } - - WritableState.prototype.getBuffer = function writableStateGetBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; - }; - function Writable(options) { - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); - this._writableState = new WritableState(options, this); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - } - - EventEmitter.call(this); - } // Otherwise people can pipe Writable streams, which is just wrong. - - Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); - }; - - function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb - - stream.emit('error', er); - nextTick$1(cb, er); - } // If we get something that is not a buffer, string, null, or undefined, - // and we're not in objectMode, then that's an error. - // Otherwise stream chunks are all considered to be of length=1, and the - // watermarks determine how many objects to keep in the buffer, rather than - // how many bytes or characters. - - - function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; // Always throw error if a null is written - // if we are not in object mode then throw - // if it is not a buffer, string, or undefined. - - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - - if (er) { - stream.emit('error', er); - nextTick$1(cb, er); - valid = false; - } - - return valid; - } - - Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, chunk, encoding, cb); - } - return ret; - }; - - Writable.prototype.cork = function () { - var state = this._writableState; - state.corked++; - }; - - Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } - }; - - Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; - }; - - function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$1.from(chunk, encoding); - } - - return chunk; - } // if we're already writing something, then just put this - // in the queue, and wait our turn. Otherwise, call _write - // If we return false, then we need a drain event, so set that flag. - - - function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; - } - - function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; - } - - function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - if (sync) nextTick$1(cb, er);else cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } - - function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; - } - - function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - nextTick$1(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } - } - - function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); - } // Must force callback to be called on nextTick, so that we don't - // emit 'drain' before the write() consumer gets the 'false' return - // value, and has a chance to attach a 'drain' listener. - - - function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } - } // if there's something in the buffer waiting, then process it - - - function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - - while (entry) { - buffer[count] = entry; - entry = entry.next; - count += 1; - } - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequestCount = 0; - state.bufferedRequest = entry; - state.bufferProcessing = false; - } - - Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('not implemented')); - }; - - Writable.prototype._writev = null; - - Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending && !state.finished) endWritable(this, state, cb); - }; - - function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; - } - - function prefinish(stream, state) { - if (!state.prefinished) { - state.prefinished = true; - stream.emit('prefinish'); - } - } - - function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - if (state.pendingcb === 0) { - prefinish(stream, state); - state.finished = true; - stream.emit('finish'); - } else { - prefinish(stream, state); - } - } - - return need; - } - - function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) nextTick$1(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; - } // It seems a linked list but it is not - // there will be only 2 of these for each stream - - - function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function (err) { - var entry = _this.entry; - _this.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = _this; - } else { - state.corkedRequestsFree = _this; - } - }; - } - - inherits$1(Duplex, Readable); - var keys$4 = Object.keys(Writable.prototype); - - for (var v = 0; v < keys$4.length; v++) { - var method = keys$4[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } - function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - if (options && options.readable === false) this.readable = false; - if (options && options.writable === false) this.writable = false; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - this.once('end', onend); - } // the no-half-open enforcer - - function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - nextTick$1(onEndNT, this); - } - - function onEndNT(self) { - self.end(); - } - - // a transform stream is a readable/writable stream where you do - inherits$1(Transform, Duplex); - - function TransformState(stream) { - this.afterTransform = function (er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; - this.writeencoding = null; - } - - function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - var cb = ts.writecb; - if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); - ts.writechunk = null; - ts.writecb = null; - if (data !== null && data !== undefined) stream.push(data); - cb(er); - var rs = stream._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } - } - function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = new TransformState(this); // when the writable side finishes, then flush out anything remaining. - - var stream = this; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } - - this.once('prefinish', function () { - if (typeof this._flush === 'function') this._flush(function (er) { - done(stream, er); - });else done(stream); - }); - } - - Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); - }; // This is the part where you do stuff! - // override this function in implementation classes. - // 'chunk' is an input chunk. - // - // Call `push(newChunk)` to pass along transformed output - // to the readable side. You may call 'push' zero or more times. - // - // Call `cb(err)` when you are done with this chunk. If you pass - // an error, then that'll put the hurt on the whole operation. If you - // never call cb(), then you'll never get another chunk. - - - Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('Not implemented'); - }; - - Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } - }; // Doesn't matter what the args are here. - // _transform does all the work. - // That we got here means that the readable side wants more data. - - - Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } - }; - - function done(stream, er) { - if (er) return stream.emit('error', er); // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - var ws = stream._writableState; - var ts = stream._transformState; - if (ws.length) throw new Error('Calling transform done when ws.length != 0'); - if (ts.transforming) throw new Error('Calling transform done when still transforming'); - return stream.push(null); - } - - inherits$1(PassThrough, Transform); - function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); - } - - PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); - }; - - inherits$1(Stream, EventEmitter); - Stream.Readable = Readable; - Stream.Writable = Writable; - Stream.Duplex = Duplex; - Stream.Transform = Transform; - Stream.PassThrough = PassThrough; // Backwards-compat with node 0.4.x - - Stream.Stream = Stream; - // part of this class) is overridden in the Readable class. - - function Stream() { - EventEmitter.call(this); - } - - Stream.prototype.pipe = function (dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - - function onend() { - if (didOnEnd) return; - didOnEnd = true; - dest.end(); - } - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - if (typeof dest.destroy === 'function') dest.destroy(); - } // don't leave dangling pipes when there are errors. - - - function onerror(er) { - cleanup(); - - if (EventEmitter.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); // remove all the event listeners that were added. - - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - source.removeListener('end', onend); - source.removeListener('close', onclose); - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - dest.on('close', cleanup); - dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) - - return dest; - }; - - var WritableStream = Stream.Writable; - var inherits$2 = util.inherits; - var browserStdout = BrowserStdout; - inherits$2(BrowserStdout, WritableStream); - - function BrowserStdout(opts) { - if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts); - opts = opts || {}; - WritableStream.call(this, opts); - this.label = opts.label !== undefined ? opts.label : 'stdout'; - } - - BrowserStdout.prototype._write = function (chunks, encoding, cb) { - var output = chunks.toString ? chunks.toString() : chunks; - - if (this.label === false) { - console.log(output); - } else { - console.log(this.label + ':', output); - } - - nextTick(cb); - }; - - var parseQuery = function parseQuery(qs) { - return qs.replace('?', '').split('&').reduce(function (obj, pair) { - var i = pair.indexOf('='); - var key = pair.slice(0, i); - var val = pair.slice(++i); // Due to how the URLSearchParams API treats spaces - - obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); - return obj; - }, {}); - }; - - function highlight(js) { - return js.replace(//g, '>').replace(/\/\/(.*)/gm, '//$1').replace(/('.*?')/gm, '$1').replace(/(\d+\.\d+)/gm, '$1').replace(/(\d+)/gm, '$1').replace(/\bnew[ \t]+(\w+)/gm, 'new $1').replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1'); - } - /** - * Highlight the contents of tag `name`. - * - * @private - * @param {string} name - */ - - - var highlightTags = function highlightTags(name) { - var code = document.getElementById('mocha').getElementsByTagName(name); - - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } - }; - - var nativePromiseConstructor = global_1.Promise; - - var iteratorClose = function (iterator) { - var returnMethod = iterator['return']; - if (returnMethod !== undefined) { - return anObject(returnMethod.call(iterator)).value; - } - }; - - var Result = function (stopped, result) { - this.stopped = stopped; - this.result = result; - }; - - var iterate = function (iterable, unboundFunction, options) { - var that = options && options.that; - var AS_ENTRIES = !!(options && options.AS_ENTRIES); - var IS_ITERATOR = !!(options && options.IS_ITERATOR); - var INTERRUPTED = !!(options && options.INTERRUPTED); - var fn = functionBindContext(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED); - var iterator, iterFn, index, length, result, next, step; - - var stop = function (condition) { - if (iterator) iteratorClose(iterator); - return new Result(true, condition); - }; - - var callFn = function (value) { - if (AS_ENTRIES) { - anObject(value); - return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]); - } return INTERRUPTED ? fn(value, stop) : fn(value); - }; - - if (IS_ITERATOR) { - iterator = iterable; - } else { - iterFn = getIteratorMethod(iterable); - if (typeof iterFn != 'function') throw TypeError('Target is not iterable'); - // optimisation for array iterators - if (isArrayIteratorMethod(iterFn)) { - for (index = 0, length = toLength(iterable.length); length > index; index++) { - result = callFn(iterable[index]); - if (result && result instanceof Result) return result; - } return new Result(false); - } - iterator = iterFn.call(iterable); - } - - next = iterator.next; - while (!(step = next.call(iterator)).done) { - try { - result = callFn(step.value); - } catch (error) { - iteratorClose(iterator); - throw error; - } - if (typeof result == 'object' && result && result instanceof Result) return result; - } return new Result(false); - }; - - var engineIsIos = /(iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent); - - var engineIsNode = classofRaw(global_1.process) == 'process'; - - var location$1 = global_1.location; - var set$2 = global_1.setImmediate; - var clear = global_1.clearImmediate; - var process$2 = global_1.process; - var MessageChannel = global_1.MessageChannel; - var Dispatch = global_1.Dispatch; - var counter = 0; - var queue$2 = {}; - var ONREADYSTATECHANGE = 'onreadystatechange'; - var defer, channel, port; - - var run = function (id) { - // eslint-disable-next-line no-prototype-builtins - if (queue$2.hasOwnProperty(id)) { - var fn = queue$2[id]; - delete queue$2[id]; - fn(); - } - }; - - var runner = function (id) { - return function () { - run(id); - }; - }; - - var listener = function (event) { - run(event.data); - }; - - var post = function (id) { - // old engines have not location.origin - global_1.postMessage(id + '', location$1.protocol + '//' + location$1.host); - }; - - // Node.js 0.9+ & IE10+ has setImmediate, otherwise: - if (!set$2 || !clear) { - set$2 = function setImmediate(fn) { - var args = []; - var i = 1; - while (arguments.length > i) args.push(arguments[i++]); - queue$2[++counter] = function () { - // eslint-disable-next-line no-new-func - (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args); - }; - defer(counter); - return counter; - }; - clear = function clearImmediate(id) { - delete queue$2[id]; - }; - // Node.js 0.8- - if (engineIsNode) { - defer = function (id) { - process$2.nextTick(runner(id)); - }; - // Sphere (JS game engine) Dispatch API - } else if (Dispatch && Dispatch.now) { - defer = function (id) { - Dispatch.now(runner(id)); - }; - // Browsers with MessageChannel, includes WebWorkers - // except iOS - https://github.com/zloirock/core-js/issues/624 - } else if (MessageChannel && !engineIsIos) { - channel = new MessageChannel(); - port = channel.port2; - channel.port1.onmessage = listener; - defer = functionBindContext(port.postMessage, port, 1); - // Browsers with postMessage, skip WebWorkers - // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' - } else if ( - global_1.addEventListener && - typeof postMessage == 'function' && - !global_1.importScripts && - location$1 && location$1.protocol !== 'file:' && - !fails(post) - ) { - defer = post; - global_1.addEventListener('message', listener, false); - // IE8- - } else if (ONREADYSTATECHANGE in documentCreateElement('script')) { - defer = function (id) { - html.appendChild(documentCreateElement('script'))[ONREADYSTATECHANGE] = function () { - html.removeChild(this); - run(id); - }; - }; - // Rest old browsers - } else { - defer = function (id) { - setTimeout(runner(id), 0); - }; - } - } - - var task = { - set: set$2, - clear: clear - }; - - var engineIsWebosWebkit = /web0s(?!.*chrome)/i.test(engineUserAgent); - - var getOwnPropertyDescriptor$3 = objectGetOwnPropertyDescriptor.f; - var macrotask = task.set; - - - - - var MutationObserver = global_1.MutationObserver || global_1.WebKitMutationObserver; - var document$2 = global_1.document; - var process$3 = global_1.process; - var Promise$1 = global_1.Promise; - // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask` - var queueMicrotaskDescriptor = getOwnPropertyDescriptor$3(global_1, 'queueMicrotask'); - var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value; - - var flush, head, last, notify, toggle, node, promise, then; - - // modern engines have queueMicrotask method - if (!queueMicrotask) { - flush = function () { - var parent, fn; - if (engineIsNode && (parent = process$3.domain)) parent.exit(); - while (head) { - fn = head.fn; - head = head.next; - try { - fn(); - } catch (error) { - if (head) notify(); - else last = undefined; - throw error; - } - } last = undefined; - if (parent) parent.enter(); - }; - - // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339 - // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898 - if (!engineIsIos && !engineIsNode && !engineIsWebosWebkit && MutationObserver && document$2) { - toggle = true; - node = document$2.createTextNode(''); - new MutationObserver(flush).observe(node, { characterData: true }); - notify = function () { - node.data = toggle = !toggle; - }; - // environments with maybe non-completely correct, but existent Promise - } else if (Promise$1 && Promise$1.resolve) { - // Promise.resolve without an argument throws an error in LG WebOS 2 - promise = Promise$1.resolve(undefined); - then = promise.then; - notify = function () { - then.call(promise, flush); - }; - // Node.js without promises - } else if (engineIsNode) { - notify = function () { - process$3.nextTick(flush); - }; - // for other environments - macrotask based on: - // - setImmediate - // - MessageChannel - // - window.postMessag - // - onreadystatechange - // - setTimeout - } else { - notify = function () { - // strange IE + webpack dev server bug - use .call(global) - macrotask.call(global_1, flush); - }; - } - } - - var microtask = queueMicrotask || function (fn) { - var task = { fn: fn, next: undefined }; - if (last) last.next = task; - if (!head) { - head = task; - notify(); - } last = task; - }; - - var PromiseCapability = function (C) { - var resolve, reject; - this.promise = new C(function ($$resolve, $$reject) { - if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor'); - resolve = $$resolve; - reject = $$reject; - }); - this.resolve = aFunction$1(resolve); - this.reject = aFunction$1(reject); - }; - - // 25.4.1.5 NewPromiseCapability(C) - var f$7 = function (C) { - return new PromiseCapability(C); - }; - - var newPromiseCapability = { - f: f$7 - }; - - var promiseResolve = function (C, x) { - anObject(C); - if (isObject(x) && x.constructor === C) return x; - var promiseCapability = newPromiseCapability.f(C); - var resolve = promiseCapability.resolve; - resolve(x); - return promiseCapability.promise; - }; - - var hostReportErrors = function (a, b) { - var console = global_1.console; - if (console && console.error) { - arguments.length === 1 ? console.error(a) : console.error(a, b); - } - }; - - var perform = function (exec) { - try { - return { error: false, value: exec() }; - } catch (error) { - return { error: true, value: error }; - } - }; - - var task$1 = task.set; - - - - - - - - - - - - var SPECIES$6 = wellKnownSymbol('species'); - var PROMISE = 'Promise'; - var getInternalState$3 = internalState.get; - var setInternalState$4 = internalState.set; - var getInternalPromiseState = internalState.getterFor(PROMISE); - var PromiseConstructor = nativePromiseConstructor; - var TypeError$1 = global_1.TypeError; - var document$3 = global_1.document; - var process$4 = global_1.process; - var $fetch = getBuiltIn('fetch'); - var newPromiseCapability$1 = newPromiseCapability.f; - var newGenericPromiseCapability = newPromiseCapability$1; - var DISPATCH_EVENT = !!(document$3 && document$3.createEvent && global_1.dispatchEvent); - var NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function'; - var UNHANDLED_REJECTION = 'unhandledrejection'; - var REJECTION_HANDLED = 'rejectionhandled'; - var PENDING = 0; - var FULFILLED = 1; - var REJECTED = 2; - var HANDLED = 1; - var UNHANDLED = 2; - var Internal, OwnPromiseCapability, PromiseWrapper, nativeThen; - - var FORCED$7 = isForced_1(PROMISE, function () { - var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor); - if (!GLOBAL_CORE_JS_PROMISE) { - // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables - // https://bugs.chromium.org/p/chromium/issues/detail?id=830565 - // We can't detect it synchronously, so just check versions - if (engineV8Version === 66) return true; - // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test - if (!engineIsNode && !NATIVE_REJECTION_EVENT) return true; - } - // We can't use @@species feature detection in V8 since it causes - // deoptimization and performance degradation - // https://github.com/zloirock/core-js/issues/679 - if (engineV8Version >= 51 && /native code/.test(PromiseConstructor)) return false; - // Detect correctness of subclassing with @@species support - var promise = PromiseConstructor.resolve(1); - var FakePromise = function (exec) { - exec(function () { /* empty */ }, function () { /* empty */ }); - }; - var constructor = promise.constructor = {}; - constructor[SPECIES$6] = FakePromise; - return !(promise.then(function () { /* empty */ }) instanceof FakePromise); - }); - - var INCORRECT_ITERATION = FORCED$7 || !checkCorrectnessOfIteration(function (iterable) { - PromiseConstructor.all(iterable)['catch'](function () { /* empty */ }); - }); - - // helpers - var isThenable = function (it) { - var then; - return isObject(it) && typeof (then = it.then) == 'function' ? then : false; - }; - - var notify$1 = function (state, isReject) { - if (state.notified) return; - state.notified = true; - var chain = state.reactions; - microtask(function () { - var value = state.value; - var ok = state.state == FULFILLED; - var index = 0; - // variable length - can't use forEach - while (chain.length > index) { - var reaction = chain[index++]; - var handler = ok ? reaction.ok : reaction.fail; - var resolve = reaction.resolve; - var reject = reaction.reject; - var domain = reaction.domain; - var result, then, exited; - try { - if (handler) { - if (!ok) { - if (state.rejection === UNHANDLED) onHandleUnhandled(state); - state.rejection = HANDLED; - } - if (handler === true) result = value; - else { - if (domain) domain.enter(); - result = handler(value); // can throw - if (domain) { - domain.exit(); - exited = true; - } - } - if (result === reaction.promise) { - reject(TypeError$1('Promise-chain cycle')); - } else if (then = isThenable(result)) { - then.call(result, resolve, reject); - } else resolve(result); - } else reject(value); - } catch (error) { - if (domain && !exited) domain.exit(); - reject(error); - } - } - state.reactions = []; - state.notified = false; - if (isReject && !state.rejection) onUnhandled(state); - }); - }; - - var dispatchEvent = function (name, promise, reason) { - var event, handler; - if (DISPATCH_EVENT) { - event = document$3.createEvent('Event'); - event.promise = promise; - event.reason = reason; - event.initEvent(name, false, true); - global_1.dispatchEvent(event); - } else event = { promise: promise, reason: reason }; - if (!NATIVE_REJECTION_EVENT && (handler = global_1['on' + name])) handler(event); - else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason); - }; - - var onUnhandled = function (state) { - task$1.call(global_1, function () { - var promise = state.facade; - var value = state.value; - var IS_UNHANDLED = isUnhandled(state); - var result; - if (IS_UNHANDLED) { - result = perform(function () { - if (engineIsNode) { - process$4.emit('unhandledRejection', value, promise); - } else dispatchEvent(UNHANDLED_REJECTION, promise, value); - }); - // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should - state.rejection = engineIsNode || isUnhandled(state) ? UNHANDLED : HANDLED; - if (result.error) throw result.value; - } - }); - }; - - var isUnhandled = function (state) { - return state.rejection !== HANDLED && !state.parent; - }; - - var onHandleUnhandled = function (state) { - task$1.call(global_1, function () { - var promise = state.facade; - if (engineIsNode) { - process$4.emit('rejectionHandled', promise); - } else dispatchEvent(REJECTION_HANDLED, promise, state.value); - }); - }; - - var bind = function (fn, state, unwrap) { - return function (value) { - fn(state, value, unwrap); - }; - }; - - var internalReject = function (state, value, unwrap) { - if (state.done) return; - state.done = true; - if (unwrap) state = unwrap; - state.value = value; - state.state = REJECTED; - notify$1(state, true); - }; - - var internalResolve = function (state, value, unwrap) { - if (state.done) return; - state.done = true; - if (unwrap) state = unwrap; - try { - if (state.facade === value) throw TypeError$1("Promise can't be resolved itself"); - var then = isThenable(value); - if (then) { - microtask(function () { - var wrapper = { done: false }; - try { - then.call(value, - bind(internalResolve, wrapper, state), - bind(internalReject, wrapper, state) - ); - } catch (error) { - internalReject(wrapper, error, state); - } - }); - } else { - state.value = value; - state.state = FULFILLED; - notify$1(state, false); - } - } catch (error) { - internalReject({ done: false }, error, state); - } - }; - - // constructor polyfill - if (FORCED$7) { - // 25.4.3.1 Promise(executor) - PromiseConstructor = function Promise(executor) { - anInstance(this, PromiseConstructor, PROMISE); - aFunction$1(executor); - Internal.call(this); - var state = getInternalState$3(this); - try { - executor(bind(internalResolve, state), bind(internalReject, state)); - } catch (error) { - internalReject(state, error); - } - }; - // eslint-disable-next-line no-unused-vars - Internal = function Promise(executor) { - setInternalState$4(this, { - type: PROMISE, - done: false, - notified: false, - parent: false, - reactions: [], - rejection: false, - state: PENDING, - value: undefined - }); - }; - Internal.prototype = redefineAll(PromiseConstructor.prototype, { - // `Promise.prototype.then` method - // https://tc39.es/ecma262/#sec-promise.prototype.then - then: function then(onFulfilled, onRejected) { - var state = getInternalPromiseState(this); - var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor)); - reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; - reaction.fail = typeof onRejected == 'function' && onRejected; - reaction.domain = engineIsNode ? process$4.domain : undefined; - state.parent = true; - state.reactions.push(reaction); - if (state.state != PENDING) notify$1(state, false); - return reaction.promise; - }, - // `Promise.prototype.catch` method - // https://tc39.es/ecma262/#sec-promise.prototype.catch - 'catch': function (onRejected) { - return this.then(undefined, onRejected); - } - }); - OwnPromiseCapability = function () { - var promise = new Internal(); - var state = getInternalState$3(promise); - this.promise = promise; - this.resolve = bind(internalResolve, state); - this.reject = bind(internalReject, state); - }; - newPromiseCapability.f = newPromiseCapability$1 = function (C) { - return C === PromiseConstructor || C === PromiseWrapper - ? new OwnPromiseCapability(C) - : newGenericPromiseCapability(C); - }; - - if ( typeof nativePromiseConstructor == 'function') { - nativeThen = nativePromiseConstructor.prototype.then; - - // wrap native Promise#then for native async functions - redefine(nativePromiseConstructor.prototype, 'then', function then(onFulfilled, onRejected) { - var that = this; - return new PromiseConstructor(function (resolve, reject) { - nativeThen.call(that, resolve, reject); - }).then(onFulfilled, onRejected); - // https://github.com/zloirock/core-js/issues/640 - }, { unsafe: true }); - - // wrap fetch result - if (typeof $fetch == 'function') _export({ global: true, enumerable: true, forced: true }, { - // eslint-disable-next-line no-unused-vars - fetch: function fetch(input /* , init */) { - return promiseResolve(PromiseConstructor, $fetch.apply(global_1, arguments)); - } - }); - } - } - - _export({ global: true, wrap: true, forced: FORCED$7 }, { - Promise: PromiseConstructor - }); - - setToStringTag(PromiseConstructor, PROMISE, false); - setSpecies(PROMISE); - - PromiseWrapper = getBuiltIn(PROMISE); - - // statics - _export({ target: PROMISE, stat: true, forced: FORCED$7 }, { - // `Promise.reject` method - // https://tc39.es/ecma262/#sec-promise.reject - reject: function reject(r) { - var capability = newPromiseCapability$1(this); - capability.reject.call(undefined, r); - return capability.promise; - } - }); - - _export({ target: PROMISE, stat: true, forced: FORCED$7 }, { - // `Promise.resolve` method - // https://tc39.es/ecma262/#sec-promise.resolve - resolve: function resolve(x) { - return promiseResolve( this, x); - } - }); - - _export({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, { - // `Promise.all` method - // https://tc39.es/ecma262/#sec-promise.all - all: function all(iterable) { - var C = this; - var capability = newPromiseCapability$1(C); - var resolve = capability.resolve; - var reject = capability.reject; - var result = perform(function () { - var $promiseResolve = aFunction$1(C.resolve); - var values = []; - var counter = 0; - var remaining = 1; - iterate(iterable, function (promise) { - var index = counter++; - var alreadyCalled = false; - values.push(undefined); - remaining++; - $promiseResolve.call(C, promise).then(function (value) { - if (alreadyCalled) return; - alreadyCalled = true; - values[index] = value; - --remaining || resolve(values); - }, reject); - }); - --remaining || resolve(values); - }); - if (result.error) reject(result.value); - return capability.promise; - }, - // `Promise.race` method - // https://tc39.es/ecma262/#sec-promise.race - race: function race(iterable) { - var C = this; - var capability = newPromiseCapability$1(C); - var reject = capability.reject; - var result = perform(function () { - var $promiseResolve = aFunction$1(C.resolve); - iterate(iterable, function (promise) { - $promiseResolve.call(C, promise).then(capability.resolve, reject); - }); - }); - if (result.error) reject(result.value); - return capability.promise; - } - }); - - // `Symbol.asyncIterator` well-known symbol - // https://tc39.es/ecma262/#sec-symbol.asynciterator - defineWellKnownSymbol('asyncIterator'); - - // `Symbol.iterator` well-known symbol - // https://tc39.es/ecma262/#sec-symbol.iterator - defineWellKnownSymbol('iterator'); - - // `Symbol.toStringTag` well-known symbol - // https://tc39.es/ecma262/#sec-symbol.tostringtag - defineWellKnownSymbol('toStringTag'); - - // JSON[@@toStringTag] property - // https://tc39.es/ecma262/#sec-json-@@tostringtag - setToStringTag(global_1.JSON, 'JSON', true); - - // Math[@@toStringTag] property - // https://tc39.es/ecma262/#sec-math-@@tostringtag - setToStringTag(Math, 'Math', true); - - var charAt$1 = stringMultibyte.charAt; - - - - var STRING_ITERATOR = 'String Iterator'; - var setInternalState$5 = internalState.set; - var getInternalState$4 = internalState.getterFor(STRING_ITERATOR); - - // `String.prototype[@@iterator]` method - // https://tc39.es/ecma262/#sec-string.prototype-@@iterator - defineIterator(String, 'String', function (iterated) { - setInternalState$5(this, { - type: STRING_ITERATOR, - string: String(iterated), - index: 0 - }); - // `%StringIteratorPrototype%.next` method - // https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next - }, function next() { - var state = getInternalState$4(this); - var string = state.string; - var index = state.index; - var point; - if (index >= string.length) return { value: undefined, done: true }; - point = charAt$1(string, index); - state.index += point.length; - return { value: point, done: false }; - }); - - var ITERATOR$6 = wellKnownSymbol('iterator'); - var TO_STRING_TAG$4 = wellKnownSymbol('toStringTag'); - var ArrayValues = es_array_iterator.values; - - for (var COLLECTION_NAME$1 in domIterables) { - var Collection$1 = global_1[COLLECTION_NAME$1]; - var CollectionPrototype$1 = Collection$1 && Collection$1.prototype; - if (CollectionPrototype$1) { - // some Chrome versions have non-configurable methods on DOMTokenList - if (CollectionPrototype$1[ITERATOR$6] !== ArrayValues) try { - createNonEnumerableProperty(CollectionPrototype$1, ITERATOR$6, ArrayValues); - } catch (error) { - CollectionPrototype$1[ITERATOR$6] = ArrayValues; - } - if (!CollectionPrototype$1[TO_STRING_TAG$4]) { - createNonEnumerableProperty(CollectionPrototype$1, TO_STRING_TAG$4, COLLECTION_NAME$1); - } - if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) { - // some Chrome versions have non-configurable methods on DOMTokenList - if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try { - createNonEnumerableProperty(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]); - } catch (error) { - CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME]; - } - } - } - } - - createCommonjsModule(function (module) { - /** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - var runtime = function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function define(obj, key, value) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - return obj[key]; - } - - try { - // IE 8 has a broken Object.defineProperty that only works on DOM objects. - define({}, ""); - } catch (err) { - define = function define(obj, key, value) { - return obj[key] = value; - }; - } - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - - generator._invoke = makeInvokeMethod(innerFn, self, context); - return generator; - } - - exports.wrap = wrap; // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - - function tryCatch(fn, obj, arg) { - try { - return { - type: "normal", - arg: fn.call(obj, arg) - }; - } catch (err) { - return { - type: "throw", - arg: err - }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - - var ContinueSentinel = {}; // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - - function Generator() {} - - function GeneratorFunction() {} - - function GeneratorFunctionPrototype() {} // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - - - var IteratorPrototype = {}; - - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - - if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function (method) { - define(prototype, method, function (arg) { - return this._invoke(method, arg); - }); - }); - } - - exports.isGeneratorFunction = function (genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor ? ctor === GeneratorFunction || // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" : false; - }; - - exports.mark = function (genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - define(genFun, toStringTagSymbol, "GeneratorFunction"); - } - - genFun.prototype = Object.create(Gp); - return genFun; - }; // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - - - exports.awrap = function (arg) { - return { - __await: arg - }; - }; - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - - if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function (value) { - invoke("next", value, resolve, reject); - }, function (err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function (unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function (error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function (resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); - } // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - - - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - - exports.AsyncIterator = AsyncIterator; // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - - exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); - return exports.isGeneratorFunction(outerFn) ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function (result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - - - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - var record = tryCatch(innerFn, self, context); - - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done ? GenStateCompleted : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - } else if (record.type === "throw") { - state = GenStateCompleted; // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - - - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError("The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (!info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; // Resume execution at the desired location (see delegateYield). - - context.next = delegate.nextLoc; // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - } else { - // Re-yield the result returned by the delegate method. - return info; - } // The delegate iterator is finished, so forget it and continue with - // the outer generator. - - - context.delegate = null; - return ContinueSentinel; - } // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - - - defineIteratorMethods(Gp); - define(Gp, toStringTagSymbol, "Generator"); // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - - Gp[iteratorSymbol] = function () { - return this; - }; - - Gp.toString = function () { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { - tryLoc: locs[0] - }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ - tryLoc: "root" - }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function (object) { - var keys = []; - - for (var key in object) { - keys.push(key); - } - - keys.reverse(); // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - - return function next() { - while (keys.length) { - var key = keys.pop(); - - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - - - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, - next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - return next; - }; - - return next.next = next; - } - } // Return an iterator with no values. - - - return { - next: doneResult - }; - } - - exports.values = values; - - function doneResult() { - return { - value: undefined$1, - done: true - }; - } - - Context.prototype = { - constructor: Context, - reset: function reset(skipTempReset) { - this.prev = 0; - this.next = 0; // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - this.method = "next"; - this.arg = undefined$1; - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - stop: function stop() { - this.done = true; - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - dispatchException: function dispatchException(exception) { - if (this.done) { - throw exception; - } - - var context = this; - - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !!caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - abrupt: function abrupt(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - complete: function complete(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - finish: function finish(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - "catch": function _catch(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - - return thrown; - } - } // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - - - throw new Error("illegal catch attempt"); - }, - delegateYield: function delegateYield(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - - return exports; - }( // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports ); - - try { - regeneratorRuntime = runtime; - } catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); - } - }); - - var escapeStringRegexp = function escapeStringRegexp(string) { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - - - return string.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&').replace(/-/g, '\\x2d'); - }; - - // Copyright Joyent, Inc. and other Node 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. - // resolves . and .. elements in a path array with directory names there - // must be no slashes, empty elements, or device names (c:\) in the array - // (so also no leading and trailing slashes - it does not distinguish - // relative and absolute paths) - function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - - if (last === '.') { - parts.splice(i, 1); - } else if (last === '..') { - parts.splice(i, 1); - up++; - } else if (up) { - parts.splice(i, 1); - up--; - } - } // if the path is allowed to go above the root, restore leading ..s - - - if (allowAboveRoot) { - for (; up--; up) { - parts.unshift('..'); - } - } - - return parts; - } // Split a filename into [root, dir, basename, ext], unix version - // 'root' is just a slash, or nothing. - - - var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; - - var splitPath = function splitPath(filename) { - return splitPathRe.exec(filename).slice(1); - }; // path.resolve([from ...], to) - // posix version - - - function resolve() { - var resolvedPath = '', - resolvedAbsolute = false; - - for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? arguments[i] : '/'; // Skip empty and invalid entries - - if (typeof path !== 'string') { - throw new TypeError('Arguments to path.resolve must be strings'); - } else if (!path) { - continue; - } - - resolvedPath = path + '/' + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - - - resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function (p) { - return !!p; - }), !resolvedAbsolute).join('/'); - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; - } - // posix version - - function normalize$1(path) { - var isPathAbsolute = isAbsolute(path), - trailingSlash = substr(path, -1) === '/'; // Normalize the path - - path = normalizeArray(filter(path.split('/'), function (p) { - return !!p; - }), !isPathAbsolute).join('/'); - - if (!path && !isPathAbsolute) { - path = '.'; - } - - if (path && trailingSlash) { - path += '/'; - } - - return (isPathAbsolute ? '/' : '') + path; - } - - function isAbsolute(path) { - return path.charAt(0) === '/'; - } // posix version - - function join() { - var paths = Array.prototype.slice.call(arguments, 0); - return normalize$1(filter(paths, function (p, index) { - if (typeof p !== 'string') { - throw new TypeError('Arguments to path.join must be strings'); - } - - return p; - }).join('/')); - } // path.relative(from, to) - // posix version - - function relative(from, to) { - from = resolve(from).substr(1); - to = resolve(to).substr(1); - - function trim(arr) { - var start = 0; - - for (; start < arr.length; start++) { - if (arr[start] !== '') break; - } - - var end = arr.length - 1; - - for (; end >= 0; end--) { - if (arr[end] !== '') break; - } - - if (start > end) return []; - return arr.slice(start, end - start + 1); - } - - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; - } - } - - var outputParts = []; - - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join('/'); - } - var sep = '/'; - var delimiter = ':'; - function dirname(path) { - var result = splitPath(path), - root = result[0], - dir = result[1]; - - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - - return root + dir; - } - function basename(path, ext) { - var f = splitPath(path)[2]; // TODO: make this comparison case-insensitive on windows? - - if (ext && f.substr(-1 * ext.length) === ext) { - f = f.substr(0, f.length - ext.length); - } - - return f; - } - function extname(path) { - return splitPath(path)[3]; - } - var path$1 = { - extname: extname, - basename: basename, - dirname: dirname, - sep: sep, - delimiter: delimiter, - relative: relative, - join: join, - isAbsolute: isAbsolute, - normalize: normalize$1, - resolve: resolve - }; - - function filter(xs, f) { - if (xs.filter) return xs.filter(f); - var res = []; - - for (var i = 0; i < xs.length; i++) { - if (f(xs[i], i, xs)) res.push(xs[i]); - } - - return res; - } // String.prototype.substr - negative index don't work in IE8 - - - var substr = 'ab'.substr(-1) === 'b' ? function (str, start, len) { - return str.substr(start, len); - } : function (str, start, len) { - if (start < 0) start = str.length + start; - return str.substr(start, len); - }; - - // call something on iterator step with safe closing on error - var callWithSafeIterationClosing = function (iterator, fn, value, ENTRIES) { - try { - return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value); - // 7.4.6 IteratorClose(iterator, completion) - } catch (error) { - iteratorClose(iterator); - throw error; - } - }; - - // `Array.from` method implementation - // https://tc39.es/ecma262/#sec-array.from - var arrayFrom = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) { - var O = toObject(arrayLike); - var C = typeof this == 'function' ? this : Array; - var argumentsLength = arguments.length; - var mapfn = argumentsLength > 1 ? arguments[1] : undefined; - var mapping = mapfn !== undefined; - var iteratorMethod = getIteratorMethod(O); - var index = 0; - var length, result, step, iterator, next, value; - if (mapping) mapfn = functionBindContext(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2); - // if the target is not iterable or it's an array with the default iterator - use a simple case - if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) { - iterator = iteratorMethod.call(O); - next = iterator.next; - result = new C(); - for (;!(step = next.call(iterator)).done; index++) { - value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value; - createProperty(result, index, value); - } - } else { - length = toLength(O.length); - result = new C(length); - for (;length > index; index++) { - value = mapping ? mapfn(O[index], index) : O[index]; - createProperty(result, index, value); - } - } - result.length = index; - return result; - }; - - var INCORRECT_ITERATION$1 = !checkCorrectnessOfIteration(function (iterable) { - Array.from(iterable); - }); - - // `Array.from` method - // https://tc39.es/ecma262/#sec-array.from - _export({ target: 'Array', stat: true, forced: INCORRECT_ITERATION$1 }, { - from: arrayFrom - }); - - var diff = createCommonjsModule(function (module, exports) { - (function (global, factory) { - factory(exports) ; - })(commonjsGlobal, function (exports) { - - function Diff() {} - - Diff.prototype = { - diff: function diff(oldString, newString) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var callback = options.callback; - - if (typeof options === 'function') { - callback = options; - options = {}; - } - - this.options = options; - var self = this; - - function done(value) { - if (callback) { - setTimeout(function () { - callback(undefined, value); - }, 0); - return true; - } else { - return value; - } - } // Allow subclasses to massage the input prior to running - - - oldString = this.castInput(oldString); - newString = this.castInput(newString); - oldString = this.removeEmpty(this.tokenize(oldString)); - newString = this.removeEmpty(this.tokenize(newString)); - var newLen = newString.length, - oldLen = oldString.length; - var editLength = 1; - var maxEditLength = newLen + oldLen; - var bestPath = [{ - newPos: -1, - components: [] - }]; // Seed editLength = 0, i.e. the content starts with the same values - - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - - if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { - // Identity per the equality and tokenizer - return done([{ - value: this.join(newString), - count: newString.length - }]); - } // Main worker method. checks all permutations of a given edit length for acceptance. - - - function execEditLength() { - for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { - var basePath = void 0; - - var addPath = bestPath[diagonalPath - 1], - removePath = bestPath[diagonalPath + 1], - _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath - 1] = undefined; - } - - var canAdd = addPath && addPath.newPos + 1 < newLen, - canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; - - if (!canAdd && !canRemove) { - // If this path is a terminal then prune - bestPath[diagonalPath] = undefined; - continue; - } // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - - - if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { - basePath = clonePath(removePath); - self.pushComponent(basePath.components, undefined, true); - } else { - basePath = addPath; // No need to clone, we've pulled it from the list - - basePath.newPos++; - self.pushComponent(basePath.components, true, undefined); - } - - _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done - - if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { - return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); - } else { - // Otherwise track this path as a potential candidate and continue. - bestPath[diagonalPath] = basePath; - } - } - - editLength++; - } // Performs the length of edit iteration. Is a bit fugly as this has to support the - // sync and async mode which is never fun. Loops over execEditLength until a value - // is produced. - - - if (callback) { - (function exec() { - setTimeout(function () { - // This should not happen, but we want to be safe. - - /* istanbul ignore next */ - if (editLength > maxEditLength) { - return callback(); - } - - if (!execEditLength()) { - exec(); - } - }, 0); - })(); - } else { - while (editLength <= maxEditLength) { - var ret = execEditLength(); - - if (ret) { - return ret; - } - } - } - }, - pushComponent: function pushComponent(components, added, removed) { - var last = components[components.length - 1]; - - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length - 1] = { - count: last.count + 1, - added: added, - removed: removed - }; - } else { - components.push({ - count: 1, - added: added, - removed: removed - }); - } - }, - extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath, - commonCount = 0; - - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { - newPos++; - oldPos++; - commonCount++; - } - - if (commonCount) { - basePath.components.push({ - count: commonCount - }); - } - - basePath.newPos = newPos; - return oldPos; - }, - equals: function equals(left, right) { - if (this.options.comparator) { - return this.options.comparator(left, right); - } else { - return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); - } - }, - removeEmpty: function removeEmpty(array) { - var ret = []; - - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - - return ret; - }, - castInput: function castInput(value) { - return value; - }, - tokenize: function tokenize(value) { - return value.split(''); - }, - join: function join(chars) { - return chars.join(''); - } - }; - - function buildValues(diff, components, newString, oldString, useLongestToken) { - var componentPos = 0, - componentLen = components.length, - newPos = 0, - oldPos = 0; - - for (; componentPos < componentLen; componentPos++) { - var component = components[componentPos]; - - if (!component.removed) { - if (!component.added && useLongestToken) { - var value = newString.slice(newPos, newPos + component.count); - value = value.map(function (value, i) { - var oldValue = oldString[oldPos + i]; - return oldValue.length > value.length ? oldValue : value; - }); - component.value = diff.join(value); - } else { - component.value = diff.join(newString.slice(newPos, newPos + component.count)); - } - - newPos += component.count; // Common case - - if (!component.added) { - oldPos += component.count; - } - } else { - component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); - oldPos += component.count; // Reverse add and remove so removes are output first to match common convention - // The diffing algorithm is tied to add then remove output and this is the simplest - // route to get the desired output with minimal overhead. - - if (componentPos && components[componentPos - 1].added) { - var tmp = components[componentPos - 1]; - components[componentPos - 1] = components[componentPos]; - components[componentPos] = tmp; - } - } - } // Special case handle for when one terminal is ignored (i.e. whitespace). - // For this case we merge the terminal into the prior string and drop the change. - // This is only available for string mode. - - - var lastComponent = components[componentLen - 1]; - - if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { - components[componentLen - 2].value += lastComponent.value; - components.pop(); - } - - return components; - } - - function clonePath(path) { - return { - newPos: path.newPos, - components: path.components.slice(0) - }; - } - - var characterDiff = new Diff(); - - function diffChars(oldStr, newStr, options) { - return characterDiff.diff(oldStr, newStr, options); - } - - function generateOptions(options, defaults) { - if (typeof options === 'function') { - defaults.callback = options; - } else if (options) { - for (var name in options) { - /* istanbul ignore else */ - if (options.hasOwnProperty(name)) { - defaults[name] = options[name]; - } - } - } - - return defaults; - } // - // Ranges and exceptions: - // Latin-1 Supplement, 0080–00FF - // - U+00D7 × Multiplication sign - // - U+00F7 ÷ Division sign - // Latin Extended-A, 0100–017F - // Latin Extended-B, 0180–024F - // IPA Extensions, 0250–02AF - // Spacing Modifier Letters, 02B0–02FF - // - U+02C7 ˇ ˇ Caron - // - U+02D8 ˘ ˘ Breve - // - U+02D9 ˙ ˙ Dot Above - // - U+02DA ˚ ˚ Ring Above - // - U+02DB ˛ ˛ Ogonek - // - U+02DC ˜ ˜ Small Tilde - // - U+02DD ˝ ˝ Double Acute Accent - // Latin Extended Additional, 1E00–1EFF - - - var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; - var reWhitespace = /\S/; - var wordDiff = new Diff(); - - wordDiff.equals = function (left, right) { - if (this.options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); - } - - return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); - }; - - wordDiff.tokenize = function (value) { - // All whitespace symbols except newline group into one token, each newline - in separate token - var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. - - for (var i = 0; i < tokens.length - 1; i++) { - // If we have an empty string in the next field and we have only word chars before and after, merge - if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { - tokens[i] += tokens[i + 2]; - tokens.splice(i + 1, 2); - i--; - } - } - - return tokens; - }; - - function diffWords(oldStr, newStr, options) { - options = generateOptions(options, { - ignoreWhitespace: true - }); - return wordDiff.diff(oldStr, newStr, options); - } - - function diffWordsWithSpace(oldStr, newStr, options) { - return wordDiff.diff(oldStr, newStr, options); - } - - var lineDiff = new Diff(); - - lineDiff.tokenize = function (value) { - var retLines = [], - linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line - - if (!linesAndNewlines[linesAndNewlines.length - 1]) { - linesAndNewlines.pop(); - } // Merge the content and line separators into single tokens - - - for (var i = 0; i < linesAndNewlines.length; i++) { - var line = linesAndNewlines[i]; - - if (i % 2 && !this.options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } else { - if (this.options.ignoreWhitespace) { - line = line.trim(); - } - - retLines.push(line); - } - } - - return retLines; - }; - - function diffLines(oldStr, newStr, callback) { - return lineDiff.diff(oldStr, newStr, callback); - } - - function diffTrimmedLines(oldStr, newStr, callback) { - var options = generateOptions(callback, { - ignoreWhitespace: true - }); - return lineDiff.diff(oldStr, newStr, options); - } - - var sentenceDiff = new Diff(); - - sentenceDiff.tokenize = function (value) { - return value.split(/(\S.+?[.!?])(?=\s+|$)/); - }; - - function diffSentences(oldStr, newStr, callback) { - return sentenceDiff.diff(oldStr, newStr, callback); - } - - var cssDiff = new Diff(); - - cssDiff.tokenize = function (value) { - return value.split(/([{}:;,]|\s+)/); - }; - - function diffCss(oldStr, newStr, callback) { - return cssDiff.diff(oldStr, newStr, callback); - } - - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function _typeof(obj) { - return typeof obj; - }; - } else { - _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var objectPrototypeToString = Object.prototype.toString; - var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a - // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: - - jsonDiff.useLongestToken = true; - jsonDiff.tokenize = lineDiff.tokenize; - - jsonDiff.castInput = function (value) { - var _this$options = this.options, - undefinedReplacement = _this$options.undefinedReplacement, - _this$options$stringi = _this$options.stringifyReplacer, - stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) { - return typeof v === 'undefined' ? undefinedReplacement : v; - } : _this$options$stringi; - return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); - }; - - jsonDiff.equals = function (left, right) { - return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); - }; - - function diffJson(oldObj, newObj, options) { - return jsonDiff.diff(oldObj, newObj, options); - } // This function handles the presence of circular references by bailing out when encountering an - // object that is already on the "stack" of items being processed. Accepts an optional replacer - - - function canonicalize(obj, stack, replacementStack, replacer, key) { - stack = stack || []; - replacementStack = replacementStack || []; - - if (replacer) { - obj = replacer(key, obj); - } - - var i; - - for (i = 0; i < stack.length; i += 1) { - if (stack[i] === obj) { - return replacementStack[i]; - } - } - - var canonicalizedObj; - - if ('[object Array]' === objectPrototypeToString.call(obj)) { - stack.push(obj); - canonicalizedObj = new Array(obj.length); - replacementStack.push(canonicalizedObj); - - for (i = 0; i < obj.length; i += 1) { - canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); - } - - stack.pop(); - replacementStack.pop(); - return canonicalizedObj; - } - - if (obj && obj.toJSON) { - obj = obj.toJSON(); - } - - if (_typeof(obj) === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - replacementStack.push(canonicalizedObj); - - var sortedKeys = [], - _key; - - for (_key in obj) { - /* istanbul ignore else */ - if (obj.hasOwnProperty(_key)) { - sortedKeys.push(_key); - } - } - - sortedKeys.sort(); - - for (i = 0; i < sortedKeys.length; i += 1) { - _key = sortedKeys[i]; - canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); - } - - stack.pop(); - replacementStack.pop(); - } else { - canonicalizedObj = obj; - } - - return canonicalizedObj; - } - - var arrayDiff = new Diff(); - - arrayDiff.tokenize = function (value) { - return value.slice(); - }; - - arrayDiff.join = arrayDiff.removeEmpty = function (value) { - return value; - }; - - function diffArrays(oldArr, newArr, callback) { - return arrayDiff.diff(oldArr, newArr, callback); - } - - function parsePatch(uniDiff) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], - list = [], - i = 0; - - function parseIndex() { - var index = {}; - list.push(index); // Parse diff metadata - - while (i < diffstr.length) { - var line = diffstr[i]; // File header found, end parsing diff metadata - - if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { - break; - } // Diff index - - - var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); - - if (header) { - index.index = header[1]; - } - - i++; - } // Parse file headers if they are defined. Unified diff requires them, but - // there's no technical issues to have an isolated hunk without file header - - - parseFileHeader(index); - parseFileHeader(index); // Parse hunks - - index.hunks = []; - - while (i < diffstr.length) { - var _line = diffstr[i]; - - if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { - break; - } else if (/^@@/.test(_line)) { - index.hunks.push(parseHunk()); - } else if (_line && options.strict) { - // Ignore unexpected content unless in strict mode - throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); - } else { - i++; - } - } - } // Parses the --- and +++ headers, if none are found, no lines - // are consumed. - - - function parseFileHeader(index) { - var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); - - if (fileHeader) { - var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; - var data = fileHeader[2].split('\t', 2); - var fileName = data[0].replace(/\\\\/g, '\\'); - - if (/^".*"$/.test(fileName)) { - fileName = fileName.substr(1, fileName.length - 2); - } - - index[keyPrefix + 'FileName'] = fileName; - index[keyPrefix + 'Header'] = (data[1] || '').trim(); - i++; - } - } // Parses a hunk - // This assumes that we are at the start of a hunk. - - - function parseHunk() { - var chunkHeaderIndex = i, - chunkHeaderLine = diffstr[i++], - chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); - var hunk = { - oldStart: +chunkHeader[1], - oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], - newStart: +chunkHeader[3], - newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], - lines: [], - linedelimiters: [] - }; // Unified Diff Format quirk: If the chunk size is 0, - // the first number is one lower than one would expect. - // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 - - if (hunk.oldLines === 0) { - hunk.oldStart += 1; - } - - if (hunk.newLines === 0) { - hunk.newStart += 1; - } - - var addCount = 0, - removeCount = 0; - - for (; i < diffstr.length; i++) { - // Lines starting with '---' could be mistaken for the "remove line" operation - // But they could be the header for the next file. Therefore prune such cases out. - if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { - break; - } - - var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; - - if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { - hunk.lines.push(diffstr[i]); - hunk.linedelimiters.push(delimiters[i] || '\n'); - - if (operation === '+') { - addCount++; - } else if (operation === '-') { - removeCount++; - } else if (operation === ' ') { - addCount++; - removeCount++; - } - } else { - break; - } - } // Handle the empty block count case - - - if (!addCount && hunk.newLines === 1) { - hunk.newLines = 0; - } - - if (!removeCount && hunk.oldLines === 1) { - hunk.oldLines = 0; - } // Perform optional sanity checking - - - if (options.strict) { - if (addCount !== hunk.newLines) { - throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); - } - - if (removeCount !== hunk.oldLines) { - throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); - } - } - - return hunk; - } - - while (i < diffstr.length) { - parseIndex(); - } - - return list; - } // Iterator that traverses in the range of [min, max], stepping - // by distance from a given start position. I.e. for [0, 4], with - // start of 2, this will iterate 2, 3, 1, 4, 0. - - - function distanceIterator(start, minLine, maxLine) { - var wantForward = true, - backwardExhausted = false, - forwardExhausted = false, - localOffset = 1; - return function iterator() { - if (wantForward && !forwardExhausted) { - if (backwardExhausted) { - localOffset++; - } else { - wantForward = false; - } // Check if trying to fit beyond text length, and if not, check it fits - // after offset location (or desired location on first iteration) - - - if (start + localOffset <= maxLine) { - return localOffset; - } - - forwardExhausted = true; - } - - if (!backwardExhausted) { - if (!forwardExhausted) { - wantForward = true; - } // Check if trying to fit before text beginning, and if not, check it fits - // before offset location - - - if (minLine <= start - localOffset) { - return -localOffset++; - } - - backwardExhausted = true; - return iterator(); - } // We tried to fit hunk before text beginning and beyond text length, then - // hunk can't fit on the text. Return undefined - - }; - } - - function applyPatch(source, uniDiff) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - - if (typeof uniDiff === 'string') { - uniDiff = parsePatch(uniDiff); - } - - if (Array.isArray(uniDiff)) { - if (uniDiff.length > 1) { - throw new Error('applyPatch only works with a single input.'); - } - - uniDiff = uniDiff[0]; - } // Apply the diff to the input - - - var lines = source.split(/\r\n|[\n\v\f\r\x85]/), - delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], - hunks = uniDiff.hunks, - compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) { - return line === patchContent; - }, - errorCount = 0, - fuzzFactor = options.fuzzFactor || 0, - minLine = 0, - offset = 0, - removeEOFNL, - addEOFNL; - /** - * Checks if the hunk exactly fits on the provided location - */ - - - function hunkFits(hunk, toPos) { - for (var j = 0; j < hunk.lines.length; j++) { - var line = hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line; - - if (operation === ' ' || operation === '-') { - // Context sanity check - if (!compareLine(toPos + 1, lines[toPos], operation, content)) { - errorCount++; - - if (errorCount > fuzzFactor) { - return false; - } - } - - toPos++; - } - } - - return true; - } // Search best fit offsets for each hunk based on the previous ones - - - for (var i = 0; i < hunks.length; i++) { - var hunk = hunks[i], - maxLine = lines.length - hunk.oldLines, - localOffset = 0, - toPos = offset + hunk.oldStart - 1; - var iterator = distanceIterator(toPos, minLine, maxLine); - - for (; localOffset !== undefined; localOffset = iterator()) { - if (hunkFits(hunk, toPos + localOffset)) { - hunk.offset = offset += localOffset; - break; - } - } - - if (localOffset === undefined) { - return false; - } // Set lower text limit to end of the current hunk, so next ones don't try - // to fit over already patched text - - - minLine = hunk.offset + hunk.oldStart + hunk.oldLines; - } // Apply patch hunks - - - var diffOffset = 0; - - for (var _i = 0; _i < hunks.length; _i++) { - var _hunk = hunks[_i], - _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; - - diffOffset += _hunk.newLines - _hunk.oldLines; - - for (var j = 0; j < _hunk.lines.length; j++) { - var line = _hunk.lines[j], - operation = line.length > 0 ? line[0] : ' ', - content = line.length > 0 ? line.substr(1) : line, - delimiter = _hunk.linedelimiters[j]; - - if (operation === ' ') { - _toPos++; - } else if (operation === '-') { - lines.splice(_toPos, 1); - delimiters.splice(_toPos, 1); - /* istanbul ignore else */ - } else if (operation === '+') { - lines.splice(_toPos, 0, content); - delimiters.splice(_toPos, 0, delimiter); - _toPos++; - } else if (operation === '\\') { - var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; - - if (previousOperation === '+') { - removeEOFNL = true; - } else if (previousOperation === '-') { - addEOFNL = true; - } - } - } - } // Handle EOFNL insertion/removal - - - if (removeEOFNL) { - while (!lines[lines.length - 1]) { - lines.pop(); - delimiters.pop(); - } - } else if (addEOFNL) { - lines.push(''); - delimiters.push('\n'); - } - - for (var _k = 0; _k < lines.length - 1; _k++) { - lines[_k] = lines[_k] + delimiters[_k]; - } - - return lines.join(''); - } // Wrapper that supports multiple file patches via callbacks. - - - function applyPatches(uniDiff, options) { - if (typeof uniDiff === 'string') { - uniDiff = parsePatch(uniDiff); - } - - var currentIndex = 0; - - function processIndex() { - var index = uniDiff[currentIndex++]; - - if (!index) { - return options.complete(); - } - - options.loadFile(index, function (err, data) { - if (err) { - return options.complete(err); - } - - var updatedContent = applyPatch(data, index, options); - options.patched(index, updatedContent, function (err) { - if (err) { - return options.complete(err); - } - - processIndex(); - }); - }); - } - - processIndex(); - } - - function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (!options) { - options = {}; - } - - if (typeof options.context === 'undefined') { - options.context = 4; - } - - var diff = diffLines(oldStr, newStr, options); - diff.push({ - value: '', - lines: [] - }); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function (entry) { - return ' ' + entry; - }); - } - - var hunks = []; - var oldRangeStart = 0, - newRangeStart = 0, - curRange = [], - oldLine = 1, - newLine = 1; - - var _loop = function _loop(i) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - var _curRange; // If we have previous context, start with that - - - if (!oldRangeStart) { - var prev = diff[i - 1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } // Output our changes - - - (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) { - return (current.added ? '+' : '-') + entry; - }))); // Track the updated file position - - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - // Identical context lines. Track line changes - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= options.context * 2 && i < diff.length - 2) { - var _curRange2; // Overlapping - - - (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines))); - } else { - var _curRange3; // end the range and output - - - var contextSize = Math.min(lines.length, options.context); - - (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize)))); - - var hunk = { - oldStart: oldRangeStart, - oldLines: oldLine - oldRangeStart + contextSize, - newStart: newRangeStart, - newLines: newLine - newRangeStart + contextSize, - lines: curRange - }; - - if (i >= diff.length - 2 && lines.length <= options.context) { - // EOF is inside this hunk - var oldEOFNewline = /\n$/.test(oldStr); - var newEOFNewline = /\n$/.test(newStr); - var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; - - if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { - // special case: old has no eol and no trailing context; no-nl can end up before adds - // however, if the old file is empty, do not output the no-nl line - curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); - } - - if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { - curRange.push('\\ No newline at end of file'); - } - } - - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - - oldLine += lines.length; - newLine += lines.length; - } - }; - - for (var i = 0; i < diff.length; i++) { - _loop(i); - } - - return { - oldFileName: oldFileName, - newFileName: newFileName, - oldHeader: oldHeader, - newHeader: newHeader, - hunks: hunks - }; - } - - function formatPatch(diff) { - var ret = []; - - if (diff.oldFileName == diff.newFileName) { - ret.push('Index: ' + diff.oldFileName); - } - - ret.push('==================================================================='); - ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); - ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); - - for (var i = 0; i < diff.hunks.length; i++) { - var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, - // the first number is one lower than one would expect. - // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 - - if (hunk.oldLines === 0) { - hunk.oldStart -= 1; - } - - if (hunk.newLines === 0) { - hunk.newStart -= 1; - } - - ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); - ret.push.apply(ret, hunk.lines); - } - - return ret.join('\n') + '\n'; - } - - function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); - } - - function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); - } - - function arrayEqual(a, b) { - if (a.length !== b.length) { - return false; - } - - return arrayStartsWith(a, b); - } - - function arrayStartsWith(array, start) { - if (start.length > array.length) { - return false; - } - - for (var i = 0; i < start.length; i++) { - if (start[i] !== array[i]) { - return false; - } - } - - return true; - } - - function calcLineCount(hunk) { - var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines), - oldLines = _calcOldNewLineCount.oldLines, - newLines = _calcOldNewLineCount.newLines; - - if (oldLines !== undefined) { - hunk.oldLines = oldLines; - } else { - delete hunk.oldLines; - } - - if (newLines !== undefined) { - hunk.newLines = newLines; - } else { - delete hunk.newLines; - } - } - - function merge(mine, theirs, base) { - mine = loadPatch(mine, base); - theirs = loadPatch(theirs, base); - var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. - // Leaving sanity checks on this to the API consumer that may know more about the - // meaning in their own context. - - if (mine.index || theirs.index) { - ret.index = mine.index || theirs.index; - } - - if (mine.newFileName || theirs.newFileName) { - if (!fileNameChanged(mine)) { - // No header or no change in ours, use theirs (and ours if theirs does not exist) - ret.oldFileName = theirs.oldFileName || mine.oldFileName; - ret.newFileName = theirs.newFileName || mine.newFileName; - ret.oldHeader = theirs.oldHeader || mine.oldHeader; - ret.newHeader = theirs.newHeader || mine.newHeader; - } else if (!fileNameChanged(theirs)) { - // No header or no change in theirs, use ours - ret.oldFileName = mine.oldFileName; - ret.newFileName = mine.newFileName; - ret.oldHeader = mine.oldHeader; - ret.newHeader = mine.newHeader; - } else { - // Both changed... figure it out - ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); - ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); - ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); - ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); - } - } - - ret.hunks = []; - var mineIndex = 0, - theirsIndex = 0, - mineOffset = 0, - theirsOffset = 0; - - while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { - var mineCurrent = mine.hunks[mineIndex] || { - oldStart: Infinity - }, - theirsCurrent = theirs.hunks[theirsIndex] || { - oldStart: Infinity - }; - - if (hunkBefore(mineCurrent, theirsCurrent)) { - // This patch does not overlap with any of the others, yay. - ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); - mineIndex++; - theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; - } else if (hunkBefore(theirsCurrent, mineCurrent)) { - // This patch does not overlap with any of the others, yay. - ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); - theirsIndex++; - mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; - } else { - // Overlap, merge as best we can - var mergedHunk = { - oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), - oldLines: 0, - newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), - newLines: 0, - lines: [] - }; - mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); - theirsIndex++; - mineIndex++; - ret.hunks.push(mergedHunk); - } - } - - return ret; - } - - function loadPatch(param, base) { - if (typeof param === 'string') { - if (/^@@/m.test(param) || /^Index:/m.test(param)) { - return parsePatch(param)[0]; - } - - if (!base) { - throw new Error('Must provide a base reference or pass in a patch'); - } - - return structuredPatch(undefined, undefined, base, param); - } - - return param; - } - - function fileNameChanged(patch) { - return patch.newFileName && patch.newFileName !== patch.oldFileName; - } - - function selectField(index, mine, theirs) { - if (mine === theirs) { - return mine; - } else { - index.conflict = true; - return { - mine: mine, - theirs: theirs - }; - } - } - - function hunkBefore(test, check) { - return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; - } - - function cloneHunk(hunk, offset) { - return { - oldStart: hunk.oldStart, - oldLines: hunk.oldLines, - newStart: hunk.newStart + offset, - newLines: hunk.newLines, - lines: hunk.lines - }; - } - - function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { - // This will generally result in a conflicted hunk, but there are cases where the context - // is the only overlap where we can successfully merge the content here. - var mine = { - offset: mineOffset, - lines: mineLines, - index: 0 - }, - their = { - offset: theirOffset, - lines: theirLines, - index: 0 - }; // Handle any leading content - - insertLeading(hunk, mine, their); - insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. - - while (mine.index < mine.lines.length && their.index < their.lines.length) { - var mineCurrent = mine.lines[mine.index], - theirCurrent = their.lines[their.index]; - - if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { - // Both modified ... - mutualChange(hunk, mine, their); - } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { - var _hunk$lines; // Mine inserted - - - (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine))); - } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { - var _hunk$lines2; // Theirs inserted - - - (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their))); - } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { - // Mine removed or edited - removal(hunk, mine, their); - } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { - // Their removed or edited - removal(hunk, their, mine, true); - } else if (mineCurrent === theirCurrent) { - // Context identity - hunk.lines.push(mineCurrent); - mine.index++; - their.index++; - } else { - // Context mismatch - conflict(hunk, collectChange(mine), collectChange(their)); - } - } // Now push anything that may be remaining - - - insertTrailing(hunk, mine); - insertTrailing(hunk, their); - calcLineCount(hunk); - } - - function mutualChange(hunk, mine, their) { - var myChanges = collectChange(mine), - theirChanges = collectChange(their); - - if (allRemoves(myChanges) && allRemoves(theirChanges)) { - // Special case for remove changes that are supersets of one another - if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { - var _hunk$lines3; - - (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges)); - - return; - } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { - var _hunk$lines4; - - (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges)); - - return; - } - } else if (arrayEqual(myChanges, theirChanges)) { - var _hunk$lines5; - - (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges)); - - return; - } - - conflict(hunk, myChanges, theirChanges); - } - - function removal(hunk, mine, their, swap) { - var myChanges = collectChange(mine), - theirChanges = collectContext(their, myChanges); - - if (theirChanges.merged) { - var _hunk$lines6; - - (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged)); - } else { - conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); - } - } - - function conflict(hunk, mine, their) { - hunk.conflict = true; - hunk.lines.push({ - conflict: true, - mine: mine, - theirs: their - }); - } - - function insertLeading(hunk, insert, their) { - while (insert.offset < their.offset && insert.index < insert.lines.length) { - var line = insert.lines[insert.index++]; - hunk.lines.push(line); - insert.offset++; - } - } - - function insertTrailing(hunk, insert) { - while (insert.index < insert.lines.length) { - var line = insert.lines[insert.index++]; - hunk.lines.push(line); - } - } - - function collectChange(state) { - var ret = [], - operation = state.lines[state.index][0]; - - while (state.index < state.lines.length) { - var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. - - if (operation === '-' && line[0] === '+') { - operation = '+'; - } - - if (operation === line[0]) { - ret.push(line); - state.index++; - } else { - break; - } - } - - return ret; - } - - function collectContext(state, matchChanges) { - var changes = [], - merged = [], - matchIndex = 0, - contextChanges = false, - conflicted = false; - - while (matchIndex < matchChanges.length && state.index < state.lines.length) { - var change = state.lines[state.index], - match = matchChanges[matchIndex]; // Once we've hit our add, then we are done - - if (match[0] === '+') { - break; - } - - contextChanges = contextChanges || change[0] !== ' '; - merged.push(match); - matchIndex++; // Consume any additions in the other block as a conflict to attempt - // to pull in the remaining context after this - - if (change[0] === '+') { - conflicted = true; - - while (change[0] === '+') { - changes.push(change); - change = state.lines[++state.index]; - } - } - - if (match.substr(1) === change.substr(1)) { - changes.push(change); - state.index++; - } else { - conflicted = true; - } - } - - if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { - conflicted = true; - } - - if (conflicted) { - return changes; - } - - while (matchIndex < matchChanges.length) { - merged.push(matchChanges[matchIndex++]); - } - - return { - merged: merged, - changes: changes - }; - } - - function allRemoves(changes) { - return changes.reduce(function (prev, change) { - return prev && change[0] === '-'; - }, true); - } - - function skipRemoveSuperset(state, removeChanges, delta) { - for (var i = 0; i < delta; i++) { - var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); - - if (state.lines[state.index + i] !== ' ' + changeContent) { - return false; - } - } - - state.index += delta; - return true; - } - - function calcOldNewLineCount(lines) { - var oldLines = 0; - var newLines = 0; - lines.forEach(function (line) { - if (typeof line !== 'string') { - var myCount = calcOldNewLineCount(line.mine); - var theirCount = calcOldNewLineCount(line.theirs); - - if (oldLines !== undefined) { - if (myCount.oldLines === theirCount.oldLines) { - oldLines += myCount.oldLines; - } else { - oldLines = undefined; - } - } - - if (newLines !== undefined) { - if (myCount.newLines === theirCount.newLines) { - newLines += myCount.newLines; - } else { - newLines = undefined; - } - } - } else { - if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { - newLines++; - } - - if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { - oldLines++; - } - } - }); - return { - oldLines: oldLines, - newLines: newLines - }; - } // See: http://code.google.com/p/google-diff-match-patch/wiki/API - - - function convertChangesToDMP(changes) { - var ret = [], - change, - operation; - - for (var i = 0; i < changes.length; i++) { - change = changes[i]; - - if (change.added) { - operation = 1; - } else if (change.removed) { - operation = -1; - } else { - operation = 0; - } - - ret.push([operation, change.value]); - } - - return ret; - } - - function convertChangesToXML(changes) { - var ret = []; - - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - } - - return ret.join(''); - } - - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(//g, '>'); - n = n.replace(/"/g, '"'); - return n; - } - - exports.Diff = Diff; - exports.applyPatch = applyPatch; - exports.applyPatches = applyPatches; - exports.canonicalize = canonicalize; - exports.convertChangesToDMP = convertChangesToDMP; - exports.convertChangesToXML = convertChangesToXML; - exports.createPatch = createPatch; - exports.createTwoFilesPatch = createTwoFilesPatch; - exports.diffArrays = diffArrays; - exports.diffChars = diffChars; - exports.diffCss = diffCss; - exports.diffJson = diffJson; - exports.diffLines = diffLines; - exports.diffSentences = diffSentences; - exports.diffTrimmedLines = diffTrimmedLines; - exports.diffWords = diffWords; - exports.diffWordsWithSpace = diffWordsWithSpace; - exports.merge = merge; - exports.parsePatch = parsePatch; - exports.structuredPatch = structuredPatch; - Object.defineProperty(exports, '__esModule', { - value: true - }); - }); - }); - - /** - * Helpers. - */ - var s = 1000; - var m = s * 60; - var h = m * 60; - var d = h * 24; - var w = d * 7; - var y = d * 365.25; - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - - var ms = function ms(val, options) { - options = options || {}; - - var type = _typeof(val); - - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options["long"] ? fmtLong(val) : fmtShort(val); - } - - throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)); - }; - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - - function parse(str) { - str = String(str); - - if (str.length > 100) { - return; - } - - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); - - if (!match) { - return; - } - - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - - case 'weeks': - case 'week': - case 'w': - return n * w; - - case 'days': - case 'day': - case 'd': - return n * d; - - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - - default: - return undefined; - } - } - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - - function fmtShort(ms) { - var msAbs = Math.abs(ms); - - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - - return ms + 'ms'; - } - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - - function fmtLong(ms) { - var msAbs = Math.abs(ms); - - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - - return ms + ' ms'; - } - /** - * Pluralization helper. - */ - - - function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); - } - - var freezing = !fails(function () { - return Object.isExtensible(Object.preventExtensions({})); - }); - - var internalMetadata = createCommonjsModule(function (module) { - var defineProperty = objectDefineProperty.f; - - - - var METADATA = uid('meta'); - var id = 0; - - var isExtensible = Object.isExtensible || function () { - return true; - }; - - var setMetadata = function (it) { - defineProperty(it, METADATA, { value: { - objectID: 'O' + ++id, // object ID - weakData: {} // weak collections IDs - } }); - }; - - var fastKey = function (it, create) { - // return a primitive with prefix - if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; - if (!has(it, METADATA)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return 'F'; - // not necessary to add metadata - if (!create) return 'E'; - // add missing metadata - setMetadata(it); - // return object ID - } return it[METADATA].objectID; - }; - - var getWeakData = function (it, create) { - if (!has(it, METADATA)) { - // can't set metadata to uncaught frozen object - if (!isExtensible(it)) return true; - // not necessary to add metadata - if (!create) return false; - // add missing metadata - setMetadata(it); - // return the store of weak collections IDs - } return it[METADATA].weakData; - }; - - // add metadata on freeze-family methods calling - var onFreeze = function (it) { - if (freezing && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it); - return it; - }; - - var meta = module.exports = { - REQUIRED: false, - fastKey: fastKey, - getWeakData: getWeakData, - onFreeze: onFreeze - }; - - hiddenKeys[METADATA] = true; - }); - - var onFreeze = internalMetadata.onFreeze; - - var nativeFreeze = Object.freeze; - var FAILS_ON_PRIMITIVES$4 = fails(function () { nativeFreeze(1); }); - - // `Object.freeze` method - // https://tc39.es/ecma262/#sec-object.freeze - _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES$4, sham: !freezing }, { - freeze: function freeze(it) { - return nativeFreeze && isObject(it) ? nativeFreeze(onFreeze(it)) : it; - } - }); - - var collection = function (CONSTRUCTOR_NAME, wrapper, common) { - var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1; - var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1; - var ADDER = IS_MAP ? 'set' : 'add'; - var NativeConstructor = global_1[CONSTRUCTOR_NAME]; - var NativePrototype = NativeConstructor && NativeConstructor.prototype; - var Constructor = NativeConstructor; - var exported = {}; - - var fixMethod = function (KEY) { - var nativeMethod = NativePrototype[KEY]; - redefine(NativePrototype, KEY, - KEY == 'add' ? function add(value) { - nativeMethod.call(this, value === 0 ? 0 : value); - return this; - } : KEY == 'delete' ? function (key) { - return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); - } : KEY == 'get' ? function get(key) { - return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key); - } : KEY == 'has' ? function has(key) { - return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key); - } : function set(key, value) { - nativeMethod.call(this, key === 0 ? 0 : key, value); - return this; - } - ); - }; - - // eslint-disable-next-line max-len - if (isForced_1(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () { - new NativeConstructor().entries().next(); - })))) { - // create collection constructor - Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER); - internalMetadata.REQUIRED = true; - } else if (isForced_1(CONSTRUCTOR_NAME, true)) { - var instance = new Constructor(); - // early implementations not supports chaining - var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance; - // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false - var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); }); - // most early implementations doesn't supports iterables, most modern - not close it correctly - // eslint-disable-next-line no-new - var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); }); - // for early implementations -0 and +0 not the same - var BUGGY_ZERO = !IS_WEAK && fails(function () { - // V8 ~ Chromium 42- fails only with 5+ elements - var $instance = new NativeConstructor(); - var index = 5; - while (index--) $instance[ADDER](index, index); - return !$instance.has(-0); - }); - - if (!ACCEPT_ITERABLES) { - Constructor = wrapper(function (dummy, iterable) { - anInstance(dummy, Constructor, CONSTRUCTOR_NAME); - var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor); - if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); - return that; - }); - Constructor.prototype = NativePrototype; - NativePrototype.constructor = Constructor; - } - - if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) { - fixMethod('delete'); - fixMethod('has'); - IS_MAP && fixMethod('get'); - } - - if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER); - - // weak collections should not contains .clear method - if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear; - } - - exported[CONSTRUCTOR_NAME] = Constructor; - _export({ global: true, forced: Constructor != NativeConstructor }, exported); - - setToStringTag(Constructor, CONSTRUCTOR_NAME); - - if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP); - - return Constructor; - }; - - var defineProperty$a = objectDefineProperty.f; - - - - - - - - - var fastKey = internalMetadata.fastKey; - - - var setInternalState$6 = internalState.set; - var internalStateGetterFor = internalState.getterFor; - - var collectionStrong = { - getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) { - var C = wrapper(function (that, iterable) { - anInstance(that, C, CONSTRUCTOR_NAME); - setInternalState$6(that, { - type: CONSTRUCTOR_NAME, - index: objectCreate(null), - first: undefined, - last: undefined, - size: 0 - }); - if (!descriptors) that.size = 0; - if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP }); - }); - - var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME); - - var define = function (that, key, value) { - var state = getInternalState(that); - var entry = getEntry(that, key); - var previous, index; - // change existing entry - if (entry) { - entry.value = value; - // create new entry - } else { - state.last = entry = { - index: index = fastKey(key, true), - key: key, - value: value, - previous: previous = state.last, - next: undefined, - removed: false - }; - if (!state.first) state.first = entry; - if (previous) previous.next = entry; - if (descriptors) state.size++; - else that.size++; - // add to index - if (index !== 'F') state.index[index] = entry; - } return that; - }; - - var getEntry = function (that, key) { - var state = getInternalState(that); - // fast case - var index = fastKey(key); - var entry; - if (index !== 'F') return state.index[index]; - // frozen object case - for (entry = state.first; entry; entry = entry.next) { - if (entry.key == key) return entry; - } - }; - - redefineAll(C.prototype, { - // 23.1.3.1 Map.prototype.clear() - // 23.2.3.2 Set.prototype.clear() - clear: function clear() { - var that = this; - var state = getInternalState(that); - var data = state.index; - var entry = state.first; - while (entry) { - entry.removed = true; - if (entry.previous) entry.previous = entry.previous.next = undefined; - delete data[entry.index]; - entry = entry.next; - } - state.first = state.last = undefined; - if (descriptors) state.size = 0; - else that.size = 0; - }, - // 23.1.3.3 Map.prototype.delete(key) - // 23.2.3.4 Set.prototype.delete(value) - 'delete': function (key) { - var that = this; - var state = getInternalState(that); - var entry = getEntry(that, key); - if (entry) { - var next = entry.next; - var prev = entry.previous; - delete state.index[entry.index]; - entry.removed = true; - if (prev) prev.next = next; - if (next) next.previous = prev; - if (state.first == entry) state.first = next; - if (state.last == entry) state.last = prev; - if (descriptors) state.size--; - else that.size--; - } return !!entry; - }, - // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) - // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) - forEach: function forEach(callbackfn /* , that = undefined */) { - var state = getInternalState(this); - var boundFunction = functionBindContext(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3); - var entry; - while (entry = entry ? entry.next : state.first) { - boundFunction(entry.value, entry.key, this); - // revert to the last existing entry - while (entry && entry.removed) entry = entry.previous; - } - }, - // 23.1.3.7 Map.prototype.has(key) - // 23.2.3.7 Set.prototype.has(value) - has: function has(key) { - return !!getEntry(this, key); - } - }); - - redefineAll(C.prototype, IS_MAP ? { - // 23.1.3.6 Map.prototype.get(key) - get: function get(key) { - var entry = getEntry(this, key); - return entry && entry.value; - }, - // 23.1.3.9 Map.prototype.set(key, value) - set: function set(key, value) { - return define(this, key === 0 ? 0 : key, value); - } - } : { - // 23.2.3.1 Set.prototype.add(value) - add: function add(value) { - return define(this, value = value === 0 ? 0 : value, value); - } - }); - if (descriptors) defineProperty$a(C.prototype, 'size', { - get: function () { - return getInternalState(this).size; - } - }); - return C; - }, - setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) { - var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator'; - var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME); - var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME); - // add .keys, .values, .entries, [@@iterator] - // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 - defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) { - setInternalState$6(this, { - type: ITERATOR_NAME, - target: iterated, - state: getInternalCollectionState(iterated), - kind: kind, - last: undefined - }); - }, function () { - var state = getInternalIteratorState(this); - var kind = state.kind; - var entry = state.last; - // revert to the last existing entry - while (entry && entry.removed) entry = entry.previous; - // get next entry - if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) { - // or finish the iteration - state.target = undefined; - return { value: undefined, done: true }; - } - // return step by kind - if (kind == 'keys') return { value: entry.key, done: false }; - if (kind == 'values') return { value: entry.value, done: false }; - return { value: [entry.key, entry.value], done: false }; - }, IS_MAP ? 'entries' : 'values', !IS_MAP, true); - - // add [@@species], 23.1.2.2, 23.2.2.2 - setSpecies(CONSTRUCTOR_NAME); - } - }; - - // `Set` constructor - // https://tc39.es/ecma262/#sec-set-objects - collection('Set', function (init) { - return function Set() { return init(this, arguments.length ? arguments[0] : undefined); }; - }, collectionStrong); - - var browser$1 = true; - - // This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped - // optimize the gzip compression for this alphabet. - var urlAlphabet = 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'; - - var customAlphabet = function customAlphabet(alphabet, size) { - return function () { - var id = ''; // A compact alternative for `for (var i = 0; i < step; i++)`. - - var i = size; - - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += alphabet[Math.random() * alphabet.length | 0]; - } - - return id; - }; - }; - - var nanoid = function nanoid() { - var size = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 21; - var id = ''; // A compact alternative for `for (var i = 0; i < step; i++)`. - - var i = size; - - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += urlAlphabet[Math.random() * 64 | 0]; - } - - return id; - }; - - var nonSecure = /*#__PURE__*/Object.freeze({ - __proto__: null, - nanoid: nanoid, - customAlphabet: customAlphabet - }); - - var he = createCommonjsModule(function (module, exports) { - - (function (root) { - // Detect free variables `exports`. - var freeExports = exports; // Detect free variable `module`. - - var freeModule = module && module.exports == freeExports && module; // Detect free variable `global`, from Node.js or Browserified code, - // and use it as `root`. - - var freeGlobal = _typeof(commonjsGlobal) == 'object' && commonjsGlobal; - - if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { - root = freeGlobal; - } - /*--------------------------------------------------------------------------*/ - // All astral symbols. - - - var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; // All ASCII symbols (not just printable ASCII) except those listed in the - // first column of the overrides table. - // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides - - var regexAsciiWhitelist = /[\x01-\x7F]/g; // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or - // code points listed in the first column of the overrides table on - // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides. - - var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; - var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g; - var encodeMap = { - '\xAD': 'shy', - "\u200C": 'zwnj', - "\u200D": 'zwj', - "\u200E": 'lrm', - "\u2063": 'ic', - "\u2062": 'it', - "\u2061": 'af', - "\u200F": 'rlm', - "\u200B": 'ZeroWidthSpace', - "\u2060": 'NoBreak', - "\u0311": 'DownBreve', - "\u20DB": 'tdot', - "\u20DC": 'DotDot', - '\t': 'Tab', - '\n': 'NewLine', - "\u2008": 'puncsp', - "\u205F": 'MediumSpace', - "\u2009": 'thinsp', - "\u200A": 'hairsp', - "\u2004": 'emsp13', - "\u2002": 'ensp', - "\u2005": 'emsp14', - "\u2003": 'emsp', - "\u2007": 'numsp', - '\xA0': 'nbsp', - "\u205F\u200A": 'ThickSpace', - "\u203E": 'oline', - '_': 'lowbar', - "\u2010": 'dash', - "\u2013": 'ndash', - "\u2014": 'mdash', - "\u2015": 'horbar', - ',': 'comma', - ';': 'semi', - "\u204F": 'bsemi', - ':': 'colon', - "\u2A74": 'Colone', - '!': 'excl', - '\xA1': 'iexcl', - '?': 'quest', - '\xBF': 'iquest', - '.': 'period', - "\u2025": 'nldr', - "\u2026": 'mldr', - '\xB7': 'middot', - '\'': 'apos', - "\u2018": 'lsquo', - "\u2019": 'rsquo', - "\u201A": 'sbquo', - "\u2039": 'lsaquo', - "\u203A": 'rsaquo', - '"': 'quot', - "\u201C": 'ldquo', - "\u201D": 'rdquo', - "\u201E": 'bdquo', - '\xAB': 'laquo', - '\xBB': 'raquo', - '(': 'lpar', - ')': 'rpar', - '[': 'lsqb', - ']': 'rsqb', - '{': 'lcub', - '}': 'rcub', - "\u2308": 'lceil', - "\u2309": 'rceil', - "\u230A": 'lfloor', - "\u230B": 'rfloor', - "\u2985": 'lopar', - "\u2986": 'ropar', - "\u298B": 'lbrke', - "\u298C": 'rbrke', - "\u298D": 'lbrkslu', - "\u298E": 'rbrksld', - "\u298F": 'lbrksld', - "\u2990": 'rbrkslu', - "\u2991": 'langd', - "\u2992": 'rangd', - "\u2993": 'lparlt', - "\u2994": 'rpargt', - "\u2995": 'gtlPar', - "\u2996": 'ltrPar', - "\u27E6": 'lobrk', - "\u27E7": 'robrk', - "\u27E8": 'lang', - "\u27E9": 'rang', - "\u27EA": 'Lang', - "\u27EB": 'Rang', - "\u27EC": 'loang', - "\u27ED": 'roang', - "\u2772": 'lbbrk', - "\u2773": 'rbbrk', - "\u2016": 'Vert', - '\xA7': 'sect', - '\xB6': 'para', - '@': 'commat', - '*': 'ast', - '/': 'sol', - 'undefined': null, - '&': 'amp', - '#': 'num', - '%': 'percnt', - "\u2030": 'permil', - "\u2031": 'pertenk', - "\u2020": 'dagger', - "\u2021": 'Dagger', - "\u2022": 'bull', - "\u2043": 'hybull', - "\u2032": 'prime', - "\u2033": 'Prime', - "\u2034": 'tprime', - "\u2057": 'qprime', - "\u2035": 'bprime', - "\u2041": 'caret', - '`': 'grave', - '\xB4': 'acute', - "\u02DC": 'tilde', - '^': 'Hat', - '\xAF': 'macr', - "\u02D8": 'breve', - "\u02D9": 'dot', - '\xA8': 'die', - "\u02DA": 'ring', - "\u02DD": 'dblac', - '\xB8': 'cedil', - "\u02DB": 'ogon', - "\u02C6": 'circ', - "\u02C7": 'caron', - '\xB0': 'deg', - '\xA9': 'copy', - '\xAE': 'reg', - "\u2117": 'copysr', - "\u2118": 'wp', - "\u211E": 'rx', - "\u2127": 'mho', - "\u2129": 'iiota', - "\u2190": 'larr', - "\u219A": 'nlarr', - "\u2192": 'rarr', - "\u219B": 'nrarr', - "\u2191": 'uarr', - "\u2193": 'darr', - "\u2194": 'harr', - "\u21AE": 'nharr', - "\u2195": 'varr', - "\u2196": 'nwarr', - "\u2197": 'nearr', - "\u2198": 'searr', - "\u2199": 'swarr', - "\u219D": 'rarrw', - "\u219D\u0338": 'nrarrw', - "\u219E": 'Larr', - "\u219F": 'Uarr', - "\u21A0": 'Rarr', - "\u21A1": 'Darr', - "\u21A2": 'larrtl', - "\u21A3": 'rarrtl', - "\u21A4": 'mapstoleft', - "\u21A5": 'mapstoup', - "\u21A6": 'map', - "\u21A7": 'mapstodown', - "\u21A9": 'larrhk', - "\u21AA": 'rarrhk', - "\u21AB": 'larrlp', - "\u21AC": 'rarrlp', - "\u21AD": 'harrw', - "\u21B0": 'lsh', - "\u21B1": 'rsh', - "\u21B2": 'ldsh', - "\u21B3": 'rdsh', - "\u21B5": 'crarr', - "\u21B6": 'cularr', - "\u21B7": 'curarr', - "\u21BA": 'olarr', - "\u21BB": 'orarr', - "\u21BC": 'lharu', - "\u21BD": 'lhard', - "\u21BE": 'uharr', - "\u21BF": 'uharl', - "\u21C0": 'rharu', - "\u21C1": 'rhard', - "\u21C2": 'dharr', - "\u21C3": 'dharl', - "\u21C4": 'rlarr', - "\u21C5": 'udarr', - "\u21C6": 'lrarr', - "\u21C7": 'llarr', - "\u21C8": 'uuarr', - "\u21C9": 'rrarr', - "\u21CA": 'ddarr', - "\u21CB": 'lrhar', - "\u21CC": 'rlhar', - "\u21D0": 'lArr', - "\u21CD": 'nlArr', - "\u21D1": 'uArr', - "\u21D2": 'rArr', - "\u21CF": 'nrArr', - "\u21D3": 'dArr', - "\u21D4": 'iff', - "\u21CE": 'nhArr', - "\u21D5": 'vArr', - "\u21D6": 'nwArr', - "\u21D7": 'neArr', - "\u21D8": 'seArr', - "\u21D9": 'swArr', - "\u21DA": 'lAarr', - "\u21DB": 'rAarr', - "\u21DD": 'zigrarr', - "\u21E4": 'larrb', - "\u21E5": 'rarrb', - "\u21F5": 'duarr', - "\u21FD": 'loarr', - "\u21FE": 'roarr', - "\u21FF": 'hoarr', - "\u2200": 'forall', - "\u2201": 'comp', - "\u2202": 'part', - "\u2202\u0338": 'npart', - "\u2203": 'exist', - "\u2204": 'nexist', - "\u2205": 'empty', - "\u2207": 'Del', - "\u2208": 'in', - "\u2209": 'notin', - "\u220B": 'ni', - "\u220C": 'notni', - "\u03F6": 'bepsi', - "\u220F": 'prod', - "\u2210": 'coprod', - "\u2211": 'sum', - '+': 'plus', - '\xB1': 'pm', - '\xF7': 'div', - '\xD7': 'times', - '<': 'lt', - "\u226E": 'nlt', - "<\u20D2": 'nvlt', - '=': 'equals', - "\u2260": 'ne', - "=\u20E5": 'bne', - "\u2A75": 'Equal', - '>': 'gt', - "\u226F": 'ngt', - ">\u20D2": 'nvgt', - '\xAC': 'not', - '|': 'vert', - '\xA6': 'brvbar', - "\u2212": 'minus', - "\u2213": 'mp', - "\u2214": 'plusdo', - "\u2044": 'frasl', - "\u2216": 'setmn', - "\u2217": 'lowast', - "\u2218": 'compfn', - "\u221A": 'Sqrt', - "\u221D": 'prop', - "\u221E": 'infin', - "\u221F": 'angrt', - "\u2220": 'ang', - "\u2220\u20D2": 'nang', - "\u2221": 'angmsd', - "\u2222": 'angsph', - "\u2223": 'mid', - "\u2224": 'nmid', - "\u2225": 'par', - "\u2226": 'npar', - "\u2227": 'and', - "\u2228": 'or', - "\u2229": 'cap', - "\u2229\uFE00": 'caps', - "\u222A": 'cup', - "\u222A\uFE00": 'cups', - "\u222B": 'int', - "\u222C": 'Int', - "\u222D": 'tint', - "\u2A0C": 'qint', - "\u222E": 'oint', - "\u222F": 'Conint', - "\u2230": 'Cconint', - "\u2231": 'cwint', - "\u2232": 'cwconint', - "\u2233": 'awconint', - "\u2234": 'there4', - "\u2235": 'becaus', - "\u2236": 'ratio', - "\u2237": 'Colon', - "\u2238": 'minusd', - "\u223A": 'mDDot', - "\u223B": 'homtht', - "\u223C": 'sim', - "\u2241": 'nsim', - "\u223C\u20D2": 'nvsim', - "\u223D": 'bsim', - "\u223D\u0331": 'race', - "\u223E": 'ac', - "\u223E\u0333": 'acE', - "\u223F": 'acd', - "\u2240": 'wr', - "\u2242": 'esim', - "\u2242\u0338": 'nesim', - "\u2243": 'sime', - "\u2244": 'nsime', - "\u2245": 'cong', - "\u2247": 'ncong', - "\u2246": 'simne', - "\u2248": 'ap', - "\u2249": 'nap', - "\u224A": 'ape', - "\u224B": 'apid', - "\u224B\u0338": 'napid', - "\u224C": 'bcong', - "\u224D": 'CupCap', - "\u226D": 'NotCupCap', - "\u224D\u20D2": 'nvap', - "\u224E": 'bump', - "\u224E\u0338": 'nbump', - "\u224F": 'bumpe', - "\u224F\u0338": 'nbumpe', - "\u2250": 'doteq', - "\u2250\u0338": 'nedot', - "\u2251": 'eDot', - "\u2252": 'efDot', - "\u2253": 'erDot', - "\u2254": 'colone', - "\u2255": 'ecolon', - "\u2256": 'ecir', - "\u2257": 'cire', - "\u2259": 'wedgeq', - "\u225A": 'veeeq', - "\u225C": 'trie', - "\u225F": 'equest', - "\u2261": 'equiv', - "\u2262": 'nequiv', - "\u2261\u20E5": 'bnequiv', - "\u2264": 'le', - "\u2270": 'nle', - "\u2264\u20D2": 'nvle', - "\u2265": 'ge', - "\u2271": 'nge', - "\u2265\u20D2": 'nvge', - "\u2266": 'lE', - "\u2266\u0338": 'nlE', - "\u2267": 'gE', - "\u2267\u0338": 'ngE', - "\u2268\uFE00": 'lvnE', - "\u2268": 'lnE', - "\u2269": 'gnE', - "\u2269\uFE00": 'gvnE', - "\u226A": 'll', - "\u226A\u0338": 'nLtv', - "\u226A\u20D2": 'nLt', - "\u226B": 'gg', - "\u226B\u0338": 'nGtv', - "\u226B\u20D2": 'nGt', - "\u226C": 'twixt', - "\u2272": 'lsim', - "\u2274": 'nlsim', - "\u2273": 'gsim', - "\u2275": 'ngsim', - "\u2276": 'lg', - "\u2278": 'ntlg', - "\u2277": 'gl', - "\u2279": 'ntgl', - "\u227A": 'pr', - "\u2280": 'npr', - "\u227B": 'sc', - "\u2281": 'nsc', - "\u227C": 'prcue', - "\u22E0": 'nprcue', - "\u227D": 'sccue', - "\u22E1": 'nsccue', - "\u227E": 'prsim', - "\u227F": 'scsim', - "\u227F\u0338": 'NotSucceedsTilde', - "\u2282": 'sub', - "\u2284": 'nsub', - "\u2282\u20D2": 'vnsub', - "\u2283": 'sup', - "\u2285": 'nsup', - "\u2283\u20D2": 'vnsup', - "\u2286": 'sube', - "\u2288": 'nsube', - "\u2287": 'supe', - "\u2289": 'nsupe', - "\u228A\uFE00": 'vsubne', - "\u228A": 'subne', - "\u228B\uFE00": 'vsupne', - "\u228B": 'supne', - "\u228D": 'cupdot', - "\u228E": 'uplus', - "\u228F": 'sqsub', - "\u228F\u0338": 'NotSquareSubset', - "\u2290": 'sqsup', - "\u2290\u0338": 'NotSquareSuperset', - "\u2291": 'sqsube', - "\u22E2": 'nsqsube', - "\u2292": 'sqsupe', - "\u22E3": 'nsqsupe', - "\u2293": 'sqcap', - "\u2293\uFE00": 'sqcaps', - "\u2294": 'sqcup', - "\u2294\uFE00": 'sqcups', - "\u2295": 'oplus', - "\u2296": 'ominus', - "\u2297": 'otimes', - "\u2298": 'osol', - "\u2299": 'odot', - "\u229A": 'ocir', - "\u229B": 'oast', - "\u229D": 'odash', - "\u229E": 'plusb', - "\u229F": 'minusb', - "\u22A0": 'timesb', - "\u22A1": 'sdotb', - "\u22A2": 'vdash', - "\u22AC": 'nvdash', - "\u22A3": 'dashv', - "\u22A4": 'top', - "\u22A5": 'bot', - "\u22A7": 'models', - "\u22A8": 'vDash', - "\u22AD": 'nvDash', - "\u22A9": 'Vdash', - "\u22AE": 'nVdash', - "\u22AA": 'Vvdash', - "\u22AB": 'VDash', - "\u22AF": 'nVDash', - "\u22B0": 'prurel', - "\u22B2": 'vltri', - "\u22EA": 'nltri', - "\u22B3": 'vrtri', - "\u22EB": 'nrtri', - "\u22B4": 'ltrie', - "\u22EC": 'nltrie', - "\u22B4\u20D2": 'nvltrie', - "\u22B5": 'rtrie', - "\u22ED": 'nrtrie', - "\u22B5\u20D2": 'nvrtrie', - "\u22B6": 'origof', - "\u22B7": 'imof', - "\u22B8": 'mumap', - "\u22B9": 'hercon', - "\u22BA": 'intcal', - "\u22BB": 'veebar', - "\u22BD": 'barvee', - "\u22BE": 'angrtvb', - "\u22BF": 'lrtri', - "\u22C0": 'Wedge', - "\u22C1": 'Vee', - "\u22C2": 'xcap', - "\u22C3": 'xcup', - "\u22C4": 'diam', - "\u22C5": 'sdot', - "\u22C6": 'Star', - "\u22C7": 'divonx', - "\u22C8": 'bowtie', - "\u22C9": 'ltimes', - "\u22CA": 'rtimes', - "\u22CB": 'lthree', - "\u22CC": 'rthree', - "\u22CD": 'bsime', - "\u22CE": 'cuvee', - "\u22CF": 'cuwed', - "\u22D0": 'Sub', - "\u22D1": 'Sup', - "\u22D2": 'Cap', - "\u22D3": 'Cup', - "\u22D4": 'fork', - "\u22D5": 'epar', - "\u22D6": 'ltdot', - "\u22D7": 'gtdot', - "\u22D8": 'Ll', - "\u22D8\u0338": 'nLl', - "\u22D9": 'Gg', - "\u22D9\u0338": 'nGg', - "\u22DA\uFE00": 'lesg', - "\u22DA": 'leg', - "\u22DB": 'gel', - "\u22DB\uFE00": 'gesl', - "\u22DE": 'cuepr', - "\u22DF": 'cuesc', - "\u22E6": 'lnsim', - "\u22E7": 'gnsim', - "\u22E8": 'prnsim', - "\u22E9": 'scnsim', - "\u22EE": 'vellip', - "\u22EF": 'ctdot', - "\u22F0": 'utdot', - "\u22F1": 'dtdot', - "\u22F2": 'disin', - "\u22F3": 'isinsv', - "\u22F4": 'isins', - "\u22F5": 'isindot', - "\u22F5\u0338": 'notindot', - "\u22F6": 'notinvc', - "\u22F7": 'notinvb', - "\u22F9": 'isinE', - "\u22F9\u0338": 'notinE', - "\u22FA": 'nisd', - "\u22FB": 'xnis', - "\u22FC": 'nis', - "\u22FD": 'notnivc', - "\u22FE": 'notnivb', - "\u2305": 'barwed', - "\u2306": 'Barwed', - "\u230C": 'drcrop', - "\u230D": 'dlcrop', - "\u230E": 'urcrop', - "\u230F": 'ulcrop', - "\u2310": 'bnot', - "\u2312": 'profline', - "\u2313": 'profsurf', - "\u2315": 'telrec', - "\u2316": 'target', - "\u231C": 'ulcorn', - "\u231D": 'urcorn', - "\u231E": 'dlcorn', - "\u231F": 'drcorn', - "\u2322": 'frown', - "\u2323": 'smile', - "\u232D": 'cylcty', - "\u232E": 'profalar', - "\u2336": 'topbot', - "\u233D": 'ovbar', - "\u233F": 'solbar', - "\u237C": 'angzarr', - "\u23B0": 'lmoust', - "\u23B1": 'rmoust', - "\u23B4": 'tbrk', - "\u23B5": 'bbrk', - "\u23B6": 'bbrktbrk', - "\u23DC": 'OverParenthesis', - "\u23DD": 'UnderParenthesis', - "\u23DE": 'OverBrace', - "\u23DF": 'UnderBrace', - "\u23E2": 'trpezium', - "\u23E7": 'elinters', - "\u2423": 'blank', - "\u2500": 'boxh', - "\u2502": 'boxv', - "\u250C": 'boxdr', - "\u2510": 'boxdl', - "\u2514": 'boxur', - "\u2518": 'boxul', - "\u251C": 'boxvr', - "\u2524": 'boxvl', - "\u252C": 'boxhd', - "\u2534": 'boxhu', - "\u253C": 'boxvh', - "\u2550": 'boxH', - "\u2551": 'boxV', - "\u2552": 'boxdR', - "\u2553": 'boxDr', - "\u2554": 'boxDR', - "\u2555": 'boxdL', - "\u2556": 'boxDl', - "\u2557": 'boxDL', - "\u2558": 'boxuR', - "\u2559": 'boxUr', - "\u255A": 'boxUR', - "\u255B": 'boxuL', - "\u255C": 'boxUl', - "\u255D": 'boxUL', - "\u255E": 'boxvR', - "\u255F": 'boxVr', - "\u2560": 'boxVR', - "\u2561": 'boxvL', - "\u2562": 'boxVl', - "\u2563": 'boxVL', - "\u2564": 'boxHd', - "\u2565": 'boxhD', - "\u2566": 'boxHD', - "\u2567": 'boxHu', - "\u2568": 'boxhU', - "\u2569": 'boxHU', - "\u256A": 'boxvH', - "\u256B": 'boxVh', - "\u256C": 'boxVH', - "\u2580": 'uhblk', - "\u2584": 'lhblk', - "\u2588": 'block', - "\u2591": 'blk14', - "\u2592": 'blk12', - "\u2593": 'blk34', - "\u25A1": 'squ', - "\u25AA": 'squf', - "\u25AB": 'EmptyVerySmallSquare', - "\u25AD": 'rect', - "\u25AE": 'marker', - "\u25B1": 'fltns', - "\u25B3": 'xutri', - "\u25B4": 'utrif', - "\u25B5": 'utri', - "\u25B8": 'rtrif', - "\u25B9": 'rtri', - "\u25BD": 'xdtri', - "\u25BE": 'dtrif', - "\u25BF": 'dtri', - "\u25C2": 'ltrif', - "\u25C3": 'ltri', - "\u25CA": 'loz', - "\u25CB": 'cir', - "\u25EC": 'tridot', - "\u25EF": 'xcirc', - "\u25F8": 'ultri', - "\u25F9": 'urtri', - "\u25FA": 'lltri', - "\u25FB": 'EmptySmallSquare', - "\u25FC": 'FilledSmallSquare', - "\u2605": 'starf', - "\u2606": 'star', - "\u260E": 'phone', - "\u2640": 'female', - "\u2642": 'male', - "\u2660": 'spades', - "\u2663": 'clubs', - "\u2665": 'hearts', - "\u2666": 'diams', - "\u266A": 'sung', - "\u2713": 'check', - "\u2717": 'cross', - "\u2720": 'malt', - "\u2736": 'sext', - "\u2758": 'VerticalSeparator', - "\u27C8": 'bsolhsub', - "\u27C9": 'suphsol', - "\u27F5": 'xlarr', - "\u27F6": 'xrarr', - "\u27F7": 'xharr', - "\u27F8": 'xlArr', - "\u27F9": 'xrArr', - "\u27FA": 'xhArr', - "\u27FC": 'xmap', - "\u27FF": 'dzigrarr', - "\u2902": 'nvlArr', - "\u2903": 'nvrArr', - "\u2904": 'nvHarr', - "\u2905": 'Map', - "\u290C": 'lbarr', - "\u290D": 'rbarr', - "\u290E": 'lBarr', - "\u290F": 'rBarr', - "\u2910": 'RBarr', - "\u2911": 'DDotrahd', - "\u2912": 'UpArrowBar', - "\u2913": 'DownArrowBar', - "\u2916": 'Rarrtl', - "\u2919": 'latail', - "\u291A": 'ratail', - "\u291B": 'lAtail', - "\u291C": 'rAtail', - "\u291D": 'larrfs', - "\u291E": 'rarrfs', - "\u291F": 'larrbfs', - "\u2920": 'rarrbfs', - "\u2923": 'nwarhk', - "\u2924": 'nearhk', - "\u2925": 'searhk', - "\u2926": 'swarhk', - "\u2927": 'nwnear', - "\u2928": 'toea', - "\u2929": 'tosa', - "\u292A": 'swnwar', - "\u2933": 'rarrc', - "\u2933\u0338": 'nrarrc', - "\u2935": 'cudarrr', - "\u2936": 'ldca', - "\u2937": 'rdca', - "\u2938": 'cudarrl', - "\u2939": 'larrpl', - "\u293C": 'curarrm', - "\u293D": 'cularrp', - "\u2945": 'rarrpl', - "\u2948": 'harrcir', - "\u2949": 'Uarrocir', - "\u294A": 'lurdshar', - "\u294B": 'ldrushar', - "\u294E": 'LeftRightVector', - "\u294F": 'RightUpDownVector', - "\u2950": 'DownLeftRightVector', - "\u2951": 'LeftUpDownVector', - "\u2952": 'LeftVectorBar', - "\u2953": 'RightVectorBar', - "\u2954": 'RightUpVectorBar', - "\u2955": 'RightDownVectorBar', - "\u2956": 'DownLeftVectorBar', - "\u2957": 'DownRightVectorBar', - "\u2958": 'LeftUpVectorBar', - "\u2959": 'LeftDownVectorBar', - "\u295A": 'LeftTeeVector', - "\u295B": 'RightTeeVector', - "\u295C": 'RightUpTeeVector', - "\u295D": 'RightDownTeeVector', - "\u295E": 'DownLeftTeeVector', - "\u295F": 'DownRightTeeVector', - "\u2960": 'LeftUpTeeVector', - "\u2961": 'LeftDownTeeVector', - "\u2962": 'lHar', - "\u2963": 'uHar', - "\u2964": 'rHar', - "\u2965": 'dHar', - "\u2966": 'luruhar', - "\u2967": 'ldrdhar', - "\u2968": 'ruluhar', - "\u2969": 'rdldhar', - "\u296A": 'lharul', - "\u296B": 'llhard', - "\u296C": 'rharul', - "\u296D": 'lrhard', - "\u296E": 'udhar', - "\u296F": 'duhar', - "\u2970": 'RoundImplies', - "\u2971": 'erarr', - "\u2972": 'simrarr', - "\u2973": 'larrsim', - "\u2974": 'rarrsim', - "\u2975": 'rarrap', - "\u2976": 'ltlarr', - "\u2978": 'gtrarr', - "\u2979": 'subrarr', - "\u297B": 'suplarr', - "\u297C": 'lfisht', - "\u297D": 'rfisht', - "\u297E": 'ufisht', - "\u297F": 'dfisht', - "\u299A": 'vzigzag', - "\u299C": 'vangrt', - "\u299D": 'angrtvbd', - "\u29A4": 'ange', - "\u29A5": 'range', - "\u29A6": 'dwangle', - "\u29A7": 'uwangle', - "\u29A8": 'angmsdaa', - "\u29A9": 'angmsdab', - "\u29AA": 'angmsdac', - "\u29AB": 'angmsdad', - "\u29AC": 'angmsdae', - "\u29AD": 'angmsdaf', - "\u29AE": 'angmsdag', - "\u29AF": 'angmsdah', - "\u29B0": 'bemptyv', - "\u29B1": 'demptyv', - "\u29B2": 'cemptyv', - "\u29B3": 'raemptyv', - "\u29B4": 'laemptyv', - "\u29B5": 'ohbar', - "\u29B6": 'omid', - "\u29B7": 'opar', - "\u29B9": 'operp', - "\u29BB": 'olcross', - "\u29BC": 'odsold', - "\u29BE": 'olcir', - "\u29BF": 'ofcir', - "\u29C0": 'olt', - "\u29C1": 'ogt', - "\u29C2": 'cirscir', - "\u29C3": 'cirE', - "\u29C4": 'solb', - "\u29C5": 'bsolb', - "\u29C9": 'boxbox', - "\u29CD": 'trisb', - "\u29CE": 'rtriltri', - "\u29CF": 'LeftTriangleBar', - "\u29CF\u0338": 'NotLeftTriangleBar', - "\u29D0": 'RightTriangleBar', - "\u29D0\u0338": 'NotRightTriangleBar', - "\u29DC": 'iinfin', - "\u29DD": 'infintie', - "\u29DE": 'nvinfin', - "\u29E3": 'eparsl', - "\u29E4": 'smeparsl', - "\u29E5": 'eqvparsl', - "\u29EB": 'lozf', - "\u29F4": 'RuleDelayed', - "\u29F6": 'dsol', - "\u2A00": 'xodot', - "\u2A01": 'xoplus', - "\u2A02": 'xotime', - "\u2A04": 'xuplus', - "\u2A06": 'xsqcup', - "\u2A0D": 'fpartint', - "\u2A10": 'cirfnint', - "\u2A11": 'awint', - "\u2A12": 'rppolint', - "\u2A13": 'scpolint', - "\u2A14": 'npolint', - "\u2A15": 'pointint', - "\u2A16": 'quatint', - "\u2A17": 'intlarhk', - "\u2A22": 'pluscir', - "\u2A23": 'plusacir', - "\u2A24": 'simplus', - "\u2A25": 'plusdu', - "\u2A26": 'plussim', - "\u2A27": 'plustwo', - "\u2A29": 'mcomma', - "\u2A2A": 'minusdu', - "\u2A2D": 'loplus', - "\u2A2E": 'roplus', - "\u2A2F": 'Cross', - "\u2A30": 'timesd', - "\u2A31": 'timesbar', - "\u2A33": 'smashp', - "\u2A34": 'lotimes', - "\u2A35": 'rotimes', - "\u2A36": 'otimesas', - "\u2A37": 'Otimes', - "\u2A38": 'odiv', - "\u2A39": 'triplus', - "\u2A3A": 'triminus', - "\u2A3B": 'tritime', - "\u2A3C": 'iprod', - "\u2A3F": 'amalg', - "\u2A40": 'capdot', - "\u2A42": 'ncup', - "\u2A43": 'ncap', - "\u2A44": 'capand', - "\u2A45": 'cupor', - "\u2A46": 'cupcap', - "\u2A47": 'capcup', - "\u2A48": 'cupbrcap', - "\u2A49": 'capbrcup', - "\u2A4A": 'cupcup', - "\u2A4B": 'capcap', - "\u2A4C": 'ccups', - "\u2A4D": 'ccaps', - "\u2A50": 'ccupssm', - "\u2A53": 'And', - "\u2A54": 'Or', - "\u2A55": 'andand', - "\u2A56": 'oror', - "\u2A57": 'orslope', - "\u2A58": 'andslope', - "\u2A5A": 'andv', - "\u2A5B": 'orv', - "\u2A5C": 'andd', - "\u2A5D": 'ord', - "\u2A5F": 'wedbar', - "\u2A66": 'sdote', - "\u2A6A": 'simdot', - "\u2A6D": 'congdot', - "\u2A6D\u0338": 'ncongdot', - "\u2A6E": 'easter', - "\u2A6F": 'apacir', - "\u2A70": 'apE', - "\u2A70\u0338": 'napE', - "\u2A71": 'eplus', - "\u2A72": 'pluse', - "\u2A73": 'Esim', - "\u2A77": 'eDDot', - "\u2A78": 'equivDD', - "\u2A79": 'ltcir', - "\u2A7A": 'gtcir', - "\u2A7B": 'ltquest', - "\u2A7C": 'gtquest', - "\u2A7D": 'les', - "\u2A7D\u0338": 'nles', - "\u2A7E": 'ges', - "\u2A7E\u0338": 'nges', - "\u2A7F": 'lesdot', - "\u2A80": 'gesdot', - "\u2A81": 'lesdoto', - "\u2A82": 'gesdoto', - "\u2A83": 'lesdotor', - "\u2A84": 'gesdotol', - "\u2A85": 'lap', - "\u2A86": 'gap', - "\u2A87": 'lne', - "\u2A88": 'gne', - "\u2A89": 'lnap', - "\u2A8A": 'gnap', - "\u2A8B": 'lEg', - "\u2A8C": 'gEl', - "\u2A8D": 'lsime', - "\u2A8E": 'gsime', - "\u2A8F": 'lsimg', - "\u2A90": 'gsiml', - "\u2A91": 'lgE', - "\u2A92": 'glE', - "\u2A93": 'lesges', - "\u2A94": 'gesles', - "\u2A95": 'els', - "\u2A96": 'egs', - "\u2A97": 'elsdot', - "\u2A98": 'egsdot', - "\u2A99": 'el', - "\u2A9A": 'eg', - "\u2A9D": 'siml', - "\u2A9E": 'simg', - "\u2A9F": 'simlE', - "\u2AA0": 'simgE', - "\u2AA1": 'LessLess', - "\u2AA1\u0338": 'NotNestedLessLess', - "\u2AA2": 'GreaterGreater', - "\u2AA2\u0338": 'NotNestedGreaterGreater', - "\u2AA4": 'glj', - "\u2AA5": 'gla', - "\u2AA6": 'ltcc', - "\u2AA7": 'gtcc', - "\u2AA8": 'lescc', - "\u2AA9": 'gescc', - "\u2AAA": 'smt', - "\u2AAB": 'lat', - "\u2AAC": 'smte', - "\u2AAC\uFE00": 'smtes', - "\u2AAD": 'late', - "\u2AAD\uFE00": 'lates', - "\u2AAE": 'bumpE', - "\u2AAF": 'pre', - "\u2AAF\u0338": 'npre', - "\u2AB0": 'sce', - "\u2AB0\u0338": 'nsce', - "\u2AB3": 'prE', - "\u2AB4": 'scE', - "\u2AB5": 'prnE', - "\u2AB6": 'scnE', - "\u2AB7": 'prap', - "\u2AB8": 'scap', - "\u2AB9": 'prnap', - "\u2ABA": 'scnap', - "\u2ABB": 'Pr', - "\u2ABC": 'Sc', - "\u2ABD": 'subdot', - "\u2ABE": 'supdot', - "\u2ABF": 'subplus', - "\u2AC0": 'supplus', - "\u2AC1": 'submult', - "\u2AC2": 'supmult', - "\u2AC3": 'subedot', - "\u2AC4": 'supedot', - "\u2AC5": 'subE', - "\u2AC5\u0338": 'nsubE', - "\u2AC6": 'supE', - "\u2AC6\u0338": 'nsupE', - "\u2AC7": 'subsim', - "\u2AC8": 'supsim', - "\u2ACB\uFE00": 'vsubnE', - "\u2ACB": 'subnE', - "\u2ACC\uFE00": 'vsupnE', - "\u2ACC": 'supnE', - "\u2ACF": 'csub', - "\u2AD0": 'csup', - "\u2AD1": 'csube', - "\u2AD2": 'csupe', - "\u2AD3": 'subsup', - "\u2AD4": 'supsub', - "\u2AD5": 'subsub', - "\u2AD6": 'supsup', - "\u2AD7": 'suphsub', - "\u2AD8": 'supdsub', - "\u2AD9": 'forkv', - "\u2ADA": 'topfork', - "\u2ADB": 'mlcp', - "\u2AE4": 'Dashv', - "\u2AE6": 'Vdashl', - "\u2AE7": 'Barv', - "\u2AE8": 'vBar', - "\u2AE9": 'vBarv', - "\u2AEB": 'Vbar', - "\u2AEC": 'Not', - "\u2AED": 'bNot', - "\u2AEE": 'rnmid', - "\u2AEF": 'cirmid', - "\u2AF0": 'midcir', - "\u2AF1": 'topcir', - "\u2AF2": 'nhpar', - "\u2AF3": 'parsim', - "\u2AFD": 'parsl', - "\u2AFD\u20E5": 'nparsl', - "\u266D": 'flat', - "\u266E": 'natur', - "\u266F": 'sharp', - '\xA4': 'curren', - '\xA2': 'cent', - '$': 'dollar', - '\xA3': 'pound', - '\xA5': 'yen', - "\u20AC": 'euro', - '\xB9': 'sup1', - '\xBD': 'half', - "\u2153": 'frac13', - '\xBC': 'frac14', - "\u2155": 'frac15', - "\u2159": 'frac16', - "\u215B": 'frac18', - '\xB2': 'sup2', - "\u2154": 'frac23', - "\u2156": 'frac25', - '\xB3': 'sup3', - '\xBE': 'frac34', - "\u2157": 'frac35', - "\u215C": 'frac38', - "\u2158": 'frac45', - "\u215A": 'frac56', - "\u215D": 'frac58', - "\u215E": 'frac78', - "\uD835\uDCB6": 'ascr', - "\uD835\uDD52": 'aopf', - "\uD835\uDD1E": 'afr', - "\uD835\uDD38": 'Aopf', - "\uD835\uDD04": 'Afr', - "\uD835\uDC9C": 'Ascr', - '\xAA': 'ordf', - '\xE1': 'aacute', - '\xC1': 'Aacute', - '\xE0': 'agrave', - '\xC0': 'Agrave', - "\u0103": 'abreve', - "\u0102": 'Abreve', - '\xE2': 'acirc', - '\xC2': 'Acirc', - '\xE5': 'aring', - '\xC5': 'angst', - '\xE4': 'auml', - '\xC4': 'Auml', - '\xE3': 'atilde', - '\xC3': 'Atilde', - "\u0105": 'aogon', - "\u0104": 'Aogon', - "\u0101": 'amacr', - "\u0100": 'Amacr', - '\xE6': 'aelig', - '\xC6': 'AElig', - "\uD835\uDCB7": 'bscr', - "\uD835\uDD53": 'bopf', - "\uD835\uDD1F": 'bfr', - "\uD835\uDD39": 'Bopf', - "\u212C": 'Bscr', - "\uD835\uDD05": 'Bfr', - "\uD835\uDD20": 'cfr', - "\uD835\uDCB8": 'cscr', - "\uD835\uDD54": 'copf', - "\u212D": 'Cfr', - "\uD835\uDC9E": 'Cscr', - "\u2102": 'Copf', - "\u0107": 'cacute', - "\u0106": 'Cacute', - "\u0109": 'ccirc', - "\u0108": 'Ccirc', - "\u010D": 'ccaron', - "\u010C": 'Ccaron', - "\u010B": 'cdot', - "\u010A": 'Cdot', - '\xE7': 'ccedil', - '\xC7': 'Ccedil', - "\u2105": 'incare', - "\uD835\uDD21": 'dfr', - "\u2146": 'dd', - "\uD835\uDD55": 'dopf', - "\uD835\uDCB9": 'dscr', - "\uD835\uDC9F": 'Dscr', - "\uD835\uDD07": 'Dfr', - "\u2145": 'DD', - "\uD835\uDD3B": 'Dopf', - "\u010F": 'dcaron', - "\u010E": 'Dcaron', - "\u0111": 'dstrok', - "\u0110": 'Dstrok', - '\xF0': 'eth', - '\xD0': 'ETH', - "\u2147": 'ee', - "\u212F": 'escr', - "\uD835\uDD22": 'efr', - "\uD835\uDD56": 'eopf', - "\u2130": 'Escr', - "\uD835\uDD08": 'Efr', - "\uD835\uDD3C": 'Eopf', - '\xE9': 'eacute', - '\xC9': 'Eacute', - '\xE8': 'egrave', - '\xC8': 'Egrave', - '\xEA': 'ecirc', - '\xCA': 'Ecirc', - "\u011B": 'ecaron', - "\u011A": 'Ecaron', - '\xEB': 'euml', - '\xCB': 'Euml', - "\u0117": 'edot', - "\u0116": 'Edot', - "\u0119": 'eogon', - "\u0118": 'Eogon', - "\u0113": 'emacr', - "\u0112": 'Emacr', - "\uD835\uDD23": 'ffr', - "\uD835\uDD57": 'fopf', - "\uD835\uDCBB": 'fscr', - "\uD835\uDD09": 'Ffr', - "\uD835\uDD3D": 'Fopf', - "\u2131": 'Fscr', - "\uFB00": 'fflig', - "\uFB03": 'ffilig', - "\uFB04": 'ffllig', - "\uFB01": 'filig', - 'fj': 'fjlig', - "\uFB02": 'fllig', - "\u0192": 'fnof', - "\u210A": 'gscr', - "\uD835\uDD58": 'gopf', - "\uD835\uDD24": 'gfr', - "\uD835\uDCA2": 'Gscr', - "\uD835\uDD3E": 'Gopf', - "\uD835\uDD0A": 'Gfr', - "\u01F5": 'gacute', - "\u011F": 'gbreve', - "\u011E": 'Gbreve', - "\u011D": 'gcirc', - "\u011C": 'Gcirc', - "\u0121": 'gdot', - "\u0120": 'Gdot', - "\u0122": 'Gcedil', - "\uD835\uDD25": 'hfr', - "\u210E": 'planckh', - "\uD835\uDCBD": 'hscr', - "\uD835\uDD59": 'hopf', - "\u210B": 'Hscr', - "\u210C": 'Hfr', - "\u210D": 'Hopf', - "\u0125": 'hcirc', - "\u0124": 'Hcirc', - "\u210F": 'hbar', - "\u0127": 'hstrok', - "\u0126": 'Hstrok', - "\uD835\uDD5A": 'iopf', - "\uD835\uDD26": 'ifr', - "\uD835\uDCBE": 'iscr', - "\u2148": 'ii', - "\uD835\uDD40": 'Iopf', - "\u2110": 'Iscr', - "\u2111": 'Im', - '\xED': 'iacute', - '\xCD': 'Iacute', - '\xEC': 'igrave', - '\xCC': 'Igrave', - '\xEE': 'icirc', - '\xCE': 'Icirc', - '\xEF': 'iuml', - '\xCF': 'Iuml', - "\u0129": 'itilde', - "\u0128": 'Itilde', - "\u0130": 'Idot', - "\u012F": 'iogon', - "\u012E": 'Iogon', - "\u012B": 'imacr', - "\u012A": 'Imacr', - "\u0133": 'ijlig', - "\u0132": 'IJlig', - "\u0131": 'imath', - "\uD835\uDCBF": 'jscr', - "\uD835\uDD5B": 'jopf', - "\uD835\uDD27": 'jfr', - "\uD835\uDCA5": 'Jscr', - "\uD835\uDD0D": 'Jfr', - "\uD835\uDD41": 'Jopf', - "\u0135": 'jcirc', - "\u0134": 'Jcirc', - "\u0237": 'jmath', - "\uD835\uDD5C": 'kopf', - "\uD835\uDCC0": 'kscr', - "\uD835\uDD28": 'kfr', - "\uD835\uDCA6": 'Kscr', - "\uD835\uDD42": 'Kopf', - "\uD835\uDD0E": 'Kfr', - "\u0137": 'kcedil', - "\u0136": 'Kcedil', - "\uD835\uDD29": 'lfr', - "\uD835\uDCC1": 'lscr', - "\u2113": 'ell', - "\uD835\uDD5D": 'lopf', - "\u2112": 'Lscr', - "\uD835\uDD0F": 'Lfr', - "\uD835\uDD43": 'Lopf', - "\u013A": 'lacute', - "\u0139": 'Lacute', - "\u013E": 'lcaron', - "\u013D": 'Lcaron', - "\u013C": 'lcedil', - "\u013B": 'Lcedil', - "\u0142": 'lstrok', - "\u0141": 'Lstrok', - "\u0140": 'lmidot', - "\u013F": 'Lmidot', - "\uD835\uDD2A": 'mfr', - "\uD835\uDD5E": 'mopf', - "\uD835\uDCC2": 'mscr', - "\uD835\uDD10": 'Mfr', - "\uD835\uDD44": 'Mopf', - "\u2133": 'Mscr', - "\uD835\uDD2B": 'nfr', - "\uD835\uDD5F": 'nopf', - "\uD835\uDCC3": 'nscr', - "\u2115": 'Nopf', - "\uD835\uDCA9": 'Nscr', - "\uD835\uDD11": 'Nfr', - "\u0144": 'nacute', - "\u0143": 'Nacute', - "\u0148": 'ncaron', - "\u0147": 'Ncaron', - '\xF1': 'ntilde', - '\xD1': 'Ntilde', - "\u0146": 'ncedil', - "\u0145": 'Ncedil', - "\u2116": 'numero', - "\u014B": 'eng', - "\u014A": 'ENG', - "\uD835\uDD60": 'oopf', - "\uD835\uDD2C": 'ofr', - "\u2134": 'oscr', - "\uD835\uDCAA": 'Oscr', - "\uD835\uDD12": 'Ofr', - "\uD835\uDD46": 'Oopf', - '\xBA': 'ordm', - '\xF3': 'oacute', - '\xD3': 'Oacute', - '\xF2': 'ograve', - '\xD2': 'Ograve', - '\xF4': 'ocirc', - '\xD4': 'Ocirc', - '\xF6': 'ouml', - '\xD6': 'Ouml', - "\u0151": 'odblac', - "\u0150": 'Odblac', - '\xF5': 'otilde', - '\xD5': 'Otilde', - '\xF8': 'oslash', - '\xD8': 'Oslash', - "\u014D": 'omacr', - "\u014C": 'Omacr', - "\u0153": 'oelig', - "\u0152": 'OElig', - "\uD835\uDD2D": 'pfr', - "\uD835\uDCC5": 'pscr', - "\uD835\uDD61": 'popf', - "\u2119": 'Popf', - "\uD835\uDD13": 'Pfr', - "\uD835\uDCAB": 'Pscr', - "\uD835\uDD62": 'qopf', - "\uD835\uDD2E": 'qfr', - "\uD835\uDCC6": 'qscr', - "\uD835\uDCAC": 'Qscr', - "\uD835\uDD14": 'Qfr', - "\u211A": 'Qopf', - "\u0138": 'kgreen', - "\uD835\uDD2F": 'rfr', - "\uD835\uDD63": 'ropf', - "\uD835\uDCC7": 'rscr', - "\u211B": 'Rscr', - "\u211C": 'Re', - "\u211D": 'Ropf', - "\u0155": 'racute', - "\u0154": 'Racute', - "\u0159": 'rcaron', - "\u0158": 'Rcaron', - "\u0157": 'rcedil', - "\u0156": 'Rcedil', - "\uD835\uDD64": 'sopf', - "\uD835\uDCC8": 'sscr', - "\uD835\uDD30": 'sfr', - "\uD835\uDD4A": 'Sopf', - "\uD835\uDD16": 'Sfr', - "\uD835\uDCAE": 'Sscr', - "\u24C8": 'oS', - "\u015B": 'sacute', - "\u015A": 'Sacute', - "\u015D": 'scirc', - "\u015C": 'Scirc', - "\u0161": 'scaron', - "\u0160": 'Scaron', - "\u015F": 'scedil', - "\u015E": 'Scedil', - '\xDF': 'szlig', - "\uD835\uDD31": 'tfr', - "\uD835\uDCC9": 'tscr', - "\uD835\uDD65": 'topf', - "\uD835\uDCAF": 'Tscr', - "\uD835\uDD17": 'Tfr', - "\uD835\uDD4B": 'Topf', - "\u0165": 'tcaron', - "\u0164": 'Tcaron', - "\u0163": 'tcedil', - "\u0162": 'Tcedil', - "\u2122": 'trade', - "\u0167": 'tstrok', - "\u0166": 'Tstrok', - "\uD835\uDCCA": 'uscr', - "\uD835\uDD66": 'uopf', - "\uD835\uDD32": 'ufr', - "\uD835\uDD4C": 'Uopf', - "\uD835\uDD18": 'Ufr', - "\uD835\uDCB0": 'Uscr', - '\xFA': 'uacute', - '\xDA': 'Uacute', - '\xF9': 'ugrave', - '\xD9': 'Ugrave', - "\u016D": 'ubreve', - "\u016C": 'Ubreve', - '\xFB': 'ucirc', - '\xDB': 'Ucirc', - "\u016F": 'uring', - "\u016E": 'Uring', - '\xFC': 'uuml', - '\xDC': 'Uuml', - "\u0171": 'udblac', - "\u0170": 'Udblac', - "\u0169": 'utilde', - "\u0168": 'Utilde', - "\u0173": 'uogon', - "\u0172": 'Uogon', - "\u016B": 'umacr', - "\u016A": 'Umacr', - "\uD835\uDD33": 'vfr', - "\uD835\uDD67": 'vopf', - "\uD835\uDCCB": 'vscr', - "\uD835\uDD19": 'Vfr', - "\uD835\uDD4D": 'Vopf', - "\uD835\uDCB1": 'Vscr', - "\uD835\uDD68": 'wopf', - "\uD835\uDCCC": 'wscr', - "\uD835\uDD34": 'wfr', - "\uD835\uDCB2": 'Wscr', - "\uD835\uDD4E": 'Wopf', - "\uD835\uDD1A": 'Wfr', - "\u0175": 'wcirc', - "\u0174": 'Wcirc', - "\uD835\uDD35": 'xfr', - "\uD835\uDCCD": 'xscr', - "\uD835\uDD69": 'xopf', - "\uD835\uDD4F": 'Xopf', - "\uD835\uDD1B": 'Xfr', - "\uD835\uDCB3": 'Xscr', - "\uD835\uDD36": 'yfr', - "\uD835\uDCCE": 'yscr', - "\uD835\uDD6A": 'yopf', - "\uD835\uDCB4": 'Yscr', - "\uD835\uDD1C": 'Yfr', - "\uD835\uDD50": 'Yopf', - '\xFD': 'yacute', - '\xDD': 'Yacute', - "\u0177": 'ycirc', - "\u0176": 'Ycirc', - '\xFF': 'yuml', - "\u0178": 'Yuml', - "\uD835\uDCCF": 'zscr', - "\uD835\uDD37": 'zfr', - "\uD835\uDD6B": 'zopf', - "\u2128": 'Zfr', - "\u2124": 'Zopf', - "\uD835\uDCB5": 'Zscr', - "\u017A": 'zacute', - "\u0179": 'Zacute', - "\u017E": 'zcaron', - "\u017D": 'Zcaron', - "\u017C": 'zdot', - "\u017B": 'Zdot', - "\u01B5": 'imped', - '\xFE': 'thorn', - '\xDE': 'THORN', - "\u0149": 'napos', - "\u03B1": 'alpha', - "\u0391": 'Alpha', - "\u03B2": 'beta', - "\u0392": 'Beta', - "\u03B3": 'gamma', - "\u0393": 'Gamma', - "\u03B4": 'delta', - "\u0394": 'Delta', - "\u03B5": 'epsi', - "\u03F5": 'epsiv', - "\u0395": 'Epsilon', - "\u03DD": 'gammad', - "\u03DC": 'Gammad', - "\u03B6": 'zeta', - "\u0396": 'Zeta', - "\u03B7": 'eta', - "\u0397": 'Eta', - "\u03B8": 'theta', - "\u03D1": 'thetav', - "\u0398": 'Theta', - "\u03B9": 'iota', - "\u0399": 'Iota', - "\u03BA": 'kappa', - "\u03F0": 'kappav', - "\u039A": 'Kappa', - "\u03BB": 'lambda', - "\u039B": 'Lambda', - "\u03BC": 'mu', - '\xB5': 'micro', - "\u039C": 'Mu', - "\u03BD": 'nu', - "\u039D": 'Nu', - "\u03BE": 'xi', - "\u039E": 'Xi', - "\u03BF": 'omicron', - "\u039F": 'Omicron', - "\u03C0": 'pi', - "\u03D6": 'piv', - "\u03A0": 'Pi', - "\u03C1": 'rho', - "\u03F1": 'rhov', - "\u03A1": 'Rho', - "\u03C3": 'sigma', - "\u03A3": 'Sigma', - "\u03C2": 'sigmaf', - "\u03C4": 'tau', - "\u03A4": 'Tau', - "\u03C5": 'upsi', - "\u03A5": 'Upsilon', - "\u03D2": 'Upsi', - "\u03C6": 'phi', - "\u03D5": 'phiv', - "\u03A6": 'Phi', - "\u03C7": 'chi', - "\u03A7": 'Chi', - "\u03C8": 'psi', - "\u03A8": 'Psi', - "\u03C9": 'omega', - "\u03A9": 'ohm', - "\u0430": 'acy', - "\u0410": 'Acy', - "\u0431": 'bcy', - "\u0411": 'Bcy', - "\u0432": 'vcy', - "\u0412": 'Vcy', - "\u0433": 'gcy', - "\u0413": 'Gcy', - "\u0453": 'gjcy', - "\u0403": 'GJcy', - "\u0434": 'dcy', - "\u0414": 'Dcy', - "\u0452": 'djcy', - "\u0402": 'DJcy', - "\u0435": 'iecy', - "\u0415": 'IEcy', - "\u0451": 'iocy', - "\u0401": 'IOcy', - "\u0454": 'jukcy', - "\u0404": 'Jukcy', - "\u0436": 'zhcy', - "\u0416": 'ZHcy', - "\u0437": 'zcy', - "\u0417": 'Zcy', - "\u0455": 'dscy', - "\u0405": 'DScy', - "\u0438": 'icy', - "\u0418": 'Icy', - "\u0456": 'iukcy', - "\u0406": 'Iukcy', - "\u0457": 'yicy', - "\u0407": 'YIcy', - "\u0439": 'jcy', - "\u0419": 'Jcy', - "\u0458": 'jsercy', - "\u0408": 'Jsercy', - "\u043A": 'kcy', - "\u041A": 'Kcy', - "\u045C": 'kjcy', - "\u040C": 'KJcy', - "\u043B": 'lcy', - "\u041B": 'Lcy', - "\u0459": 'ljcy', - "\u0409": 'LJcy', - "\u043C": 'mcy', - "\u041C": 'Mcy', - "\u043D": 'ncy', - "\u041D": 'Ncy', - "\u045A": 'njcy', - "\u040A": 'NJcy', - "\u043E": 'ocy', - "\u041E": 'Ocy', - "\u043F": 'pcy', - "\u041F": 'Pcy', - "\u0440": 'rcy', - "\u0420": 'Rcy', - "\u0441": 'scy', - "\u0421": 'Scy', - "\u0442": 'tcy', - "\u0422": 'Tcy', - "\u045B": 'tshcy', - "\u040B": 'TSHcy', - "\u0443": 'ucy', - "\u0423": 'Ucy', - "\u045E": 'ubrcy', - "\u040E": 'Ubrcy', - "\u0444": 'fcy', - "\u0424": 'Fcy', - "\u0445": 'khcy', - "\u0425": 'KHcy', - "\u0446": 'tscy', - "\u0426": 'TScy', - "\u0447": 'chcy', - "\u0427": 'CHcy', - "\u045F": 'dzcy', - "\u040F": 'DZcy', - "\u0448": 'shcy', - "\u0428": 'SHcy', - "\u0449": 'shchcy', - "\u0429": 'SHCHcy', - "\u044A": 'hardcy', - "\u042A": 'HARDcy', - "\u044B": 'ycy', - "\u042B": 'Ycy', - "\u044C": 'softcy', - "\u042C": 'SOFTcy', - "\u044D": 'ecy', - "\u042D": 'Ecy', - "\u044E": 'yucy', - "\u042E": 'YUcy', - "\u044F": 'yacy', - "\u042F": 'YAcy', - "\u2135": 'aleph', - "\u2136": 'beth', - "\u2137": 'gimel', - "\u2138": 'daleth' - }; - var regexEscape = /["&'<>`]/g; - var escapeMap = { - '"': '"', - '&': '&', - '\'': ''', - '<': '<', - // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the - // following is not strictly necessary unless it’s part of a tag or an - // unquoted attribute value. We’re only escaping it to support those - // situations, and for XML support. - '>': '>', - // In Internet Explorer ≤ 8, the backtick character can be used - // to break out of (un)quoted attribute values or HTML comments. - // See http://html5sec.org/#102, http://html5sec.org/#108, and - // http://html5sec.org/#133. - '`': '`' - }; - var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/; - var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; - var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|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edil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g; - var decodeMap = { - 'aacute': '\xE1', - 'Aacute': '\xC1', - 'abreve': "\u0103", - 'Abreve': "\u0102", - 'ac': "\u223E", - 'acd': "\u223F", - 'acE': "\u223E\u0333", - 'acirc': '\xE2', - 'Acirc': '\xC2', - 'acute': '\xB4', - 'acy': "\u0430", - 'Acy': "\u0410", - 'aelig': '\xE6', - 'AElig': '\xC6', - 'af': "\u2061", - 'afr': "\uD835\uDD1E", - 'Afr': "\uD835\uDD04", - 'agrave': '\xE0', - 'Agrave': '\xC0', - 'alefsym': "\u2135", - 'aleph': "\u2135", - 'alpha': "\u03B1", - 'Alpha': "\u0391", - 'amacr': "\u0101", - 'Amacr': "\u0100", - 'amalg': "\u2A3F", - 'amp': '&', - 'AMP': '&', - 'and': "\u2227", - 'And': "\u2A53", - 'andand': "\u2A55", - 'andd': "\u2A5C", - 'andslope': "\u2A58", - 'andv': "\u2A5A", - 'ang': "\u2220", - 'ange': "\u29A4", - 'angle': "\u2220", - 'angmsd': "\u2221", - 'angmsdaa': "\u29A8", - 'angmsdab': "\u29A9", - 'angmsdac': "\u29AA", - 'angmsdad': "\u29AB", - 'angmsdae': "\u29AC", - 'angmsdaf': "\u29AD", - 'angmsdag': "\u29AE", - 'angmsdah': "\u29AF", - 'angrt': "\u221F", - 'angrtvb': "\u22BE", - 'angrtvbd': "\u299D", - 'angsph': "\u2222", - 'angst': '\xC5', - 'angzarr': "\u237C", - 'aogon': "\u0105", - 'Aogon': "\u0104", - 'aopf': "\uD835\uDD52", - 'Aopf': "\uD835\uDD38", - 'ap': "\u2248", - 'apacir': "\u2A6F", - 'ape': "\u224A", - 'apE': "\u2A70", - 'apid': "\u224B", - 'apos': '\'', - 'ApplyFunction': "\u2061", - 'approx': "\u2248", - 'approxeq': "\u224A", - 'aring': '\xE5', - 'Aring': '\xC5', - 'ascr': "\uD835\uDCB6", - 'Ascr': "\uD835\uDC9C", - 'Assign': "\u2254", - 'ast': '*', - 'asymp': "\u2248", - 'asympeq': "\u224D", - 'atilde': '\xE3', - 'Atilde': '\xC3', - 'auml': '\xE4', - 'Auml': '\xC4', - 'awconint': "\u2233", - 'awint': "\u2A11", - 'backcong': "\u224C", - 'backepsilon': "\u03F6", - 'backprime': "\u2035", - 'backsim': "\u223D", - 'backsimeq': "\u22CD", - 'Backslash': "\u2216", - 'Barv': "\u2AE7", - 'barvee': "\u22BD", - 'barwed': "\u2305", - 'Barwed': "\u2306", - 'barwedge': "\u2305", - 'bbrk': "\u23B5", - 'bbrktbrk': "\u23B6", - 'bcong': "\u224C", - 'bcy': "\u0431", - 'Bcy': "\u0411", - 'bdquo': "\u201E", - 'becaus': "\u2235", - 'because': "\u2235", - 'Because': "\u2235", - 'bemptyv': "\u29B0", - 'bepsi': "\u03F6", - 'bernou': "\u212C", - 'Bernoullis': "\u212C", - 'beta': "\u03B2", - 'Beta': "\u0392", - 'beth': "\u2136", - 'between': "\u226C", - 'bfr': "\uD835\uDD1F", - 'Bfr': "\uD835\uDD05", - 'bigcap': "\u22C2", - 'bigcirc': "\u25EF", - 'bigcup': "\u22C3", - 'bigodot': "\u2A00", - 'bigoplus': "\u2A01", - 'bigotimes': "\u2A02", - 'bigsqcup': "\u2A06", - 'bigstar': "\u2605", - 'bigtriangledown': "\u25BD", - 'bigtriangleup': "\u25B3", - 'biguplus': "\u2A04", - 'bigvee': "\u22C1", - 'bigwedge': "\u22C0", - 'bkarow': "\u290D", - 'blacklozenge': "\u29EB", - 'blacksquare': "\u25AA", - 'blacktriangle': "\u25B4", - 'blacktriangledown': "\u25BE", - 'blacktriangleleft': "\u25C2", - 'blacktriangleright': "\u25B8", - 'blank': "\u2423", - 'blk12': "\u2592", - 'blk14': "\u2591", - 'blk34': "\u2593", - 'block': "\u2588", - 'bne': "=\u20E5", - 'bnequiv': "\u2261\u20E5", - 'bnot': "\u2310", - 'bNot': "\u2AED", - 'bopf': "\uD835\uDD53", - 'Bopf': "\uD835\uDD39", - 'bot': "\u22A5", - 'bottom': "\u22A5", - 'bowtie': "\u22C8", - 'boxbox': "\u29C9", - 'boxdl': "\u2510", - 'boxdL': "\u2555", - 'boxDl': "\u2556", - 'boxDL': "\u2557", - 'boxdr': "\u250C", - 'boxdR': "\u2552", - 'boxDr': "\u2553", - 'boxDR': "\u2554", - 'boxh': "\u2500", - 'boxH': "\u2550", - 'boxhd': "\u252C", - 'boxhD': "\u2565", - 'boxHd': "\u2564", - 'boxHD': "\u2566", - 'boxhu': "\u2534", - 'boxhU': "\u2568", - 'boxHu': "\u2567", - 'boxHU': "\u2569", - 'boxminus': "\u229F", - 'boxplus': "\u229E", - 'boxtimes': "\u22A0", - 'boxul': "\u2518", - 'boxuL': "\u255B", - 'boxUl': "\u255C", - 'boxUL': "\u255D", - 'boxur': "\u2514", - 'boxuR': "\u2558", - 'boxUr': "\u2559", - 'boxUR': "\u255A", - 'boxv': "\u2502", - 'boxV': "\u2551", - 'boxvh': "\u253C", - 'boxvH': "\u256A", - 'boxVh': "\u256B", - 'boxVH': "\u256C", - 'boxvl': "\u2524", - 'boxvL': "\u2561", - 'boxVl': "\u2562", - 'boxVL': "\u2563", - 'boxvr': "\u251C", - 'boxvR': "\u255E", - 'boxVr': "\u255F", - 'boxVR': "\u2560", - 'bprime': "\u2035", - 'breve': "\u02D8", - 'Breve': "\u02D8", - 'brvbar': '\xA6', - 'bscr': "\uD835\uDCB7", - 'Bscr': "\u212C", - 'bsemi': "\u204F", - 'bsim': "\u223D", - 'bsime': "\u22CD", - 'bsol': '\\', - 'bsolb': "\u29C5", - 'bsolhsub': "\u27C8", - 'bull': "\u2022", - 'bullet': "\u2022", - 'bump': "\u224E", - 'bumpe': "\u224F", - 'bumpE': "\u2AAE", - 'bumpeq': "\u224F", - 'Bumpeq': "\u224E", - 'cacute': "\u0107", - 'Cacute': "\u0106", - 'cap': "\u2229", - 'Cap': "\u22D2", - 'capand': "\u2A44", - 'capbrcup': "\u2A49", - 'capcap': "\u2A4B", - 'capcup': "\u2A47", - 'capdot': "\u2A40", - 'CapitalDifferentialD': "\u2145", - 'caps': "\u2229\uFE00", - 'caret': "\u2041", - 'caron': "\u02C7", - 'Cayleys': "\u212D", - 'ccaps': "\u2A4D", - 'ccaron': "\u010D", - 'Ccaron': "\u010C", - 'ccedil': '\xE7', - 'Ccedil': '\xC7', - 'ccirc': "\u0109", - 'Ccirc': "\u0108", - 'Cconint': "\u2230", - 'ccups': "\u2A4C", - 'ccupssm': "\u2A50", - 'cdot': "\u010B", - 'Cdot': "\u010A", - 'cedil': '\xB8', - 'Cedilla': '\xB8', - 'cemptyv': "\u29B2", - 'cent': '\xA2', - 'centerdot': '\xB7', - 'CenterDot': '\xB7', - 'cfr': "\uD835\uDD20", - 'Cfr': "\u212D", - 'chcy': "\u0447", - 'CHcy': "\u0427", - 'check': "\u2713", - 'checkmark': "\u2713", - 'chi': "\u03C7", - 'Chi': "\u03A7", - 'cir': "\u25CB", - 'circ': "\u02C6", - 'circeq': "\u2257", - 'circlearrowleft': "\u21BA", - 'circlearrowright': "\u21BB", - 'circledast': "\u229B", - 'circledcirc': "\u229A", - 'circleddash': "\u229D", - 'CircleDot': "\u2299", - 'circledR': '\xAE', - 'circledS': "\u24C8", - 'CircleMinus': "\u2296", - 'CirclePlus': "\u2295", - 'CircleTimes': "\u2297", - 'cire': "\u2257", - 'cirE': "\u29C3", - 'cirfnint': "\u2A10", - 'cirmid': "\u2AEF", - 'cirscir': "\u29C2", - 'ClockwiseContourIntegral': "\u2232", - 'CloseCurlyDoubleQuote': "\u201D", - 'CloseCurlyQuote': "\u2019", - 'clubs': "\u2663", - 'clubsuit': "\u2663", - 'colon': ':', - 'Colon': "\u2237", - 'colone': "\u2254", - 'Colone': "\u2A74", - 'coloneq': "\u2254", - 'comma': ',', - 'commat': '@', - 'comp': "\u2201", - 'compfn': "\u2218", - 'complement': "\u2201", - 'complexes': "\u2102", - 'cong': "\u2245", - 'congdot': "\u2A6D", - 'Congruent': "\u2261", - 'conint': "\u222E", - 'Conint': "\u222F", - 'ContourIntegral': "\u222E", - 'copf': "\uD835\uDD54", - 'Copf': "\u2102", - 'coprod': "\u2210", - 'Coproduct': "\u2210", - 'copy': '\xA9', - 'COPY': '\xA9', - 'copysr': "\u2117", - 'CounterClockwiseContourIntegral': "\u2233", - 'crarr': "\u21B5", - 'cross': "\u2717", - 'Cross': "\u2A2F", - 'cscr': "\uD835\uDCB8", - 'Cscr': "\uD835\uDC9E", - 'csub': "\u2ACF", - 'csube': "\u2AD1", - 'csup': "\u2AD0", - 'csupe': "\u2AD2", - 'ctdot': "\u22EF", - 'cudarrl': "\u2938", - 'cudarrr': "\u2935", - 'cuepr': "\u22DE", - 'cuesc': "\u22DF", - 'cularr': "\u21B6", - 'cularrp': "\u293D", - 'cup': "\u222A", - 'Cup': "\u22D3", - 'cupbrcap': "\u2A48", - 'cupcap': "\u2A46", - 'CupCap': "\u224D", - 'cupcup': "\u2A4A", - 'cupdot': "\u228D", - 'cupor': "\u2A45", - 'cups': "\u222A\uFE00", - 'curarr': "\u21B7", - 'curarrm': "\u293C", - 'curlyeqprec': "\u22DE", - 'curlyeqsucc': "\u22DF", - 'curlyvee': "\u22CE", - 'curlywedge': "\u22CF", - 'curren': '\xA4', - 'curvearrowleft': "\u21B6", - 'curvearrowright': "\u21B7", - 'cuvee': "\u22CE", - 'cuwed': "\u22CF", - 'cwconint': "\u2232", - 'cwint': "\u2231", - 'cylcty': "\u232D", - 'dagger': "\u2020", - 'Dagger': "\u2021", - 'daleth': "\u2138", - 'darr': "\u2193", - 'dArr': "\u21D3", - 'Darr': "\u21A1", - 'dash': "\u2010", - 'dashv': "\u22A3", - 'Dashv': "\u2AE4", - 'dbkarow': "\u290F", - 'dblac': "\u02DD", - 'dcaron': "\u010F", - 'Dcaron': "\u010E", - 'dcy': "\u0434", - 'Dcy': "\u0414", - 'dd': "\u2146", - 'DD': "\u2145", - 'ddagger': "\u2021", - 'ddarr': "\u21CA", - 'DDotrahd': "\u2911", - 'ddotseq': "\u2A77", - 'deg': '\xB0', - 'Del': "\u2207", - 'delta': "\u03B4", - 'Delta': "\u0394", - 'demptyv': "\u29B1", - 'dfisht': "\u297F", - 'dfr': "\uD835\uDD21", - 'Dfr': "\uD835\uDD07", - 'dHar': "\u2965", - 'dharl': "\u21C3", - 'dharr': "\u21C2", - 'DiacriticalAcute': '\xB4', - 'DiacriticalDot': "\u02D9", - 'DiacriticalDoubleAcute': "\u02DD", - 'DiacriticalGrave': '`', - 'DiacriticalTilde': "\u02DC", - 'diam': "\u22C4", - 'diamond': "\u22C4", - 'Diamond': "\u22C4", - 'diamondsuit': "\u2666", - 'diams': "\u2666", - 'die': '\xA8', - 'DifferentialD': "\u2146", - 'digamma': "\u03DD", - 'disin': "\u22F2", - 'div': '\xF7', - 'divide': '\xF7', - 'divideontimes': "\u22C7", - 'divonx': "\u22C7", - 'djcy': "\u0452", - 'DJcy': "\u0402", - 'dlcorn': "\u231E", - 'dlcrop': "\u230D", - 'dollar': '$', - 'dopf': "\uD835\uDD55", - 'Dopf': "\uD835\uDD3B", - 'dot': "\u02D9", - 'Dot': '\xA8', - 'DotDot': "\u20DC", - 'doteq': "\u2250", - 'doteqdot': "\u2251", - 'DotEqual': "\u2250", - 'dotminus': "\u2238", - 'dotplus': "\u2214", - 'dotsquare': "\u22A1", - 'doublebarwedge': "\u2306", - 'DoubleContourIntegral': "\u222F", - 'DoubleDot': '\xA8', - 'DoubleDownArrow': "\u21D3", - 'DoubleLeftArrow': "\u21D0", - 'DoubleLeftRightArrow': "\u21D4", - 'DoubleLeftTee': "\u2AE4", - 'DoubleLongLeftArrow': "\u27F8", - 'DoubleLongLeftRightArrow': "\u27FA", - 'DoubleLongRightArrow': "\u27F9", - 'DoubleRightArrow': "\u21D2", - 'DoubleRightTee': "\u22A8", - 'DoubleUpArrow': "\u21D1", - 'DoubleUpDownArrow': "\u21D5", - 'DoubleVerticalBar': "\u2225", - 'downarrow': "\u2193", - 'Downarrow': "\u21D3", - 'DownArrow': "\u2193", - 'DownArrowBar': "\u2913", - 'DownArrowUpArrow': "\u21F5", - 'DownBreve': "\u0311", - 'downdownarrows': "\u21CA", - 'downharpoonleft': "\u21C3", - 'downharpoonright': "\u21C2", - 'DownLeftRightVector': "\u2950", - 'DownLeftTeeVector': "\u295E", - 'DownLeftVector': "\u21BD", - 'DownLeftVectorBar': "\u2956", - 'DownRightTeeVector': "\u295F", - 'DownRightVector': "\u21C1", - 'DownRightVectorBar': "\u2957", - 'DownTee': "\u22A4", - 'DownTeeArrow': "\u21A7", - 'drbkarow': "\u2910", - 'drcorn': "\u231F", - 'drcrop': "\u230C", - 'dscr': "\uD835\uDCB9", - 'Dscr': "\uD835\uDC9F", - 'dscy': "\u0455", - 'DScy': "\u0405", - 'dsol': "\u29F6", - 'dstrok': "\u0111", - 'Dstrok': "\u0110", - 'dtdot': "\u22F1", - 'dtri': "\u25BF", - 'dtrif': "\u25BE", - 'duarr': "\u21F5", - 'duhar': "\u296F", - 'dwangle': "\u29A6", - 'dzcy': "\u045F", - 'DZcy': "\u040F", - 'dzigrarr': "\u27FF", - 'eacute': '\xE9', - 'Eacute': '\xC9', - 'easter': "\u2A6E", - 'ecaron': "\u011B", - 'Ecaron': "\u011A", - 'ecir': "\u2256", - 'ecirc': '\xEA', - 'Ecirc': '\xCA', - 'ecolon': "\u2255", - 'ecy': "\u044D", - 'Ecy': "\u042D", - 'eDDot': "\u2A77", - 'edot': "\u0117", - 'eDot': "\u2251", - 'Edot': "\u0116", - 'ee': "\u2147", - 'efDot': "\u2252", - 'efr': "\uD835\uDD22", - 'Efr': "\uD835\uDD08", - 'eg': "\u2A9A", - 'egrave': '\xE8', - 'Egrave': '\xC8', - 'egs': "\u2A96", - 'egsdot': "\u2A98", - 'el': "\u2A99", - 'Element': "\u2208", - 'elinters': "\u23E7", - 'ell': "\u2113", - 'els': "\u2A95", - 'elsdot': "\u2A97", - 'emacr': "\u0113", - 'Emacr': "\u0112", - 'empty': "\u2205", - 'emptyset': "\u2205", - 'EmptySmallSquare': "\u25FB", - 'emptyv': "\u2205", - 'EmptyVerySmallSquare': "\u25AB", - 'emsp': "\u2003", - 'emsp13': "\u2004", - 'emsp14': "\u2005", - 'eng': "\u014B", - 'ENG': "\u014A", - 'ensp': "\u2002", - 'eogon': "\u0119", - 'Eogon': "\u0118", - 'eopf': "\uD835\uDD56", - 'Eopf': "\uD835\uDD3C", - 'epar': "\u22D5", - 'eparsl': "\u29E3", - 'eplus': "\u2A71", - 'epsi': "\u03B5", - 'epsilon': "\u03B5", - 'Epsilon': "\u0395", - 'epsiv': "\u03F5", - 'eqcirc': "\u2256", - 'eqcolon': "\u2255", - 'eqsim': "\u2242", - 'eqslantgtr': "\u2A96", - 'eqslantless': "\u2A95", - 'Equal': "\u2A75", - 'equals': '=', - 'EqualTilde': "\u2242", - 'equest': "\u225F", - 'Equilibrium': "\u21CC", - 'equiv': "\u2261", - 'equivDD': "\u2A78", - 'eqvparsl': "\u29E5", - 'erarr': "\u2971", - 'erDot': "\u2253", - 'escr': "\u212F", - 'Escr': "\u2130", - 'esdot': "\u2250", - 'esim': "\u2242", - 'Esim': "\u2A73", - 'eta': "\u03B7", - 'Eta': "\u0397", - 'eth': '\xF0', - 'ETH': '\xD0', - 'euml': '\xEB', - 'Euml': '\xCB', - 'euro': "\u20AC", - 'excl': '!', - 'exist': "\u2203", - 'Exists': "\u2203", - 'expectation': "\u2130", - 'exponentiale': "\u2147", - 'ExponentialE': "\u2147", - 'fallingdotseq': "\u2252", - 'fcy': "\u0444", - 'Fcy': "\u0424", - 'female': "\u2640", - 'ffilig': "\uFB03", - 'fflig': "\uFB00", - 'ffllig': "\uFB04", - 'ffr': "\uD835\uDD23", - 'Ffr': "\uD835\uDD09", - 'filig': "\uFB01", - 'FilledSmallSquare': "\u25FC", - 'FilledVerySmallSquare': "\u25AA", - 'fjlig': 'fj', - 'flat': "\u266D", - 'fllig': "\uFB02", - 'fltns': "\u25B1", - 'fnof': "\u0192", - 'fopf': "\uD835\uDD57", - 'Fopf': "\uD835\uDD3D", - 'forall': "\u2200", - 'ForAll': "\u2200", - 'fork': "\u22D4", - 'forkv': "\u2AD9", - 'Fouriertrf': "\u2131", - 'fpartint': "\u2A0D", - 'frac12': '\xBD', - 'frac13': "\u2153", - 'frac14': '\xBC', - 'frac15': "\u2155", - 'frac16': "\u2159", - 'frac18': "\u215B", - 'frac23': "\u2154", - 'frac25': "\u2156", - 'frac34': '\xBE', - 'frac35': "\u2157", - 'frac38': "\u215C", - 'frac45': "\u2158", - 'frac56': "\u215A", - 'frac58': "\u215D", - 'frac78': "\u215E", - 'frasl': "\u2044", - 'frown': "\u2322", - 'fscr': "\uD835\uDCBB", - 'Fscr': "\u2131", - 'gacute': "\u01F5", - 'gamma': "\u03B3", - 'Gamma': "\u0393", - 'gammad': "\u03DD", - 'Gammad': "\u03DC", - 'gap': "\u2A86", - 'gbreve': "\u011F", - 'Gbreve': "\u011E", - 'Gcedil': "\u0122", - 'gcirc': "\u011D", - 'Gcirc': "\u011C", - 'gcy': "\u0433", - 'Gcy': "\u0413", - 'gdot': "\u0121", - 'Gdot': "\u0120", - 'ge': "\u2265", - 'gE': "\u2267", - 'gel': "\u22DB", - 'gEl': "\u2A8C", - 'geq': "\u2265", - 'geqq': "\u2267", - 'geqslant': "\u2A7E", - 'ges': "\u2A7E", - 'gescc': "\u2AA9", - 'gesdot': "\u2A80", - 'gesdoto': "\u2A82", - 'gesdotol': "\u2A84", - 'gesl': "\u22DB\uFE00", - 'gesles': "\u2A94", - 'gfr': "\uD835\uDD24", - 'Gfr': "\uD835\uDD0A", - 'gg': "\u226B", - 'Gg': "\u22D9", - 'ggg': "\u22D9", - 'gimel': "\u2137", - 'gjcy': "\u0453", - 'GJcy': "\u0403", - 'gl': "\u2277", - 'gla': "\u2AA5", - 'glE': "\u2A92", - 'glj': "\u2AA4", - 'gnap': "\u2A8A", - 'gnapprox': "\u2A8A", - 'gne': "\u2A88", - 'gnE': "\u2269", - 'gneq': "\u2A88", - 'gneqq': "\u2269", - 'gnsim': "\u22E7", - 'gopf': "\uD835\uDD58", - 'Gopf': "\uD835\uDD3E", - 'grave': '`', - 'GreaterEqual': "\u2265", - 'GreaterEqualLess': "\u22DB", - 'GreaterFullEqual': "\u2267", - 'GreaterGreater': "\u2AA2", - 'GreaterLess': "\u2277", - 'GreaterSlantEqual': "\u2A7E", - 'GreaterTilde': "\u2273", - 'gscr': "\u210A", - 'Gscr': "\uD835\uDCA2", - 'gsim': "\u2273", - 'gsime': "\u2A8E", - 'gsiml': "\u2A90", - 'gt': '>', - 'Gt': "\u226B", - 'GT': '>', - 'gtcc': "\u2AA7", - 'gtcir': "\u2A7A", - 'gtdot': "\u22D7", - 'gtlPar': "\u2995", - 'gtquest': "\u2A7C", - 'gtrapprox': "\u2A86", - 'gtrarr': "\u2978", - 'gtrdot': "\u22D7", - 'gtreqless': "\u22DB", - 'gtreqqless': "\u2A8C", - 'gtrless': "\u2277", - 'gtrsim': "\u2273", - 'gvertneqq': "\u2269\uFE00", - 'gvnE': "\u2269\uFE00", - 'Hacek': "\u02C7", - 'hairsp': "\u200A", - 'half': '\xBD', - 'hamilt': "\u210B", - 'hardcy': "\u044A", - 'HARDcy': "\u042A", - 'harr': "\u2194", - 'hArr': "\u21D4", - 'harrcir': "\u2948", - 'harrw': "\u21AD", - 'Hat': '^', - 'hbar': "\u210F", - 'hcirc': "\u0125", - 'Hcirc': "\u0124", - 'hearts': "\u2665", - 'heartsuit': "\u2665", - 'hellip': "\u2026", - 'hercon': "\u22B9", - 'hfr': "\uD835\uDD25", - 'Hfr': "\u210C", - 'HilbertSpace': "\u210B", - 'hksearow': "\u2925", - 'hkswarow': "\u2926", - 'hoarr': "\u21FF", - 'homtht': "\u223B", - 'hookleftarrow': "\u21A9", - 'hookrightarrow': "\u21AA", - 'hopf': "\uD835\uDD59", - 'Hopf': "\u210D", - 'horbar': "\u2015", - 'HorizontalLine': "\u2500", - 'hscr': "\uD835\uDCBD", - 'Hscr': "\u210B", - 'hslash': "\u210F", - 'hstrok': "\u0127", - 'Hstrok': "\u0126", - 'HumpDownHump': "\u224E", - 'HumpEqual': "\u224F", - 'hybull': "\u2043", - 'hyphen': "\u2010", - 'iacute': '\xED', - 'Iacute': '\xCD', - 'ic': "\u2063", - 'icirc': '\xEE', - 'Icirc': '\xCE', - 'icy': "\u0438", - 'Icy': "\u0418", - 'Idot': "\u0130", - 'iecy': "\u0435", - 'IEcy': "\u0415", - 'iexcl': '\xA1', - 'iff': "\u21D4", - 'ifr': "\uD835\uDD26", - 'Ifr': "\u2111", - 'igrave': '\xEC', - 'Igrave': '\xCC', - 'ii': "\u2148", - 'iiiint': "\u2A0C", - 'iiint': "\u222D", - 'iinfin': "\u29DC", - 'iiota': "\u2129", - 'ijlig': "\u0133", - 'IJlig': "\u0132", - 'Im': "\u2111", - 'imacr': "\u012B", - 'Imacr': "\u012A", - 'image': "\u2111", - 'ImaginaryI': "\u2148", - 'imagline': "\u2110", - 'imagpart': "\u2111", - 'imath': "\u0131", - 'imof': "\u22B7", - 'imped': "\u01B5", - 'Implies': "\u21D2", - 'in': "\u2208", - 'incare': "\u2105", - 'infin': "\u221E", - 'infintie': "\u29DD", - 'inodot': "\u0131", - 'int': "\u222B", - 'Int': "\u222C", - 'intcal': "\u22BA", - 'integers': "\u2124", - 'Integral': "\u222B", - 'intercal': "\u22BA", - 'Intersection': "\u22C2", - 'intlarhk': "\u2A17", - 'intprod': "\u2A3C", - 'InvisibleComma': "\u2063", - 'InvisibleTimes': "\u2062", - 'iocy': "\u0451", - 'IOcy': "\u0401", - 'iogon': "\u012F", - 'Iogon': "\u012E", - 'iopf': "\uD835\uDD5A", - 'Iopf': "\uD835\uDD40", - 'iota': "\u03B9", - 'Iota': "\u0399", - 'iprod': "\u2A3C", - 'iquest': '\xBF', - 'iscr': "\uD835\uDCBE", - 'Iscr': "\u2110", - 'isin': "\u2208", - 'isindot': "\u22F5", - 'isinE': "\u22F9", - 'isins': "\u22F4", - 'isinsv': "\u22F3", - 'isinv': "\u2208", - 'it': "\u2062", - 'itilde': "\u0129", - 'Itilde': "\u0128", - 'iukcy': "\u0456", - 'Iukcy': "\u0406", - 'iuml': '\xEF', - 'Iuml': '\xCF', - 'jcirc': "\u0135", - 'Jcirc': "\u0134", - 'jcy': "\u0439", - 'Jcy': "\u0419", - 'jfr': "\uD835\uDD27", - 'Jfr': "\uD835\uDD0D", - 'jmath': "\u0237", - 'jopf': "\uD835\uDD5B", - 'Jopf': "\uD835\uDD41", - 'jscr': "\uD835\uDCBF", - 'Jscr': "\uD835\uDCA5", - 'jsercy': "\u0458", - 'Jsercy': "\u0408", - 'jukcy': "\u0454", - 'Jukcy': "\u0404", - 'kappa': "\u03BA", - 'Kappa': "\u039A", - 'kappav': "\u03F0", - 'kcedil': "\u0137", - 'Kcedil': "\u0136", - 'kcy': "\u043A", - 'Kcy': "\u041A", - 'kfr': "\uD835\uDD28", - 'Kfr': "\uD835\uDD0E", - 'kgreen': "\u0138", - 'khcy': "\u0445", - 'KHcy': "\u0425", - 'kjcy': "\u045C", - 'KJcy': "\u040C", - 'kopf': "\uD835\uDD5C", - 'Kopf': "\uD835\uDD42", - 'kscr': "\uD835\uDCC0", - 'Kscr': "\uD835\uDCA6", - 'lAarr': "\u21DA", - 'lacute': "\u013A", - 'Lacute': "\u0139", - 'laemptyv': "\u29B4", - 'lagran': "\u2112", - 'lambda': "\u03BB", - 'Lambda': "\u039B", - 'lang': "\u27E8", - 'Lang': "\u27EA", - 'langd': "\u2991", - 'langle': "\u27E8", - 'lap': "\u2A85", - 'Laplacetrf': "\u2112", - 'laquo': '\xAB', - 'larr': "\u2190", - 'lArr': "\u21D0", - 'Larr': "\u219E", - 'larrb': "\u21E4", - 'larrbfs': "\u291F", - 'larrfs': "\u291D", - 'larrhk': "\u21A9", - 'larrlp': "\u21AB", - 'larrpl': "\u2939", - 'larrsim': "\u2973", - 'larrtl': "\u21A2", - 'lat': "\u2AAB", - 'latail': "\u2919", - 'lAtail': "\u291B", - 'late': "\u2AAD", - 'lates': "\u2AAD\uFE00", - 'lbarr': "\u290C", - 'lBarr': "\u290E", - 'lbbrk': "\u2772", - 'lbrace': '{', - 'lbrack': '[', - 'lbrke': "\u298B", - 'lbrksld': "\u298F", - 'lbrkslu': "\u298D", - 'lcaron': "\u013E", - 'Lcaron': "\u013D", - 'lcedil': "\u013C", - 'Lcedil': "\u013B", - 'lceil': "\u2308", - 'lcub': '{', - 'lcy': "\u043B", - 'Lcy': "\u041B", - 'ldca': "\u2936", - 'ldquo': "\u201C", - 'ldquor': "\u201E", - 'ldrdhar': "\u2967", - 'ldrushar': "\u294B", - 'ldsh': "\u21B2", - 'le': "\u2264", - 'lE': "\u2266", - 'LeftAngleBracket': "\u27E8", - 'leftarrow': "\u2190", - 'Leftarrow': "\u21D0", - 'LeftArrow': "\u2190", - 'LeftArrowBar': "\u21E4", - 'LeftArrowRightArrow': "\u21C6", - 'leftarrowtail': "\u21A2", - 'LeftCeiling': "\u2308", - 'LeftDoubleBracket': "\u27E6", - 'LeftDownTeeVector': "\u2961", - 'LeftDownVector': "\u21C3", - 'LeftDownVectorBar': "\u2959", - 'LeftFloor': "\u230A", - 'leftharpoondown': "\u21BD", - 'leftharpoonup': "\u21BC", - 'leftleftarrows': "\u21C7", - 'leftrightarrow': "\u2194", - 'Leftrightarrow': "\u21D4", - 'LeftRightArrow': "\u2194", - 'leftrightarrows': "\u21C6", - 'leftrightharpoons': "\u21CB", - 'leftrightsquigarrow': "\u21AD", - 'LeftRightVector': "\u294E", - 'LeftTee': "\u22A3", - 'LeftTeeArrow': "\u21A4", - 'LeftTeeVector': "\u295A", - 'leftthreetimes': "\u22CB", - 'LeftTriangle': "\u22B2", - 'LeftTriangleBar': "\u29CF", - 'LeftTriangleEqual': "\u22B4", - 'LeftUpDownVector': "\u2951", - 'LeftUpTeeVector': "\u2960", - 'LeftUpVector': "\u21BF", - 'LeftUpVectorBar': "\u2958", - 'LeftVector': "\u21BC", - 'LeftVectorBar': "\u2952", - 'leg': "\u22DA", - 'lEg': "\u2A8B", - 'leq': "\u2264", - 'leqq': "\u2266", - 'leqslant': "\u2A7D", - 'les': "\u2A7D", - 'lescc': "\u2AA8", - 'lesdot': "\u2A7F", - 'lesdoto': "\u2A81", - 'lesdotor': "\u2A83", - 'lesg': "\u22DA\uFE00", - 'lesges': "\u2A93", - 'lessapprox': "\u2A85", - 'lessdot': "\u22D6", - 'lesseqgtr': "\u22DA", - 'lesseqqgtr': "\u2A8B", - 'LessEqualGreater': "\u22DA", - 'LessFullEqual': "\u2266", - 'LessGreater': "\u2276", - 'lessgtr': "\u2276", - 'LessLess': "\u2AA1", - 'lesssim': "\u2272", - 'LessSlantEqual': "\u2A7D", - 'LessTilde': "\u2272", - 'lfisht': "\u297C", - 'lfloor': "\u230A", - 'lfr': "\uD835\uDD29", - 'Lfr': "\uD835\uDD0F", - 'lg': "\u2276", - 'lgE': "\u2A91", - 'lHar': "\u2962", - 'lhard': "\u21BD", - 'lharu': "\u21BC", - 'lharul': "\u296A", - 'lhblk': "\u2584", - 'ljcy': "\u0459", - 'LJcy': "\u0409", - 'll': "\u226A", - 'Ll': "\u22D8", - 'llarr': "\u21C7", - 'llcorner': "\u231E", - 'Lleftarrow': "\u21DA", - 'llhard': "\u296B", - 'lltri': "\u25FA", - 'lmidot': "\u0140", - 'Lmidot': "\u013F", - 'lmoust': "\u23B0", - 'lmoustache': "\u23B0", - 'lnap': "\u2A89", - 'lnapprox': "\u2A89", - 'lne': "\u2A87", - 'lnE': "\u2268", - 'lneq': "\u2A87", - 'lneqq': "\u2268", - 'lnsim': "\u22E6", - 'loang': "\u27EC", - 'loarr': "\u21FD", - 'lobrk': "\u27E6", - 'longleftarrow': "\u27F5", - 'Longleftarrow': "\u27F8", - 'LongLeftArrow': "\u27F5", - 'longleftrightarrow': "\u27F7", - 'Longleftrightarrow': "\u27FA", - 'LongLeftRightArrow': "\u27F7", - 'longmapsto': "\u27FC", - 'longrightarrow': "\u27F6", - 'Longrightarrow': "\u27F9", - 'LongRightArrow': "\u27F6", - 'looparrowleft': "\u21AB", - 'looparrowright': "\u21AC", - 'lopar': "\u2985", - 'lopf': "\uD835\uDD5D", - 'Lopf': "\uD835\uDD43", - 'loplus': "\u2A2D", - 'lotimes': "\u2A34", - 'lowast': "\u2217", - 'lowbar': '_', - 'LowerLeftArrow': "\u2199", - 'LowerRightArrow': "\u2198", - 'loz': "\u25CA", - 'lozenge': "\u25CA", - 'lozf': "\u29EB", - 'lpar': '(', - 'lparlt': "\u2993", - 'lrarr': "\u21C6", - 'lrcorner': "\u231F", - 'lrhar': "\u21CB", - 'lrhard': "\u296D", - 'lrm': "\u200E", - 'lrtri': "\u22BF", - 'lsaquo': "\u2039", - 'lscr': "\uD835\uDCC1", - 'Lscr': "\u2112", - 'lsh': "\u21B0", - 'Lsh': "\u21B0", - 'lsim': "\u2272", - 'lsime': "\u2A8D", - 'lsimg': "\u2A8F", - 'lsqb': '[', - 'lsquo': "\u2018", - 'lsquor': "\u201A", - 'lstrok': "\u0142", - 'Lstrok': "\u0141", - 'lt': '<', - 'Lt': "\u226A", - 'LT': '<', - 'ltcc': "\u2AA6", - 'ltcir': "\u2A79", - 'ltdot': "\u22D6", - 'lthree': "\u22CB", - 'ltimes': "\u22C9", - 'ltlarr': "\u2976", - 'ltquest': "\u2A7B", - 'ltri': "\u25C3", - 'ltrie': "\u22B4", - 'ltrif': "\u25C2", - 'ltrPar': "\u2996", - 'lurdshar': "\u294A", - 'luruhar': "\u2966", - 'lvertneqq': "\u2268\uFE00", - 'lvnE': "\u2268\uFE00", - 'macr': '\xAF', - 'male': "\u2642", - 'malt': "\u2720", - 'maltese': "\u2720", - 'map': "\u21A6", - 'Map': "\u2905", - 'mapsto': "\u21A6", - 'mapstodown': "\u21A7", - 'mapstoleft': "\u21A4", - 'mapstoup': "\u21A5", - 'marker': "\u25AE", - 'mcomma': "\u2A29", - 'mcy': "\u043C", - 'Mcy': "\u041C", - 'mdash': "\u2014", - 'mDDot': "\u223A", - 'measuredangle': "\u2221", - 'MediumSpace': "\u205F", - 'Mellintrf': "\u2133", - 'mfr': "\uD835\uDD2A", - 'Mfr': "\uD835\uDD10", - 'mho': "\u2127", - 'micro': '\xB5', - 'mid': "\u2223", - 'midast': '*', - 'midcir': "\u2AF0", - 'middot': '\xB7', - 'minus': "\u2212", - 'minusb': "\u229F", - 'minusd': "\u2238", - 'minusdu': "\u2A2A", - 'MinusPlus': "\u2213", - 'mlcp': "\u2ADB", - 'mldr': "\u2026", - 'mnplus': "\u2213", - 'models': "\u22A7", - 'mopf': "\uD835\uDD5E", - 'Mopf': "\uD835\uDD44", - 'mp': "\u2213", - 'mscr': "\uD835\uDCC2", - 'Mscr': "\u2133", - 'mstpos': "\u223E", - 'mu': "\u03BC", - 'Mu': "\u039C", - 'multimap': "\u22B8", - 'mumap': "\u22B8", - 'nabla': "\u2207", - 'nacute': "\u0144", - 'Nacute': "\u0143", - 'nang': "\u2220\u20D2", - 'nap': "\u2249", - 'napE': "\u2A70\u0338", - 'napid': "\u224B\u0338", - 'napos': "\u0149", - 'napprox': "\u2249", - 'natur': "\u266E", - 'natural': "\u266E", - 'naturals': "\u2115", - 'nbsp': '\xA0', - 'nbump': "\u224E\u0338", - 'nbumpe': "\u224F\u0338", - 'ncap': "\u2A43", - 'ncaron': "\u0148", - 'Ncaron': "\u0147", - 'ncedil': "\u0146", - 'Ncedil': "\u0145", - 'ncong': "\u2247", - 'ncongdot': "\u2A6D\u0338", - 'ncup': "\u2A42", - 'ncy': "\u043D", - 'Ncy': "\u041D", - 'ndash': "\u2013", - 'ne': "\u2260", - 'nearhk': "\u2924", - 'nearr': "\u2197", - 'neArr': "\u21D7", - 'nearrow': "\u2197", - 'nedot': "\u2250\u0338", - 'NegativeMediumSpace': "\u200B", - 'NegativeThickSpace': "\u200B", - 'NegativeThinSpace': "\u200B", - 'NegativeVeryThinSpace': "\u200B", - 'nequiv': "\u2262", - 'nesear': "\u2928", - 'nesim': "\u2242\u0338", - 'NestedGreaterGreater': "\u226B", - 'NestedLessLess': "\u226A", - 'NewLine': '\n', - 'nexist': "\u2204", - 'nexists': "\u2204", - 'nfr': "\uD835\uDD2B", - 'Nfr': "\uD835\uDD11", - 'nge': "\u2271", - 'ngE': "\u2267\u0338", - 'ngeq': "\u2271", - 'ngeqq': "\u2267\u0338", - 'ngeqslant': "\u2A7E\u0338", - 'nges': "\u2A7E\u0338", - 'nGg': "\u22D9\u0338", - 'ngsim': "\u2275", - 'ngt': "\u226F", - 'nGt': "\u226B\u20D2", - 'ngtr': "\u226F", - 'nGtv': "\u226B\u0338", - 'nharr': "\u21AE", - 'nhArr': "\u21CE", - 'nhpar': "\u2AF2", - 'ni': "\u220B", - 'nis': "\u22FC", - 'nisd': "\u22FA", - 'niv': "\u220B", - 'njcy': "\u045A", - 'NJcy': "\u040A", - 'nlarr': "\u219A", - 'nlArr': "\u21CD", - 'nldr': "\u2025", - 'nle': "\u2270", - 'nlE': "\u2266\u0338", - 'nleftarrow': "\u219A", - 'nLeftarrow': "\u21CD", - 'nleftrightarrow': "\u21AE", - 'nLeftrightarrow': "\u21CE", - 'nleq': "\u2270", - 'nleqq': "\u2266\u0338", - 'nleqslant': "\u2A7D\u0338", - 'nles': "\u2A7D\u0338", - 'nless': "\u226E", - 'nLl': "\u22D8\u0338", - 'nlsim': "\u2274", - 'nlt': "\u226E", - 'nLt': "\u226A\u20D2", - 'nltri': "\u22EA", - 'nltrie': "\u22EC", - 'nLtv': "\u226A\u0338", - 'nmid': "\u2224", - 'NoBreak': "\u2060", - 'NonBreakingSpace': '\xA0', - 'nopf': "\uD835\uDD5F", - 'Nopf': "\u2115", - 'not': '\xAC', - 'Not': "\u2AEC", - 'NotCongruent': "\u2262", - 'NotCupCap': "\u226D", - 'NotDoubleVerticalBar': "\u2226", - 'NotElement': "\u2209", - 'NotEqual': "\u2260", - 'NotEqualTilde': "\u2242\u0338", - 'NotExists': "\u2204", - 'NotGreater': "\u226F", - 'NotGreaterEqual': "\u2271", - 'NotGreaterFullEqual': "\u2267\u0338", - 'NotGreaterGreater': "\u226B\u0338", - 'NotGreaterLess': "\u2279", - 'NotGreaterSlantEqual': "\u2A7E\u0338", - 'NotGreaterTilde': "\u2275", - 'NotHumpDownHump': "\u224E\u0338", - 'NotHumpEqual': "\u224F\u0338", - 'notin': "\u2209", - 'notindot': "\u22F5\u0338", - 'notinE': "\u22F9\u0338", - 'notinva': "\u2209", - 'notinvb': "\u22F7", - 'notinvc': "\u22F6", - 'NotLeftTriangle': "\u22EA", - 'NotLeftTriangleBar': "\u29CF\u0338", - 'NotLeftTriangleEqual': "\u22EC", - 'NotLess': "\u226E", - 'NotLessEqual': "\u2270", - 'NotLessGreater': "\u2278", - 'NotLessLess': "\u226A\u0338", - 'NotLessSlantEqual': "\u2A7D\u0338", - 'NotLessTilde': "\u2274", - 'NotNestedGreaterGreater': "\u2AA2\u0338", - 'NotNestedLessLess': "\u2AA1\u0338", - 'notni': "\u220C", - 'notniva': "\u220C", - 'notnivb': "\u22FE", - 'notnivc': "\u22FD", - 'NotPrecedes': "\u2280", - 'NotPrecedesEqual': "\u2AAF\u0338", - 'NotPrecedesSlantEqual': "\u22E0", - 'NotReverseElement': "\u220C", - 'NotRightTriangle': "\u22EB", - 'NotRightTriangleBar': "\u29D0\u0338", - 'NotRightTriangleEqual': "\u22ED", - 'NotSquareSubset': "\u228F\u0338", - 'NotSquareSubsetEqual': "\u22E2", - 'NotSquareSuperset': "\u2290\u0338", - 'NotSquareSupersetEqual': "\u22E3", - 'NotSubset': "\u2282\u20D2", - 'NotSubsetEqual': "\u2288", - 'NotSucceeds': "\u2281", - 'NotSucceedsEqual': "\u2AB0\u0338", - 'NotSucceedsSlantEqual': "\u22E1", - 'NotSucceedsTilde': "\u227F\u0338", - 'NotSuperset': "\u2283\u20D2", - 'NotSupersetEqual': "\u2289", - 'NotTilde': "\u2241", - 'NotTildeEqual': "\u2244", - 'NotTildeFullEqual': "\u2247", - 'NotTildeTilde': "\u2249", - 'NotVerticalBar': "\u2224", - 'npar': "\u2226", - 'nparallel': "\u2226", - 'nparsl': "\u2AFD\u20E5", - 'npart': "\u2202\u0338", - 'npolint': "\u2A14", - 'npr': "\u2280", - 'nprcue': "\u22E0", - 'npre': "\u2AAF\u0338", - 'nprec': "\u2280", - 'npreceq': "\u2AAF\u0338", - 'nrarr': "\u219B", - 'nrArr': "\u21CF", - 'nrarrc': "\u2933\u0338", - 'nrarrw': "\u219D\u0338", - 'nrightarrow': "\u219B", - 'nRightarrow': "\u21CF", - 'nrtri': "\u22EB", - 'nrtrie': "\u22ED", - 'nsc': "\u2281", - 'nsccue': "\u22E1", - 'nsce': "\u2AB0\u0338", - 'nscr': "\uD835\uDCC3", - 'Nscr': "\uD835\uDCA9", - 'nshortmid': "\u2224", - 'nshortparallel': "\u2226", - 'nsim': "\u2241", - 'nsime': "\u2244", - 'nsimeq': "\u2244", - 'nsmid': "\u2224", - 'nspar': "\u2226", - 'nsqsube': "\u22E2", - 'nsqsupe': "\u22E3", - 'nsub': "\u2284", - 'nsube': "\u2288", - 'nsubE': "\u2AC5\u0338", - 'nsubset': "\u2282\u20D2", - 'nsubseteq': "\u2288", - 'nsubseteqq': "\u2AC5\u0338", - 'nsucc': "\u2281", - 'nsucceq': "\u2AB0\u0338", - 'nsup': "\u2285", - 'nsupe': "\u2289", - 'nsupE': "\u2AC6\u0338", - 'nsupset': "\u2283\u20D2", - 'nsupseteq': "\u2289", - 'nsupseteqq': "\u2AC6\u0338", - 'ntgl': "\u2279", - 'ntilde': '\xF1', - 'Ntilde': '\xD1', - 'ntlg': "\u2278", - 'ntriangleleft': "\u22EA", - 'ntrianglelefteq': "\u22EC", - 'ntriangleright': "\u22EB", - 'ntrianglerighteq': "\u22ED", - 'nu': "\u03BD", - 'Nu': "\u039D", - 'num': '#', - 'numero': "\u2116", - 'numsp': "\u2007", - 'nvap': "\u224D\u20D2", - 'nvdash': "\u22AC", - 'nvDash': "\u22AD", - 'nVdash': "\u22AE", - 'nVDash': "\u22AF", - 'nvge': "\u2265\u20D2", - 'nvgt': ">\u20D2", - 'nvHarr': "\u2904", - 'nvinfin': "\u29DE", - 'nvlArr': "\u2902", - 'nvle': "\u2264\u20D2", - 'nvlt': "<\u20D2", - 'nvltrie': "\u22B4\u20D2", - 'nvrArr': "\u2903", - 'nvrtrie': "\u22B5\u20D2", - 'nvsim': "\u223C\u20D2", - 'nwarhk': "\u2923", - 'nwarr': "\u2196", - 'nwArr': "\u21D6", - 'nwarrow': "\u2196", - 'nwnear': "\u2927", - 'oacute': '\xF3', - 'Oacute': '\xD3', - 'oast': "\u229B", - 'ocir': "\u229A", - 'ocirc': '\xF4', - 'Ocirc': '\xD4', - 'ocy': "\u043E", - 'Ocy': "\u041E", - 'odash': "\u229D", - 'odblac': "\u0151", - 'Odblac': "\u0150", - 'odiv': "\u2A38", - 'odot': "\u2299", - 'odsold': "\u29BC", - 'oelig': "\u0153", - 'OElig': "\u0152", - 'ofcir': "\u29BF", - 'ofr': "\uD835\uDD2C", - 'Ofr': "\uD835\uDD12", - 'ogon': "\u02DB", - 'ograve': '\xF2', - 'Ograve': '\xD2', - 'ogt': "\u29C1", - 'ohbar': "\u29B5", - 'ohm': "\u03A9", - 'oint': "\u222E", - 'olarr': "\u21BA", - 'olcir': "\u29BE", - 'olcross': "\u29BB", - 'oline': "\u203E", - 'olt': "\u29C0", - 'omacr': "\u014D", - 'Omacr': "\u014C", - 'omega': "\u03C9", - 'Omega': "\u03A9", - 'omicron': "\u03BF", - 'Omicron': "\u039F", - 'omid': "\u29B6", - 'ominus': "\u2296", - 'oopf': "\uD835\uDD60", - 'Oopf': "\uD835\uDD46", - 'opar': "\u29B7", - 'OpenCurlyDoubleQuote': "\u201C", - 'OpenCurlyQuote': "\u2018", - 'operp': "\u29B9", - 'oplus': "\u2295", - 'or': "\u2228", - 'Or': "\u2A54", - 'orarr': "\u21BB", - 'ord': "\u2A5D", - 'order': "\u2134", - 'orderof': "\u2134", - 'ordf': '\xAA', - 'ordm': '\xBA', - 'origof': "\u22B6", - 'oror': "\u2A56", - 'orslope': "\u2A57", - 'orv': "\u2A5B", - 'oS': "\u24C8", - 'oscr': "\u2134", - 'Oscr': "\uD835\uDCAA", - 'oslash': '\xF8', - 'Oslash': '\xD8', - 'osol': "\u2298", - 'otilde': '\xF5', - 'Otilde': '\xD5', - 'otimes': "\u2297", - 'Otimes': "\u2A37", - 'otimesas': "\u2A36", - 'ouml': '\xF6', - 'Ouml': '\xD6', - 'ovbar': "\u233D", - 'OverBar': "\u203E", - 'OverBrace': "\u23DE", - 'OverBracket': "\u23B4", - 'OverParenthesis': "\u23DC", - 'par': "\u2225", - 'para': '\xB6', - 'parallel': "\u2225", - 'parsim': "\u2AF3", - 'parsl': "\u2AFD", - 'part': "\u2202", - 'PartialD': "\u2202", - 'pcy': "\u043F", - 'Pcy': "\u041F", - 'percnt': '%', - 'period': '.', - 'permil': "\u2030", - 'perp': "\u22A5", - 'pertenk': "\u2031", - 'pfr': "\uD835\uDD2D", - 'Pfr': "\uD835\uDD13", - 'phi': "\u03C6", - 'Phi': "\u03A6", - 'phiv': "\u03D5", - 'phmmat': "\u2133", - 'phone': "\u260E", - 'pi': "\u03C0", - 'Pi': "\u03A0", - 'pitchfork': "\u22D4", - 'piv': "\u03D6", - 'planck': "\u210F", - 'planckh': "\u210E", - 'plankv': "\u210F", - 'plus': '+', - 'plusacir': "\u2A23", - 'plusb': "\u229E", - 'pluscir': "\u2A22", - 'plusdo': "\u2214", - 'plusdu': "\u2A25", - 'pluse': "\u2A72", - 'PlusMinus': '\xB1', - 'plusmn': '\xB1', - 'plussim': "\u2A26", - 'plustwo': "\u2A27", - 'pm': '\xB1', - 'Poincareplane': "\u210C", - 'pointint': "\u2A15", - 'popf': "\uD835\uDD61", - 'Popf': "\u2119", - 'pound': '\xA3', - 'pr': "\u227A", - 'Pr': "\u2ABB", - 'prap': "\u2AB7", - 'prcue': "\u227C", - 'pre': "\u2AAF", - 'prE': "\u2AB3", - 'prec': "\u227A", - 'precapprox': "\u2AB7", - 'preccurlyeq': "\u227C", - 'Precedes': "\u227A", - 'PrecedesEqual': "\u2AAF", - 'PrecedesSlantEqual': "\u227C", - 'PrecedesTilde': "\u227E", - 'preceq': "\u2AAF", - 'precnapprox': "\u2AB9", - 'precneqq': "\u2AB5", - 'precnsim': "\u22E8", - 'precsim': "\u227E", - 'prime': "\u2032", - 'Prime': "\u2033", - 'primes': "\u2119", - 'prnap': "\u2AB9", - 'prnE': "\u2AB5", - 'prnsim': "\u22E8", - 'prod': "\u220F", - 'Product': "\u220F", - 'profalar': "\u232E", - 'profline': "\u2312", - 'profsurf': "\u2313", - 'prop': "\u221D", - 'Proportion': "\u2237", - 'Proportional': "\u221D", - 'propto': "\u221D", - 'prsim': "\u227E", - 'prurel': "\u22B0", - 'pscr': "\uD835\uDCC5", - 'Pscr': "\uD835\uDCAB", - 'psi': "\u03C8", - 'Psi': "\u03A8", - 'puncsp': "\u2008", - 'qfr': "\uD835\uDD2E", - 'Qfr': "\uD835\uDD14", - 'qint': "\u2A0C", - 'qopf': "\uD835\uDD62", - 'Qopf': "\u211A", - 'qprime': "\u2057", - 'qscr': "\uD835\uDCC6", - 'Qscr': "\uD835\uDCAC", - 'quaternions': "\u210D", - 'quatint': "\u2A16", - 'quest': '?', - 'questeq': "\u225F", - 'quot': '"', - 'QUOT': '"', - 'rAarr': "\u21DB", - 'race': "\u223D\u0331", - 'racute': "\u0155", - 'Racute': "\u0154", - 'radic': "\u221A", - 'raemptyv': "\u29B3", - 'rang': "\u27E9", - 'Rang': "\u27EB", - 'rangd': "\u2992", - 'range': "\u29A5", - 'rangle': "\u27E9", - 'raquo': '\xBB', - 'rarr': "\u2192", - 'rArr': "\u21D2", - 'Rarr': "\u21A0", - 'rarrap': "\u2975", - 'rarrb': "\u21E5", - 'rarrbfs': "\u2920", - 'rarrc': "\u2933", - 'rarrfs': "\u291E", - 'rarrhk': "\u21AA", - 'rarrlp': "\u21AC", - 'rarrpl': "\u2945", - 'rarrsim': "\u2974", - 'rarrtl': "\u21A3", - 'Rarrtl': "\u2916", - 'rarrw': "\u219D", - 'ratail': "\u291A", - 'rAtail': "\u291C", - 'ratio': "\u2236", - 'rationals': "\u211A", - 'rbarr': "\u290D", - 'rBarr': "\u290F", - 'RBarr': "\u2910", - 'rbbrk': "\u2773", - 'rbrace': '}', - 'rbrack': ']', - 'rbrke': "\u298C", - 'rbrksld': "\u298E", - 'rbrkslu': "\u2990", - 'rcaron': "\u0159", - 'Rcaron': "\u0158", - 'rcedil': "\u0157", - 'Rcedil': "\u0156", - 'rceil': "\u2309", - 'rcub': '}', - 'rcy': "\u0440", - 'Rcy': "\u0420", - 'rdca': "\u2937", - 'rdldhar': "\u2969", - 'rdquo': "\u201D", - 'rdquor': "\u201D", - 'rdsh': "\u21B3", - 'Re': "\u211C", - 'real': "\u211C", - 'realine': "\u211B", - 'realpart': "\u211C", - 'reals': "\u211D", - 'rect': "\u25AD", - 'reg': '\xAE', - 'REG': '\xAE', - 'ReverseElement': "\u220B", - 'ReverseEquilibrium': "\u21CB", - 'ReverseUpEquilibrium': "\u296F", - 'rfisht': "\u297D", - 'rfloor': "\u230B", - 'rfr': "\uD835\uDD2F", - 'Rfr': "\u211C", - 'rHar': "\u2964", - 'rhard': "\u21C1", - 'rharu': "\u21C0", - 'rharul': "\u296C", - 'rho': "\u03C1", - 'Rho': "\u03A1", - 'rhov': "\u03F1", - 'RightAngleBracket': "\u27E9", - 'rightarrow': "\u2192", - 'Rightarrow': "\u21D2", - 'RightArrow': "\u2192", - 'RightArrowBar': "\u21E5", - 'RightArrowLeftArrow': "\u21C4", - 'rightarrowtail': "\u21A3", - 'RightCeiling': "\u2309", - 'RightDoubleBracket': "\u27E7", - 'RightDownTeeVector': "\u295D", - 'RightDownVector': "\u21C2", - 'RightDownVectorBar': "\u2955", - 'RightFloor': "\u230B", - 'rightharpoondown': "\u21C1", - 'rightharpoonup': "\u21C0", - 'rightleftarrows': "\u21C4", - 'rightleftharpoons': "\u21CC", - 'rightrightarrows': "\u21C9", - 'rightsquigarrow': "\u219D", - 'RightTee': "\u22A2", - 'RightTeeArrow': "\u21A6", - 'RightTeeVector': "\u295B", - 'rightthreetimes': "\u22CC", - 'RightTriangle': "\u22B3", - 'RightTriangleBar': "\u29D0", - 'RightTriangleEqual': "\u22B5", - 'RightUpDownVector': "\u294F", - 'RightUpTeeVector': "\u295C", - 'RightUpVector': "\u21BE", - 'RightUpVectorBar': "\u2954", - 'RightVector': "\u21C0", - 'RightVectorBar': "\u2953", - 'ring': "\u02DA", - 'risingdotseq': "\u2253", - 'rlarr': "\u21C4", - 'rlhar': "\u21CC", - 'rlm': "\u200F", - 'rmoust': "\u23B1", - 'rmoustache': "\u23B1", - 'rnmid': "\u2AEE", - 'roang': "\u27ED", - 'roarr': "\u21FE", - 'robrk': "\u27E7", - 'ropar': "\u2986", - 'ropf': "\uD835\uDD63", - 'Ropf': "\u211D", - 'roplus': "\u2A2E", - 'rotimes': "\u2A35", - 'RoundImplies': "\u2970", - 'rpar': ')', - 'rpargt': "\u2994", - 'rppolint': "\u2A12", - 'rrarr': "\u21C9", - 'Rrightarrow': "\u21DB", - 'rsaquo': "\u203A", - 'rscr': "\uD835\uDCC7", - 'Rscr': "\u211B", - 'rsh': "\u21B1", - 'Rsh': "\u21B1", - 'rsqb': ']', - 'rsquo': "\u2019", - 'rsquor': "\u2019", - 'rthree': "\u22CC", - 'rtimes': "\u22CA", - 'rtri': "\u25B9", - 'rtrie': "\u22B5", - 'rtrif': "\u25B8", - 'rtriltri': "\u29CE", - 'RuleDelayed': "\u29F4", - 'ruluhar': "\u2968", - 'rx': "\u211E", - 'sacute': "\u015B", - 'Sacute': "\u015A", - 'sbquo': "\u201A", - 'sc': "\u227B", - 'Sc': "\u2ABC", - 'scap': "\u2AB8", - 'scaron': "\u0161", - 'Scaron': "\u0160", - 'sccue': "\u227D", - 'sce': "\u2AB0", - 'scE': "\u2AB4", - 'scedil': "\u015F", - 'Scedil': "\u015E", - 'scirc': "\u015D", - 'Scirc': "\u015C", - 'scnap': "\u2ABA", - 'scnE': "\u2AB6", - 'scnsim': "\u22E9", - 'scpolint': "\u2A13", - 'scsim': "\u227F", - 'scy': "\u0441", - 'Scy': "\u0421", - 'sdot': "\u22C5", - 'sdotb': "\u22A1", - 'sdote': "\u2A66", - 'searhk': "\u2925", - 'searr': "\u2198", - 'seArr': "\u21D8", - 'searrow': "\u2198", - 'sect': '\xA7', - 'semi': ';', - 'seswar': "\u2929", - 'setminus': "\u2216", - 'setmn': "\u2216", - 'sext': "\u2736", - 'sfr': "\uD835\uDD30", - 'Sfr': "\uD835\uDD16", - 'sfrown': "\u2322", - 'sharp': "\u266F", - 'shchcy': "\u0449", - 'SHCHcy': "\u0429", - 'shcy': "\u0448", - 'SHcy': "\u0428", - 'ShortDownArrow': "\u2193", - 'ShortLeftArrow': "\u2190", - 'shortmid': "\u2223", - 'shortparallel': "\u2225", - 'ShortRightArrow': "\u2192", - 'ShortUpArrow': "\u2191", - 'shy': '\xAD', - 'sigma': "\u03C3", - 'Sigma': "\u03A3", - 'sigmaf': "\u03C2", - 'sigmav': "\u03C2", - 'sim': "\u223C", - 'simdot': "\u2A6A", - 'sime': "\u2243", - 'simeq': "\u2243", - 'simg': "\u2A9E", - 'simgE': "\u2AA0", - 'siml': "\u2A9D", - 'simlE': "\u2A9F", - 'simne': "\u2246", - 'simplus': "\u2A24", - 'simrarr': "\u2972", - 'slarr': "\u2190", - 'SmallCircle': "\u2218", - 'smallsetminus': "\u2216", - 'smashp': "\u2A33", - 'smeparsl': "\u29E4", - 'smid': "\u2223", - 'smile': "\u2323", - 'smt': "\u2AAA", - 'smte': "\u2AAC", - 'smtes': "\u2AAC\uFE00", - 'softcy': "\u044C", - 'SOFTcy': "\u042C", - 'sol': '/', - 'solb': "\u29C4", - 'solbar': "\u233F", - 'sopf': "\uD835\uDD64", - 'Sopf': "\uD835\uDD4A", - 'spades': "\u2660", - 'spadesuit': "\u2660", - 'spar': "\u2225", - 'sqcap': "\u2293", - 'sqcaps': "\u2293\uFE00", - 'sqcup': "\u2294", - 'sqcups': "\u2294\uFE00", - 'Sqrt': "\u221A", - 'sqsub': "\u228F", - 'sqsube': "\u2291", - 'sqsubset': "\u228F", - 'sqsubseteq': "\u2291", - 'sqsup': "\u2290", - 'sqsupe': "\u2292", - 'sqsupset': "\u2290", - 'sqsupseteq': "\u2292", - 'squ': "\u25A1", - 'square': "\u25A1", - 'Square': "\u25A1", - 'SquareIntersection': "\u2293", - 'SquareSubset': "\u228F", - 'SquareSubsetEqual': "\u2291", - 'SquareSuperset': "\u2290", - 'SquareSupersetEqual': "\u2292", - 'SquareUnion': "\u2294", - 'squarf': "\u25AA", - 'squf': "\u25AA", - 'srarr': "\u2192", - 'sscr': "\uD835\uDCC8", - 'Sscr': "\uD835\uDCAE", - 'ssetmn': "\u2216", - 'ssmile': "\u2323", - 'sstarf': "\u22C6", - 'star': "\u2606", - 'Star': "\u22C6", - 'starf': "\u2605", - 'straightepsilon': "\u03F5", - 'straightphi': "\u03D5", - 'strns': '\xAF', - 'sub': "\u2282", - 'Sub': "\u22D0", - 'subdot': "\u2ABD", - 'sube': "\u2286", - 'subE': "\u2AC5", - 'subedot': "\u2AC3", - 'submult': "\u2AC1", - 'subne': "\u228A", - 'subnE': "\u2ACB", - 'subplus': "\u2ABF", - 'subrarr': "\u2979", - 'subset': "\u2282", - 'Subset': "\u22D0", - 'subseteq': "\u2286", - 'subseteqq': "\u2AC5", - 'SubsetEqual': "\u2286", - 'subsetneq': "\u228A", - 'subsetneqq': "\u2ACB", - 'subsim': "\u2AC7", - 'subsub': "\u2AD5", - 'subsup': "\u2AD3", - 'succ': "\u227B", - 'succapprox': "\u2AB8", - 'succcurlyeq': "\u227D", - 'Succeeds': "\u227B", - 'SucceedsEqual': "\u2AB0", - 'SucceedsSlantEqual': "\u227D", - 'SucceedsTilde': "\u227F", - 'succeq': "\u2AB0", - 'succnapprox': "\u2ABA", - 'succneqq': "\u2AB6", - 'succnsim': "\u22E9", - 'succsim': "\u227F", - 'SuchThat': "\u220B", - 'sum': "\u2211", - 'Sum': "\u2211", - 'sung': "\u266A", - 'sup': "\u2283", - 'Sup': "\u22D1", - 'sup1': '\xB9', - 'sup2': '\xB2', - 'sup3': '\xB3', - 'supdot': "\u2ABE", - 'supdsub': "\u2AD8", - 'supe': "\u2287", - 'supE': "\u2AC6", - 'supedot': "\u2AC4", - 'Superset': "\u2283", - 'SupersetEqual': "\u2287", - 'suphsol': "\u27C9", - 'suphsub': "\u2AD7", - 'suplarr': "\u297B", - 'supmult': "\u2AC2", - 'supne': "\u228B", - 'supnE': "\u2ACC", - 'supplus': "\u2AC0", - 'supset': "\u2283", - 'Supset': "\u22D1", - 'supseteq': "\u2287", - 'supseteqq': "\u2AC6", - 'supsetneq': "\u228B", - 'supsetneqq': "\u2ACC", - 'supsim': "\u2AC8", - 'supsub': "\u2AD4", - 'supsup': "\u2AD6", - 'swarhk': "\u2926", - 'swarr': "\u2199", - 'swArr': "\u21D9", - 'swarrow': "\u2199", - 'swnwar': "\u292A", - 'szlig': '\xDF', - 'Tab': '\t', - 'target': "\u2316", - 'tau': "\u03C4", - 'Tau': "\u03A4", - 'tbrk': "\u23B4", - 'tcaron': "\u0165", - 'Tcaron': "\u0164", - 'tcedil': "\u0163", - 'Tcedil': "\u0162", - 'tcy': "\u0442", - 'Tcy': "\u0422", - 'tdot': "\u20DB", - 'telrec': "\u2315", - 'tfr': "\uD835\uDD31", - 'Tfr': "\uD835\uDD17", - 'there4': "\u2234", - 'therefore': "\u2234", - 'Therefore': "\u2234", - 'theta': "\u03B8", - 'Theta': "\u0398", - 'thetasym': "\u03D1", - 'thetav': "\u03D1", - 'thickapprox': "\u2248", - 'thicksim': "\u223C", - 'ThickSpace': "\u205F\u200A", - 'thinsp': "\u2009", - 'ThinSpace': "\u2009", - 'thkap': "\u2248", - 'thksim': "\u223C", - 'thorn': '\xFE', - 'THORN': '\xDE', - 'tilde': "\u02DC", - 'Tilde': "\u223C", - 'TildeEqual': "\u2243", - 'TildeFullEqual': "\u2245", - 'TildeTilde': "\u2248", - 'times': '\xD7', - 'timesb': "\u22A0", - 'timesbar': "\u2A31", - 'timesd': "\u2A30", - 'tint': "\u222D", - 'toea': "\u2928", - 'top': "\u22A4", - 'topbot': "\u2336", - 'topcir': "\u2AF1", - 'topf': "\uD835\uDD65", - 'Topf': "\uD835\uDD4B", - 'topfork': "\u2ADA", - 'tosa': "\u2929", - 'tprime': "\u2034", - 'trade': "\u2122", - 'TRADE': "\u2122", - 'triangle': "\u25B5", - 'triangledown': "\u25BF", - 'triangleleft': "\u25C3", - 'trianglelefteq': "\u22B4", - 'triangleq': "\u225C", - 'triangleright': "\u25B9", - 'trianglerighteq': "\u22B5", - 'tridot': "\u25EC", - 'trie': "\u225C", - 'triminus': "\u2A3A", - 'TripleDot': "\u20DB", - 'triplus': "\u2A39", - 'trisb': "\u29CD", - 'tritime': "\u2A3B", - 'trpezium': "\u23E2", - 'tscr': "\uD835\uDCC9", - 'Tscr': "\uD835\uDCAF", - 'tscy': "\u0446", - 'TScy': "\u0426", - 'tshcy': "\u045B", - 'TSHcy': "\u040B", - 'tstrok': "\u0167", - 'Tstrok': "\u0166", - 'twixt': "\u226C", - 'twoheadleftarrow': "\u219E", - 'twoheadrightarrow': "\u21A0", - 'uacute': '\xFA', - 'Uacute': '\xDA', - 'uarr': "\u2191", - 'uArr': "\u21D1", - 'Uarr': "\u219F", - 'Uarrocir': "\u2949", - 'ubrcy': "\u045E", - 'Ubrcy': "\u040E", - 'ubreve': "\u016D", - 'Ubreve': "\u016C", - 'ucirc': '\xFB', - 'Ucirc': '\xDB', - 'ucy': "\u0443", - 'Ucy': "\u0423", - 'udarr': "\u21C5", - 'udblac': "\u0171", - 'Udblac': "\u0170", - 'udhar': "\u296E", - 'ufisht': "\u297E", - 'ufr': "\uD835\uDD32", - 'Ufr': "\uD835\uDD18", - 'ugrave': '\xF9', - 'Ugrave': '\xD9', - 'uHar': "\u2963", - 'uharl': "\u21BF", - 'uharr': "\u21BE", - 'uhblk': "\u2580", - 'ulcorn': "\u231C", - 'ulcorner': "\u231C", - 'ulcrop': "\u230F", - 'ultri': "\u25F8", - 'umacr': "\u016B", - 'Umacr': "\u016A", - 'uml': '\xA8', - 'UnderBar': '_', - 'UnderBrace': "\u23DF", - 'UnderBracket': "\u23B5", - 'UnderParenthesis': "\u23DD", - 'Union': "\u22C3", - 'UnionPlus': "\u228E", - 'uogon': "\u0173", - 'Uogon': "\u0172", - 'uopf': "\uD835\uDD66", - 'Uopf': "\uD835\uDD4C", - 'uparrow': "\u2191", - 'Uparrow': "\u21D1", - 'UpArrow': "\u2191", - 'UpArrowBar': "\u2912", - 'UpArrowDownArrow': "\u21C5", - 'updownarrow': "\u2195", - 'Updownarrow': "\u21D5", - 'UpDownArrow': "\u2195", - 'UpEquilibrium': "\u296E", - 'upharpoonleft': "\u21BF", - 'upharpoonright': "\u21BE", - 'uplus': "\u228E", - 'UpperLeftArrow': "\u2196", - 'UpperRightArrow': "\u2197", - 'upsi': "\u03C5", - 'Upsi': "\u03D2", - 'upsih': "\u03D2", - 'upsilon': "\u03C5", - 'Upsilon': "\u03A5", - 'UpTee': "\u22A5", - 'UpTeeArrow': "\u21A5", - 'upuparrows': "\u21C8", - 'urcorn': "\u231D", - 'urcorner': "\u231D", - 'urcrop': "\u230E", - 'uring': "\u016F", - 'Uring': "\u016E", - 'urtri': "\u25F9", - 'uscr': "\uD835\uDCCA", - 'Uscr': "\uD835\uDCB0", - 'utdot': "\u22F0", - 'utilde': "\u0169", - 'Utilde': "\u0168", - 'utri': "\u25B5", - 'utrif': "\u25B4", - 'uuarr': "\u21C8", - 'uuml': '\xFC', - 'Uuml': '\xDC', - 'uwangle': "\u29A7", - 'vangrt': "\u299C", - 'varepsilon': "\u03F5", - 'varkappa': "\u03F0", - 'varnothing': "\u2205", - 'varphi': "\u03D5", - 'varpi': "\u03D6", - 'varpropto': "\u221D", - 'varr': "\u2195", - 'vArr': "\u21D5", - 'varrho': "\u03F1", - 'varsigma': "\u03C2", - 'varsubsetneq': "\u228A\uFE00", - 'varsubsetneqq': "\u2ACB\uFE00", - 'varsupsetneq': "\u228B\uFE00", - 'varsupsetneqq': "\u2ACC\uFE00", - 'vartheta': "\u03D1", - 'vartriangleleft': "\u22B2", - 'vartriangleright': "\u22B3", - 'vBar': "\u2AE8", - 'Vbar': "\u2AEB", - 'vBarv': "\u2AE9", - 'vcy': "\u0432", - 'Vcy': "\u0412", - 'vdash': "\u22A2", - 'vDash': "\u22A8", - 'Vdash': "\u22A9", - 'VDash': "\u22AB", - 'Vdashl': "\u2AE6", - 'vee': "\u2228", - 'Vee': "\u22C1", - 'veebar': "\u22BB", - 'veeeq': "\u225A", - 'vellip': "\u22EE", - 'verbar': '|', - 'Verbar': "\u2016", - 'vert': '|', - 'Vert': "\u2016", - 'VerticalBar': "\u2223", - 'VerticalLine': '|', - 'VerticalSeparator': "\u2758", - 'VerticalTilde': "\u2240", - 'VeryThinSpace': "\u200A", - 'vfr': "\uD835\uDD33", - 'Vfr': "\uD835\uDD19", - 'vltri': "\u22B2", - 'vnsub': "\u2282\u20D2", - 'vnsup': "\u2283\u20D2", - 'vopf': "\uD835\uDD67", - 'Vopf': "\uD835\uDD4D", - 'vprop': "\u221D", - 'vrtri': "\u22B3", - 'vscr': "\uD835\uDCCB", - 'Vscr': "\uD835\uDCB1", - 'vsubne': "\u228A\uFE00", - 'vsubnE': "\u2ACB\uFE00", - 'vsupne': "\u228B\uFE00", - 'vsupnE': "\u2ACC\uFE00", - 'Vvdash': "\u22AA", - 'vzigzag': "\u299A", - 'wcirc': "\u0175", - 'Wcirc': "\u0174", - 'wedbar': "\u2A5F", - 'wedge': "\u2227", - 'Wedge': "\u22C0", - 'wedgeq': "\u2259", - 'weierp': "\u2118", - 'wfr': "\uD835\uDD34", - 'Wfr': "\uD835\uDD1A", - 'wopf': "\uD835\uDD68", - 'Wopf': "\uD835\uDD4E", - 'wp': "\u2118", - 'wr': "\u2240", - 'wreath': "\u2240", - 'wscr': "\uD835\uDCCC", - 'Wscr': "\uD835\uDCB2", - 'xcap': "\u22C2", - 'xcirc': "\u25EF", - 'xcup': "\u22C3", - 'xdtri': "\u25BD", - 'xfr': "\uD835\uDD35", - 'Xfr': "\uD835\uDD1B", - 'xharr': "\u27F7", - 'xhArr': "\u27FA", - 'xi': "\u03BE", - 'Xi': "\u039E", - 'xlarr': "\u27F5", - 'xlArr': "\u27F8", - 'xmap': "\u27FC", - 'xnis': "\u22FB", - 'xodot': "\u2A00", - 'xopf': "\uD835\uDD69", - 'Xopf': "\uD835\uDD4F", - 'xoplus': "\u2A01", - 'xotime': "\u2A02", - 'xrarr': "\u27F6", - 'xrArr': "\u27F9", - 'xscr': "\uD835\uDCCD", - 'Xscr': "\uD835\uDCB3", - 'xsqcup': "\u2A06", - 'xuplus': "\u2A04", - 'xutri': "\u25B3", - 'xvee': "\u22C1", - 'xwedge': "\u22C0", - 'yacute': '\xFD', - 'Yacute': '\xDD', - 'yacy': "\u044F", - 'YAcy': "\u042F", - 'ycirc': "\u0177", - 'Ycirc': "\u0176", - 'ycy': "\u044B", - 'Ycy': "\u042B", - 'yen': '\xA5', - 'yfr': "\uD835\uDD36", - 'Yfr': "\uD835\uDD1C", - 'yicy': "\u0457", - 'YIcy': "\u0407", - 'yopf': "\uD835\uDD6A", - 'Yopf': "\uD835\uDD50", - 'yscr': "\uD835\uDCCE", - 'Yscr': "\uD835\uDCB4", - 'yucy': "\u044E", - 'YUcy': "\u042E", - 'yuml': '\xFF', - 'Yuml': "\u0178", - 'zacute': "\u017A", - 'Zacute': "\u0179", - 'zcaron': "\u017E", - 'Zcaron': "\u017D", - 'zcy': "\u0437", - 'Zcy': "\u0417", - 'zdot': "\u017C", - 'Zdot': "\u017B", - 'zeetrf': "\u2128", - 'ZeroWidthSpace': "\u200B", - 'zeta': "\u03B6", - 'Zeta': "\u0396", - 'zfr': "\uD835\uDD37", - 'Zfr': "\u2128", - 'zhcy': "\u0436", - 'ZHcy': "\u0416", - 'zigrarr': "\u21DD", - 'zopf': "\uD835\uDD6B", - 'Zopf': "\u2124", - 'zscr': "\uD835\uDCCF", - 'Zscr': "\uD835\uDCB5", - 'zwj': "\u200D", - 'zwnj': "\u200C" - }; - var decodeMapLegacy = { - 'aacute': '\xE1', - 'Aacute': '\xC1', - 'acirc': '\xE2', - 'Acirc': '\xC2', - 'acute': '\xB4', - 'aelig': '\xE6', - 'AElig': '\xC6', - 'agrave': '\xE0', - 'Agrave': '\xC0', - 'amp': '&', - 'AMP': '&', - 'aring': '\xE5', - 'Aring': '\xC5', - 'atilde': '\xE3', - 'Atilde': '\xC3', - 'auml': '\xE4', - 'Auml': '\xC4', - 'brvbar': '\xA6', - 'ccedil': '\xE7', - 'Ccedil': '\xC7', - 'cedil': '\xB8', - 'cent': '\xA2', - 'copy': '\xA9', - 'COPY': '\xA9', - 'curren': '\xA4', - 'deg': '\xB0', - 'divide': '\xF7', - 'eacute': '\xE9', - 'Eacute': '\xC9', - 'ecirc': '\xEA', - 'Ecirc': '\xCA', - 'egrave': '\xE8', - 'Egrave': '\xC8', - 'eth': '\xF0', - 'ETH': '\xD0', - 'euml': '\xEB', - 'Euml': '\xCB', - 'frac12': '\xBD', - 'frac14': '\xBC', - 'frac34': '\xBE', - 'gt': '>', - 'GT': '>', - 'iacute': '\xED', - 'Iacute': '\xCD', - 'icirc': '\xEE', - 'Icirc': '\xCE', - 'iexcl': '\xA1', - 'igrave': '\xEC', - 'Igrave': '\xCC', - 'iquest': '\xBF', - 'iuml': '\xEF', - 'Iuml': '\xCF', - 'laquo': '\xAB', - 'lt': '<', - 'LT': '<', - 'macr': '\xAF', - 'micro': '\xB5', - 'middot': '\xB7', - 'nbsp': '\xA0', - 'not': '\xAC', - 'ntilde': '\xF1', - 'Ntilde': '\xD1', - 'oacute': '\xF3', - 'Oacute': '\xD3', - 'ocirc': '\xF4', - 'Ocirc': '\xD4', - 'ograve': '\xF2', - 'Ograve': '\xD2', - 'ordf': '\xAA', - 'ordm': '\xBA', - 'oslash': '\xF8', - 'Oslash': '\xD8', - 'otilde': '\xF5', - 'Otilde': '\xD5', - 'ouml': '\xF6', - 'Ouml': '\xD6', - 'para': '\xB6', - 'plusmn': '\xB1', - 'pound': '\xA3', - 'quot': '"', - 'QUOT': '"', - 'raquo': '\xBB', - 'reg': '\xAE', - 'REG': '\xAE', - 'sect': '\xA7', - 'shy': '\xAD', - 'sup1': '\xB9', - 'sup2': '\xB2', - 'sup3': '\xB3', - 'szlig': '\xDF', - 'thorn': '\xFE', - 'THORN': '\xDE', - 'times': '\xD7', - 'uacute': '\xFA', - 'Uacute': '\xDA', - 'ucirc': '\xFB', - 'Ucirc': '\xDB', - 'ugrave': '\xF9', - 'Ugrave': '\xD9', - 'uml': '\xA8', - 'uuml': '\xFC', - 'Uuml': '\xDC', - 'yacute': '\xFD', - 'Yacute': '\xDD', - 'yen': '\xA5', - 'yuml': '\xFF' - }; - var decodeMapNumeric = { - '0': "\uFFFD", - '128': "\u20AC", - '130': "\u201A", - '131': "\u0192", - '132': "\u201E", - '133': "\u2026", - '134': "\u2020", - '135': "\u2021", - '136': "\u02C6", - '137': "\u2030", - '138': "\u0160", - '139': "\u2039", - '140': "\u0152", - '142': "\u017D", - '145': "\u2018", - '146': "\u2019", - '147': "\u201C", - '148': "\u201D", - '149': "\u2022", - '150': "\u2013", - '151': "\u2014", - '152': "\u02DC", - '153': "\u2122", - '154': "\u0161", - '155': "\u203A", - '156': "\u0153", - '158': "\u017E", - '159': "\u0178" - }; - var invalidReferenceCodePoints = [1, 2, 3, 4, 5, 6, 7, 8, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 64976, 64977, 64978, 64979, 64980, 64981, 64982, 64983, 64984, 64985, 64986, 64987, 64988, 64989, 64990, 64991, 64992, 64993, 64994, 64995, 64996, 64997, 64998, 64999, 65000, 65001, 65002, 65003, 65004, 65005, 65006, 65007, 65534, 65535, 131070, 131071, 196606, 196607, 262142, 262143, 327678, 327679, 393214, 393215, 458750, 458751, 524286, 524287, 589822, 589823, 655358, 655359, 720894, 720895, 786430, 786431, 851966, 851967, 917502, 917503, 983038, 983039, 1048574, 1048575, 1114110, 1114111]; - /*--------------------------------------------------------------------------*/ - - var stringFromCharCode = String.fromCharCode; - var object = {}; - var hasOwnProperty = object.hasOwnProperty; - - var has = function has(object, propertyName) { - return hasOwnProperty.call(object, propertyName); - }; - - var contains = function contains(array, value) { - var index = -1; - var length = array.length; - - while (++index < length) { - if (array[index] == value) { - return true; - } - } - - return false; - }; - - var merge = function merge(options, defaults) { - if (!options) { - return defaults; - } - - var result = {}; - var key; - - for (key in defaults) { - // A `hasOwnProperty` check is not needed here, since only recognized - // option names are used anyway. Any others are ignored. - result[key] = has(options, key) ? options[key] : defaults[key]; - } - - return result; - }; // Modified version of `ucs2encode`; see https://mths.be/punycode. - - - var codePointToSymbol = function codePointToSymbol(codePoint, strict) { - var output = ''; - - if (codePoint >= 0xD800 && codePoint <= 0xDFFF || codePoint > 0x10FFFF) { - // See issue #4: - // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is - // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD - // REPLACEMENT CHARACTER.” - if (strict) { - parseError('character reference outside the permissible Unicode range'); - } - - return "\uFFFD"; - } - - if (has(decodeMapNumeric, codePoint)) { - if (strict) { - parseError('disallowed character reference'); - } - - return decodeMapNumeric[codePoint]; - } - - if (strict && contains(invalidReferenceCodePoints, codePoint)) { - parseError('disallowed character reference'); - } - - if (codePoint > 0xFFFF) { - codePoint -= 0x10000; - output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - output += stringFromCharCode(codePoint); - return output; - }; - - var hexEscape = function hexEscape(codePoint) { - return '&#x' + codePoint.toString(16).toUpperCase() + ';'; - }; - - var decEscape = function decEscape(codePoint) { - return '&#' + codePoint + ';'; - }; - - var parseError = function parseError(message) { - throw Error('Parse error: ' + message); - }; - /*--------------------------------------------------------------------------*/ - - - var encode = function encode(string, options) { - options = merge(options, encode.options); - var strict = options.strict; - - if (strict && regexInvalidRawCodePoint.test(string)) { - parseError('forbidden code point'); - } - - var encodeEverything = options.encodeEverything; - var useNamedReferences = options.useNamedReferences; - var allowUnsafeSymbols = options.allowUnsafeSymbols; - var escapeCodePoint = options.decimal ? decEscape : hexEscape; - - var escapeBmpSymbol = function escapeBmpSymbol(symbol) { - return escapeCodePoint(symbol.charCodeAt(0)); - }; - - if (encodeEverything) { - // Encode ASCII symbols. - string = string.replace(regexAsciiWhitelist, function (symbol) { - // Use named references if requested & possible. - if (useNamedReferences && has(encodeMap, symbol)) { - return '&' + encodeMap[symbol] + ';'; - } - - return escapeBmpSymbol(symbol); - }); // Shorten a few escapes that represent two symbols, of which at least one - // is within the ASCII range. - - if (useNamedReferences) { - string = string.replace(/>\u20D2/g, '>⃒').replace(/<\u20D2/g, '<⃒').replace(/fj/g, 'fj'); - } // Encode non-ASCII symbols. - - - if (useNamedReferences) { - // Encode non-ASCII symbols that can be replaced with a named reference. - string = string.replace(regexEncodeNonAscii, function (string) { - // Note: there is no need to check `has(encodeMap, string)` here. - return '&' + encodeMap[string] + ';'; - }); - } // Note: any remaining non-ASCII symbols are handled outside of the `if`. - - } else if (useNamedReferences) { - // Apply named character references. - // Encode `<>"'&` using named character references. - if (!allowUnsafeSymbols) { - string = string.replace(regexEscape, function (string) { - return '&' + encodeMap[string] + ';'; // no need to check `has()` here - }); - } // Shorten escapes that represent two symbols, of which at least one is - // `<>"'&`. - - - string = string.replace(/>\u20D2/g, '>⃒').replace(/<\u20D2/g, '<⃒'); // Encode non-ASCII symbols that can be replaced with a named reference. - - string = string.replace(regexEncodeNonAscii, function (string) { - // Note: there is no need to check `has(encodeMap, string)` here. - return '&' + encodeMap[string] + ';'; - }); - } else if (!allowUnsafeSymbols) { - // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled - // using named character references. - string = string.replace(regexEscape, escapeBmpSymbol); - } - - return string // Encode astral symbols. - .replace(regexAstralSymbols, function ($0) { - // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae - var high = $0.charCodeAt(0); - var low = $0.charCodeAt(1); - var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000; - return escapeCodePoint(codePoint); - }) // Encode any remaining BMP symbols that are not printable ASCII symbols - // using a hexadecimal escape. - .replace(regexBmpWhitelist, escapeBmpSymbol); - }; // Expose default options (so they can be overridden globally). - - - encode.options = { - 'allowUnsafeSymbols': false, - 'encodeEverything': false, - 'strict': false, - 'useNamedReferences': false, - 'decimal': false - }; - - var decode = function decode(html, options) { - options = merge(options, decode.options); - var strict = options.strict; - - if (strict && regexInvalidEntity.test(html)) { - parseError('malformed character reference'); - } - - return html.replace(regexDecode, function ($0, $1, $2, $3, $4, $5, $6, $7, $8) { - var codePoint; - var semicolon; - var decDigits; - var hexDigits; - var reference; - var next; - - if ($1) { - reference = $1; // Note: there is no need to check `has(decodeMap, reference)`. - - return decodeMap[reference]; - } - - if ($2) { - // Decode named character references without trailing `;`, e.g. `&`. - // This is only a parse error if it gets converted to `&`, or if it is - // followed by `=` in an attribute context. - reference = $2; - next = $3; - - if (next && options.isAttributeValue) { - if (strict && next == '=') { - parseError('`&` did not start a character reference'); - } - - return $0; - } else { - if (strict) { - parseError('named character reference was not terminated by a semicolon'); - } // Note: there is no need to check `has(decodeMapLegacy, reference)`. - - - return decodeMapLegacy[reference] + (next || ''); - } - } - - if ($4) { - // Decode decimal escapes, e.g. `𝌆`. - decDigits = $4; - semicolon = $5; - - if (strict && !semicolon) { - parseError('character reference was not terminated by a semicolon'); - } - - codePoint = parseInt(decDigits, 10); - return codePointToSymbol(codePoint, strict); - } - - if ($6) { - // Decode hexadecimal escapes, e.g. `𝌆`. - hexDigits = $6; - semicolon = $7; - - if (strict && !semicolon) { - parseError('character reference was not terminated by a semicolon'); - } - - codePoint = parseInt(hexDigits, 16); - return codePointToSymbol(codePoint, strict); - } // If we’re still here, `if ($7)` is implied; it’s an ambiguous - // ampersand for sure. https://mths.be/notes/ambiguous-ampersands - - - if (strict) { - parseError('named character reference was not terminated by a semicolon'); - } - - return $0; - }); - }; // Expose default options (so they can be overridden globally). - - - decode.options = { - 'isAttributeValue': false, - 'strict': false - }; - - var escape = function escape(string) { - return string.replace(regexEscape, function ($0) { - // Note: there is no need to check `has(escapeMap, $0)` here. - return escapeMap[$0]; - }); - }; - /*--------------------------------------------------------------------------*/ - - - var he = { - 'version': '1.2.0', - 'encode': encode, - 'decode': decode, - 'escape': escape, - 'unescape': decode - }; // Some AMD build optimizers, like r.js, check for specific condition patterns - // like the following: - - if (freeExports && !freeExports.nodeType) { - if (freeModule) { - // in Node.js, io.js, or RingoJS v0.8.0+ - freeModule.exports = he; - } else { - // in Narwhal or RingoJS v0.7.0- - for (var key in he) { - has(he, key) && (freeExports[key] = he[key]); - } - } - } else { - // in Rhino or a web browser - root.he = he; - } - })(commonjsGlobal); - }); - - var propertyIsEnumerable = objectPropertyIsEnumerable.f; - - // `Object.{ entries, values }` methods implementation - var createMethod$5 = function (TO_ENTRIES) { - return function (it) { - var O = toIndexedObject(it); - var keys = objectKeys(O); - var length = keys.length; - var i = 0; - var result = []; - var key; - while (length > i) { - key = keys[i++]; - if (!descriptors || propertyIsEnumerable.call(O, key)) { - result.push(TO_ENTRIES ? [key, O[key]] : O[key]); - } - } - return result; - }; - }; - - var objectToArray = { - // `Object.entries` method - // https://tc39.es/ecma262/#sec-object.entries - entries: createMethod$5(true), - // `Object.values` method - // https://tc39.es/ecma262/#sec-object.values - values: createMethod$5(false) - }; - - var $values = objectToArray.values; - - // `Object.values` method - // https://tc39.es/ecma262/#sec-object.values - _export({ target: 'Object', stat: true }, { - values: function values(O) { - return $values(O); - } - }); - - var format$1 = util.format; - /** - * Contains error codes, factory functions to create throwable error objects, - * and warning/deprecation functions. - * @module - */ - - /** - * process.emitWarning or a polyfill - * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options - * @ignore - */ - - var emitWarning$1 = function emitWarning(msg, type) { - if (process$1.emitWarning) { - process$1.emitWarning(msg, type); - } else { - /* istanbul ignore next */ - nextTick(function () { - console.warn(type + ': ' + msg); - }); - } - }; - /** - * Show a deprecation warning. Each distinct message is only displayed once. - * Ignores empty messages. - * - * @param {string} [msg] - Warning to print - * @private - */ - - - var deprecate$1 = function deprecate(msg) { - msg = String(msg); - - if (msg && !deprecate.cache[msg]) { - deprecate.cache[msg] = true; - emitWarning$1(msg, 'DeprecationWarning'); - } - }; - - deprecate$1.cache = {}; - /** - * Show a generic warning. - * Ignores empty messages. - * - * @param {string} [msg] - Warning to print - * @private - */ - - var warn = function warn(msg) { - if (msg) { - emitWarning$1(msg); - } - }; - /** - * When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`. - * @public - * @namespace - * @memberof module:lib/errors - */ - - - var constants = { - /** - * An unrecoverable error. - * @constant - * @default - */ - FATAL: 'ERR_MOCHA_FATAL', - - /** - * The type of an argument to a function call is invalid - * @constant - * @default - */ - INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE', - - /** - * The value of an argument to a function call is invalid - * @constant - * @default - */ - INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE', - - /** - * Something was thrown, but it wasn't an `Error` - * @constant - * @default - */ - INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION', - - /** - * An interface (e.g., `Mocha.interfaces`) is unknown or invalid - * @constant - * @default - */ - INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE', - - /** - * A reporter (.e.g, `Mocha.reporters`) is unknown or invalid - * @constant - * @default - */ - INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER', - - /** - * `done()` was called twice in a `Test` or `Hook` callback - * @constant - * @default - */ - MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE', - - /** - * No files matched the pattern provided by the user - * @constant - * @default - */ - NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN', - - /** - * Known, but unsupported behavior of some kind - * @constant - * @default - */ - UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED', - - /** - * Invalid state transition occurring in `Mocha` instance - * @constant - * @default - */ - INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING', - - /** - * Invalid state transition occurring in `Mocha` instance - * @constant - * @default - */ - INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED', - - /** - * Use of `only()` w/ `--forbid-only` results in this error. - * @constant - * @default - */ - FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY', - - /** - * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid - * @constant - * @default - */ - INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION', - - /** - * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid - * @constant - * @default - */ - INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION', - - /** - * When a runnable exceeds its allowed run time. - * @constant - * @default - */ - TIMEOUT: 'ERR_MOCHA_TIMEOUT', - - /** - * Input file is not able to be parsed - * @constant - * @default - */ - UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE' - }; - /** - * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}. - * @private - */ - - var MOCHA_ERRORS = new Set(Object.values(constants)); - /** - * Creates an error object to be thrown when no files to be tested could be found using specified pattern. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} pattern - User-specified argument value. - * @returns {Error} instance detailing the error condition - */ - - function createNoFilesMatchPatternError(message, pattern) { - var err = new Error(message); - err.code = constants.NO_FILES_MATCH_PATTERN; - err.pattern = pattern; - return err; - } - /** - * Creates an error object to be thrown when the reporter specified in the options was not found. - * - * @public - * @param {string} message - Error message to be displayed. - * @param {string} reporter - User-specified reporter value. - * @returns {Error} instance detailing the error condition - */ - - - function createInvalidReporterError(message, reporter) { - var err = new TypeError(message); - err.code = constants.INVALID_REPORTER; - err.reporter = reporter; - return err; - } - /** - * Creates an error object to be thrown when the interface specified in the options was not found. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} ui - User-specified interface value. - * @returns {Error} instance detailing the error condition - */ - - - function createInvalidInterfaceError(message, ui) { - var err = new Error(message); - err.code = constants.INVALID_INTERFACE; - err["interface"] = ui; - return err; - } - /** - * Creates an error object to be thrown when a behavior, option, or parameter is unsupported. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @returns {Error} instance detailing the error condition - */ - - - function createUnsupportedError(message) { - var err = new Error(message); - err.code = constants.UNSUPPORTED; - return err; - } - /** - * Creates an error object to be thrown when an argument is missing. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} argument - Argument name. - * @param {string} expected - Expected argument datatype. - * @returns {Error} instance detailing the error condition - */ - - - function createMissingArgumentError(message, argument, expected) { - return createInvalidArgumentTypeError(message, argument, expected); - } - /** - * Creates an error object to be thrown when an argument did not use the supported type - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} argument - Argument name. - * @param {string} expected - Expected argument datatype. - * @returns {Error} instance detailing the error condition - */ - - - function createInvalidArgumentTypeError(message, argument, expected) { - var err = new TypeError(message); - err.code = constants.INVALID_ARG_TYPE; - err.argument = argument; - err.expected = expected; - err.actual = _typeof(argument); - return err; - } - /** - * Creates an error object to be thrown when an argument did not use the supported value - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} argument - Argument name. - * @param {string} value - Argument value. - * @param {string} [reason] - Why value is invalid. - * @returns {Error} instance detailing the error condition - */ - - - function createInvalidArgumentValueError(message, argument, value, reason) { - var err = new TypeError(message); - err.code = constants.INVALID_ARG_VALUE; - err.argument = argument; - err.value = value; - err.reason = typeof reason !== 'undefined' ? reason : 'is invalid'; - return err; - } - /** - * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @returns {Error} instance detailing the error condition - */ - - - function createInvalidExceptionError(message, value) { - var err = new Error(message); - err.code = constants.INVALID_EXCEPTION; - err.valueType = _typeof(value); - err.value = value; - return err; - } - /** - * Creates an error object to be thrown when an unrecoverable error occurs. - * - * @public - * @static - * @param {string} message - Error message to be displayed. - * @returns {Error} instance detailing the error condition - */ - - - function createFatalError(message, value) { - var err = new Error(message); - err.code = constants.FATAL; - err.valueType = _typeof(value); - err.value = value; - return err; - } - /** - * Dynamically creates a plugin-type-specific error based on plugin type - * @param {string} message - Error message - * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed - * @param {string} [pluginId] - Name/path of plugin, if any - * @throws When `pluginType` is not known - * @public - * @static - * @returns {Error} - */ - - - function createInvalidLegacyPluginError(message, pluginType, pluginId) { - switch (pluginType) { - case 'reporter': - return createInvalidReporterError(message, pluginId); - - case 'interface': - return createInvalidInterfaceError(message, pluginId); - - default: - throw new Error('unknown pluginType "' + pluginType + '"'); - } - } - /** - * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type - * @deprecated - * @param {string} message - Error message - * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed - * @param {string} [pluginId] - Name/path of plugin, if any - * @throws When `pluginType` is not known - * @public - * @static - * @returns {Error} - */ - - - function createInvalidPluginError() { - deprecate$1('Use createInvalidLegacyPluginError() instead'); - return createInvalidLegacyPluginError.apply(void 0, arguments); - } - /** - * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed. - * @param {string} message The error message to be displayed. - * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun` - * @param {Mocha} instance the mocha instance that throw this error - * @static - */ - - - function createMochaInstanceAlreadyDisposedError(message, cleanReferencesAfterRun, instance) { - var err = new Error(message); - err.code = constants.INSTANCE_ALREADY_DISPOSED; - err.cleanReferencesAfterRun = cleanReferencesAfterRun; - err.instance = instance; - return err; - } - /** - * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress. - * @param {string} message The error message to be displayed. - * @static - * @public - */ - - - function createMochaInstanceAlreadyRunningError(message, instance) { - var err = new Error(message); - err.code = constants.INSTANCE_ALREADY_RUNNING; - err.instance = instance; - return err; - } - /** - * Creates an error object to be thrown when done() is called multiple times in a test - * - * @public - * @param {Runnable} runnable - Original runnable - * @param {Error} [originalErr] - Original error, if any - * @returns {Error} instance detailing the error condition - * @static - */ - - - function createMultipleDoneError(runnable, originalErr) { - var title; - - try { - title = format$1('<%s>', runnable.fullTitle()); - - if (runnable.parent.root) { - title += ' (of root suite)'; - } - } catch (ignored) { - title = format$1('<%s> (of unknown suite)', runnable.title); - } - - var message = format$1('done() called multiple times in %s %s', runnable.type ? runnable.type : 'unknown runnable', title); - - if (runnable.file) { - message += format$1(' of file %s', runnable.file); - } - - if (originalErr) { - message += format$1('; in addition, done() received error: %s', originalErr); - } - - var err = new Error(message); - err.code = constants.MULTIPLE_DONE; - err.valueType = _typeof(originalErr); - err.value = originalErr; - return err; - } - /** - * Creates an error object to be thrown when `.only()` is used with - * `--forbid-only`. - * @static - * @public - * @param {Mocha} mocha - Mocha instance - * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY} - */ - - - function createForbiddenExclusivityError(mocha) { - var err = new Error(mocha.isWorker ? '`.only` is not supported in parallel mode' : '`.only` forbidden by --forbid-only'); - err.code = constants.FORBIDDEN_EXCLUSIVITY; - return err; - } - /** - * Creates an error object to be thrown when a plugin definition is invalid - * @static - * @param {string} msg - Error message - * @param {PluginDefinition} [pluginDef] - Problematic plugin definition - * @public - * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION} - */ - - - function createInvalidPluginDefinitionError(msg, pluginDef) { - var err = new Error(msg); - err.code = constants.INVALID_PLUGIN_DEFINITION; - err.pluginDef = pluginDef; - return err; - } - /** - * Creates an error object to be thrown when a plugin implementation (user code) is invalid - * @static - * @param {string} msg - Error message - * @param {Object} [opts] - Plugin definition and user-supplied implementation - * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition - * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied) - * @public - * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION} - */ - - - function createInvalidPluginImplementationError(msg) { - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - pluginDef = _ref.pluginDef, - pluginImpl = _ref.pluginImpl; - - var err = new Error(msg); - err.code = constants.INVALID_PLUGIN_IMPLEMENTATION; - err.pluginDef = pluginDef; - err.pluginImpl = pluginImpl; - return err; - } - /** - * Creates an error object to be thrown when a runnable exceeds its allowed run time. - * @static - * @param {string} msg - Error message - * @param {number} [timeout] - Timeout in ms - * @param {string} [file] - File, if given - * @returns {MochaTimeoutError} - */ - - - function createTimeoutError(msg, timeout, file) { - var err = new Error(msg); - err.code = constants.TIMEOUT; - err.timeout = timeout; - err.file = file; - return err; - } - /** - * Creates an error object to be thrown when file is unparsable - * @public - * @static - * @param {string} message - Error message to be displayed. - * @param {string} filename - File name - * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE} - */ - - - function createUnparsableFileError(message, filename) { - var err = new Error(message); - err.code = constants.UNPARSABLE_FILE; - return err; - } - /** - * Returns `true` if an error came out of Mocha. - * _Can suffer from false negatives, but not false positives._ - * @static - * @public - * @param {*} err - Error, or anything - * @returns {boolean} - */ - - - var isMochaError = function isMochaError(err) { - return Boolean(err && _typeof(err) === 'object' && MOCHA_ERRORS.has(err.code)); - }; - - var errors = { - constants: constants, - createFatalError: createFatalError, - createForbiddenExclusivityError: createForbiddenExclusivityError, - createInvalidArgumentTypeError: createInvalidArgumentTypeError, - createInvalidArgumentValueError: createInvalidArgumentValueError, - createInvalidExceptionError: createInvalidExceptionError, - createInvalidInterfaceError: createInvalidInterfaceError, - createInvalidLegacyPluginError: createInvalidLegacyPluginError, - createInvalidPluginDefinitionError: createInvalidPluginDefinitionError, - createInvalidPluginError: createInvalidPluginError, - createInvalidPluginImplementationError: createInvalidPluginImplementationError, - createInvalidReporterError: createInvalidReporterError, - createMissingArgumentError: createMissingArgumentError, - createMochaInstanceAlreadyDisposedError: createMochaInstanceAlreadyDisposedError, - createMochaInstanceAlreadyRunningError: createMochaInstanceAlreadyRunningError, - createMultipleDoneError: createMultipleDoneError, - createNoFilesMatchPatternError: createNoFilesMatchPatternError, - createTimeoutError: createTimeoutError, - createUnparsableFileError: createUnparsableFileError, - createUnsupportedError: createUnsupportedError, - deprecate: deprecate$1, - isMochaError: isMochaError, - warn: warn - }; - - var _nodeResolve_empty = {}; - - var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - 'default': _nodeResolve_empty - }); - - var require$$11 = getCjsExportFromNamespace(_nodeResolve_empty$1); - - var utils = createCommonjsModule(function (module, exports) { - /** - * Various utility functions used throughout Mocha's codebase. - * @module utils - */ - - /** - * Module dependencies. - */ - - var nanoid = nonSecure.nanoid; - var MOCHA_ID_PROP_NAME = '__mocha_id__'; - /** - * Inherit the prototype methods from one constructor into another. - * - * @param {function} ctor - Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor - Constructor function to inherit prototype from. - * @throws {TypeError} if either constructor is null, or if super constructor - * lacks a prototype. - */ - - exports.inherits = util.inherits; - /** - * Escape special characters in the given string of html. - * - * @private - * @param {string} html - * @return {string} - */ - - exports.escape = function (html) { - return he.encode(String(html), { - useNamedReferences: false - }); - }; - /** - * Test if the given obj is type of string. - * - * @private - * @param {Object} obj - * @return {boolean} - */ - - - exports.isString = function (obj) { - return typeof obj === 'string'; - }; - /** - * Compute a slug from the given `str`. - * - * @private - * @param {string} str - * @return {string} - */ - - - exports.slug = function (str) { - return str.toLowerCase().replace(/\s+/g, '-').replace(/[^-\w]/g, '').replace(/-{2,}/g, '-'); - }; - /** - * Strip the function definition from `str`, and re-indent for pre whitespace. - * - * @param {string} str - * @return {string} - */ - - - exports.clean = function (str) { - str = str.replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '') // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content - .replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3'); - var spaces = str.match(/^\n?( *)/)[1].length; - var tabs = str.match(/^\n?(\t*)/)[1].length; - var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', 'gm'); - str = str.replace(re, ''); - return str.trim(); - }; - /** - * If a value could have properties, and has none, this function is called, - * which returns a string representation of the empty value. - * - * Functions w/ no properties return `'[Function]'` - * Arrays w/ length === 0 return `'[]'` - * Objects w/ no properties return `'{}'` - * All else: return result of `value.toString()` - * - * @private - * @param {*} value The value to inspect. - * @param {string} typeHint The type of the value - * @returns {string} - */ - - - function emptyRepresentation(value, typeHint) { - switch (typeHint) { - case 'function': - return '[Function]'; - - case 'object': - return '{}'; - - case 'array': - return '[]'; - - default: - return value.toString(); - } - } - /** - * Takes some variable and asks `Object.prototype.toString()` what it thinks it - * is. - * - * @private - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString - * @param {*} value The value to test. - * @returns {string} Computed type - * @example - * canonicalType({}) // 'object' - * canonicalType([]) // 'array' - * canonicalType(1) // 'number' - * canonicalType(false) // 'boolean' - * canonicalType(Infinity) // 'number' - * canonicalType(null) // 'null' - * canonicalType(new Date()) // 'date' - * canonicalType(/foo/) // 'regexp' - * canonicalType('type') // 'string' - * canonicalType(global) // 'global' - * canonicalType(new String('foo') // 'object' - * canonicalType(async function() {}) // 'asyncfunction' - * canonicalType(await import(name)) // 'module' - */ - - - var canonicalType = exports.canonicalType = function canonicalType(value) { - if (value === undefined) { - return 'undefined'; - } else if (value === null) { - return 'null'; - } else if (isBuffer(value)) { - return 'buffer'; - } - - return Object.prototype.toString.call(value).replace(/^\[.+\s(.+?)]$/, '$1').toLowerCase(); - }; - /** - * - * Returns a general type or data structure of a variable - * @private - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures - * @param {*} value The value to test. - * @returns {string} One of undefined, boolean, number, string, bigint, symbol, object - * @example - * type({}) // 'object' - * type([]) // 'array' - * type(1) // 'number' - * type(false) // 'boolean' - * type(Infinity) // 'number' - * type(null) // 'null' - * type(new Date()) // 'object' - * type(/foo/) // 'object' - * type('type') // 'string' - * type(global) // 'object' - * type(new String('foo') // 'string' - */ - - - exports.type = function type(value) { - // Null is special - if (value === null) return 'null'; - var primitives = new Set(['undefined', 'boolean', 'number', 'string', 'bigint', 'symbol']); - - var _type = _typeof(value); - - if (_type === 'function') return _type; - if (primitives.has(_type)) return _type; - if (value instanceof String) return 'string'; - if (value instanceof Error) return 'error'; - if (Array.isArray(value)) return 'array'; - return _type; - }; - /** - * Stringify `value`. Different behavior depending on type of value: - * - * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. - * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. - * - If `value` is an *empty* object, function, or array, return result of function - * {@link emptyRepresentation}. - * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of - * JSON.stringify(). - * - * @private - * @see exports.type - * @param {*} value - * @return {string} - */ - - - exports.stringify = function (value) { - var typeHint = canonicalType(value); - - if (!~['object', 'array', 'function'].indexOf(typeHint)) { - if (typeHint === 'buffer') { - var json = Buffer.prototype.toJSON.call(value); // Based on the toJSON result - - return jsonStringify(json.data && json.type ? json.data : json, 2).replace(/,(\n|$)/g, '$1'); - } // IE7/IE8 has a bizarre String constructor; needs to be coerced - // into an array and back to obj. - - - if (typeHint === 'string' && _typeof(value) === 'object') { - value = value.split('').reduce(function (acc, _char, idx) { - acc[idx] = _char; - return acc; - }, {}); - typeHint = 'object'; - } else { - return jsonStringify(value); - } - } - - for (var prop in value) { - if (Object.prototype.hasOwnProperty.call(value, prop)) { - return jsonStringify(exports.canonicalize(value, null, typeHint), 2).replace(/,(\n|$)/g, '$1'); - } - } - - return emptyRepresentation(value, typeHint); - }; - /** - * like JSON.stringify but more sense. - * - * @private - * @param {Object} object - * @param {number=} spaces - * @param {number=} depth - * @returns {*} - */ - - - function jsonStringify(object, spaces, depth) { - if (typeof spaces === 'undefined') { - // primitive types - return _stringify(object); - } - - depth = depth || 1; - var space = spaces * depth; - var str = Array.isArray(object) ? '[' : '{'; - var end = Array.isArray(object) ? ']' : '}'; - var length = typeof object.length === 'number' ? object.length : Object.keys(object).length; // `.repeat()` polyfill - - function repeat(s, n) { - return new Array(n).join(s); - } - - function _stringify(val) { - switch (canonicalType(val)) { - case 'null': - case 'undefined': - val = '[' + val + ']'; - break; - - case 'array': - case 'object': - val = jsonStringify(val, spaces, depth + 1); - break; - - case 'boolean': - case 'regexp': - case 'symbol': - case 'number': - val = val === 0 && 1 / val === -Infinity // `-0` - ? '-0' : val.toString(); - break; - - case 'bigint': - val = val.toString() + 'n'; - break; - - case 'date': - var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); - val = '[Date: ' + sDate + ']'; - break; - - case 'buffer': - var json = val.toJSON(); // Based on the toJSON result - - json = json.data && json.type ? json.data : json; - val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; - break; - - default: - val = val === '[Function]' || val === '[Circular]' ? val : JSON.stringify(val); - // string - } - - return val; - } - - for (var i in object) { - if (!Object.prototype.hasOwnProperty.call(object, i)) { - continue; // not my business - } - - --length; - str += '\n ' + repeat(' ', space) + (Array.isArray(object) ? '' : '"' + i + '": ') + // key - _stringify(object[i]) + ( // value - length ? ',' : ''); // comma - } - - return str + ( // [], {} - str.length !== 1 ? '\n' + repeat(' ', --space) + end : end); - } - /** - * Return a new Thing that has the keys in sorted order. Recursive. - * - * If the Thing... - * - has already been seen, return string `'[Circular]'` - * - is `undefined`, return string `'[undefined]'` - * - is `null`, return value `null` - * - is some other primitive, return the value - * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method - * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. - * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` - * - * @private - * @see {@link exports.stringify} - * @param {*} value Thing to inspect. May or may not have properties. - * @param {Array} [stack=[]] Stack of seen values - * @param {string} [typeHint] Type hint - * @return {(Object|Array|Function|string|undefined)} - */ - - - exports.canonicalize = function canonicalize(value, stack, typeHint) { - var canonicalizedObj; - /* eslint-disable no-unused-vars */ - - var prop; - /* eslint-enable no-unused-vars */ - - typeHint = typeHint || canonicalType(value); - - function withStack(value, fn) { - stack.push(value); - fn(); - stack.pop(); - } - - stack = stack || []; - - if (stack.indexOf(value) !== -1) { - return '[Circular]'; - } - - switch (typeHint) { - case 'undefined': - case 'buffer': - case 'null': - canonicalizedObj = value; - break; - - case 'array': - withStack(value, function () { - canonicalizedObj = value.map(function (item) { - return exports.canonicalize(item, stack); - }); - }); - break; - - case 'function': - /* eslint-disable-next-line no-unused-vars */ - for (prop in value) { - canonicalizedObj = {}; - break; - } - /* eslint-enable guard-for-in */ - - - if (!canonicalizedObj) { - canonicalizedObj = emptyRepresentation(value, typeHint); - break; - } - - /* falls through */ - - case 'object': - canonicalizedObj = canonicalizedObj || {}; - withStack(value, function () { - Object.keys(value).sort().forEach(function (key) { - canonicalizedObj[key] = exports.canonicalize(value[key], stack); - }); - }); - break; - - case 'date': - case 'number': - case 'regexp': - case 'boolean': - case 'symbol': - canonicalizedObj = value; - break; - - default: - canonicalizedObj = value + ''; - } - - return canonicalizedObj; - }; - /** - * @summary - * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) - * @description - * When invoking this function you get a filter function that get the Error.stack as an input, - * and return a prettify output. - * (i.e: strip Mocha and internal node functions from stack trace). - * @returns {Function} - */ - - - exports.stackTraceFilter = function () { - // TODO: Replace with `process.browser` - var is = typeof document === 'undefined' ? { - node: true - } : { - browser: true - }; - var slash = path$1.sep; - var cwd; - - if (is.node) { - cwd = exports.cwd() + slash; - } else { - cwd = (typeof location === 'undefined' ? window.location : location).href.replace(/\/[^/]*$/, '/'); - slash = '/'; - } - - function isMochaInternal(line) { - return ~line.indexOf('node_modules' + slash + 'mocha' + slash) || ~line.indexOf(slash + 'mocha.js') || ~line.indexOf(slash + 'mocha.min.js'); - } - - function isNodeInternal(line) { - return ~line.indexOf('(timers.js:') || ~line.indexOf('(events.js:') || ~line.indexOf('(node.js:') || ~line.indexOf('(module.js:') || ~line.indexOf('GeneratorFunctionPrototype.next (native)') || false; - } - - return function (stack) { - stack = stack.split('\n'); - stack = stack.reduce(function (list, line) { - if (isMochaInternal(line)) { - return list; - } - - if (is.node && isNodeInternal(line)) { - return list; - } // Clean up cwd(absolute) - - - if (/:\d+:\d+\)?$/.test(line)) { - line = line.replace('(' + cwd, '('); - } - - list.push(line); - return list; - }, []); - return stack.join('\n'); - }; - }; - /** - * Crude, but effective. - * @public - * @param {*} value - * @returns {boolean} Whether or not `value` is a Promise - */ - - - exports.isPromise = function isPromise(value) { - return _typeof(value) === 'object' && value !== null && typeof value.then === 'function'; - }; - /** - * Clamps a numeric value to an inclusive range. - * - * @param {number} value - Value to be clamped. - * @param {number[]} range - Two element array specifying [min, max] range. - * @returns {number} clamped value - */ - - - exports.clamp = function clamp(value, range) { - return Math.min(Math.max(value, range[0]), range[1]); - }; - /** - * Single quote text by combining with undirectional ASCII quotation marks. - * - * @description - * Provides a simple means of markup for quoting text to be used in output. - * Use this to quote names of variables, methods, and packages. - * - * package 'foo' cannot be found - * - * @private - * @param {string} str - Value to be quoted. - * @returns {string} quoted value - * @example - * sQuote('n') // => 'n' - */ - - - exports.sQuote = function (str) { - return "'" + str + "'"; - }; - /** - * Double quote text by combining with undirectional ASCII quotation marks. - * - * @description - * Provides a simple means of markup for quoting text to be used in output. - * Use this to quote names of datatypes, classes, pathnames, and strings. - * - * argument 'value' must be "string" or "number" - * - * @private - * @param {string} str - Value to be quoted. - * @returns {string} quoted value - * @example - * dQuote('number') // => "number" - */ - - - exports.dQuote = function (str) { - return '"' + str + '"'; - }; - /** - * It's a noop. - * @public - */ - - - exports.noop = function () {}; - /** - * Creates a map-like object. - * - * @description - * A "map" is an object with no prototype, for our purposes. In some cases - * this would be more appropriate than a `Map`, especially if your environment - * doesn't support it. Recommended for use in Mocha's public APIs. - * - * @public - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Custom_and_Null_objects|MDN:Map} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Custom_and_Null_objects|MDN:Object.assign} - * @param {...*} [obj] - Arguments to `Object.assign()`. - * @returns {Object} An object with no prototype, having `...obj` properties - */ - - - exports.createMap = function (obj) { - return Object.assign.apply(null, [Object.create(null)].concat(Array.prototype.slice.call(arguments))); - }; - /** - * Creates a read-only map-like object. - * - * @description - * This differs from {@link module:utils.createMap createMap} only in that - * the argument must be non-empty, because the result is frozen. - * - * @see {@link module:utils.createMap createMap} - * @param {...*} [obj] - Arguments to `Object.assign()`. - * @returns {Object} A frozen object with no prototype, having `...obj` properties - * @throws {TypeError} if argument is not a non-empty object. - */ - - - exports.defineConstants = function (obj) { - if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) { - throw new TypeError('Invalid argument; expected a non-empty object'); - } - - return Object.freeze(exports.createMap(obj)); - }; - /** - * Whether current version of Node support ES modules - * - * @description - * Versions prior to 10 did not support ES Modules, and version 10 has an old incompatible version of ESM. - * This function returns whether Node.JS has ES Module supports that is compatible with Mocha's needs, - * which is version >=12.11. - * - * @param {partialSupport} whether the full Node.js ESM support is available (>= 12) or just something that supports the runtime (>= 10) - * - * @returns {Boolean} whether the current version of Node.JS supports ES Modules in a way that is compatible with Mocha - */ - - - exports.supportsEsModules = function (partialSupport) { - if (!exports.isBrowser() && process$1.versions && process$1.versions.node) { - var versionFields = process$1.versions.node.split('.'); - var major = +versionFields[0]; - var minor = +versionFields[1]; - - if (!partialSupport) { - return major >= 13 || major === 12 && minor >= 11; - } else { - return major >= 10; - } - } - }; - /** - * Returns current working directory - * - * Wrapper around `process.cwd()` for isolation - * @private - */ - - - exports.cwd = function cwd() { - return process$1.cwd(); - }; - /** - * Returns `true` if Mocha is running in a browser. - * Checks for `process.browser`. - * @returns {boolean} - * @private - */ - - - exports.isBrowser = function isBrowser() { - return Boolean(browser$1); - }; - /** - * Lookup file names at the given `path`. - * - * @description - * Filenames are returned in _traversal_ order by the OS/filesystem. - * **Make no assumption that the names will be sorted in any fashion.** - * - * @public - * @alias module:lib/cli.lookupFiles - * @param {string} filepath - Base path to start searching from. - * @param {string[]} [extensions=[]] - File extensions to look for. - * @param {boolean} [recursive=false] - Whether to recurse into subdirectories. - * @return {string[]} An array of paths. - * @throws {Error} if no files match pattern. - * @throws {TypeError} if `filepath` is directory and `extensions` not provided. - * @deprecated Moved to {@link module:lib/cli.lookupFiles} - */ - - - exports.lookupFiles = function () { - if (exports.isBrowser()) { - throw errors.createUnsupportedError('lookupFiles() is only supported in Node.js!'); - } - - errors.deprecate('`lookupFiles()` in module `mocha/lib/utils` has moved to module `mocha/lib/cli` and will be removed in the next major revision of Mocha'); - return require$$11.lookupFiles.apply(require$$11, arguments); - }; - /* - * Casts `value` to an array; useful for optionally accepting array parameters - * - * It follows these rules, depending on `value`. If `value` is... - * 1. `undefined`: return an empty Array - * 2. `null`: return an array with a single `null` element - * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable - * 4. otherwise: return an array with a single element, `value` - * @param {*} value - Something to cast to an Array - * @returns {Array<*>} - */ - - - exports.castArray = function castArray(value) { - if (value === undefined) { - return []; - } - - if (value === null) { - return [null]; - } - - if (_typeof(value) === 'object' && (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)) { - return Array.from(value); - } - - return [value]; - }; - - exports.constants = exports.defineConstants({ - MOCHA_ID_PROP_NAME: MOCHA_ID_PROP_NAME - }); - /** - * Creates a new unique identifier - * @returns {string} Unique identifier - */ - - exports.uniqueID = function () { - return nanoid(); - }; - - exports.assignNewMochaID = function (obj) { - var id = exports.uniqueID(); - Object.defineProperty(obj, MOCHA_ID_PROP_NAME, { - get: function get() { - return id; - } - }); - return obj; - }; - /** - * Retrieves a Mocha ID from an object, if present. - * @param {*} [obj] - Object - * @returns {string|void} - */ - - - exports.getMochaID = function (obj) { - return obj && _typeof(obj) === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined; - }; - }); - - // `Map` constructor - // https://tc39.es/ecma262/#sec-map-objects - collection('Map', function (init) { - return function Map() { return init(this, arguments.length ? arguments[0] : undefined); }; - }, collectionStrong); - - /** - @module Pending - */ - - var pending = Pending; - /** - * Initialize a new `Pending` error with the given message. - * - * @param {string} message - */ - - function Pending(message) { - this.message = message; - } - - /** - * Helpers. - */ - var s$1 = 1000; - var m$1 = s$1 * 60; - var h$1 = m$1 * 60; - var d$1 = h$1 * 24; - var w$1 = d$1 * 7; - var y$1 = d$1 * 365.25; - /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ - - var ms$1 = function ms(val, options) { - options = options || {}; - - var type = _typeof(val); - - if (type === 'string' && val.length > 0) { - return parse$1(val); - } else if (type === 'number' && isFinite(val)) { - return options["long"] ? fmtLong$1(val) : fmtShort$1(val); - } - - throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)); - }; - /** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - - - function parse$1(str) { - str = String(str); - - if (str.length > 100) { - return; - } - - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); - - if (!match) { - return; - } - - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y$1; - - case 'weeks': - case 'week': - case 'w': - return n * w$1; - - case 'days': - case 'day': - case 'd': - return n * d$1; - - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h$1; - - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m$1; - - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s$1; - - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - - default: - return undefined; - } - } - /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - - function fmtShort$1(ms) { - var msAbs = Math.abs(ms); - - if (msAbs >= d$1) { - return Math.round(ms / d$1) + 'd'; - } - - if (msAbs >= h$1) { - return Math.round(ms / h$1) + 'h'; - } - - if (msAbs >= m$1) { - return Math.round(ms / m$1) + 'm'; - } - - if (msAbs >= s$1) { - return Math.round(ms / s$1) + 's'; - } - - return ms + 'ms'; - } - /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - - - function fmtLong$1(ms) { - var msAbs = Math.abs(ms); - - if (msAbs >= d$1) { - return plural$1(ms, msAbs, d$1, 'day'); - } - - if (msAbs >= h$1) { - return plural$1(ms, msAbs, h$1, 'hour'); - } - - if (msAbs >= m$1) { - return plural$1(ms, msAbs, m$1, 'minute'); - } - - if (msAbs >= s$1) { - return plural$1(ms, msAbs, s$1, 'second'); - } - - return ms + ' ms'; - } - /** - * Pluralization helper. - */ - - - function plural$1(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); - } - - /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - - function setup(env) { - createDebug.debug = createDebug; - createDebug["default"] = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = ms$1; - createDebug.destroy = destroy; - Object.keys(env).forEach(function (key) { - createDebug[key] = env[key]; - }); - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - - createDebug.formatters = {}; - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - - function selectColor(namespace) { - var hash = 0; - - for (var i = 0; i < namespace.length; i++) { - hash = (hash << 5) - hash + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - - createDebug.selectColor = selectColor; - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - - function createDebug(namespace) { - var prevTime; - var enableOverride = null; - - function debug() { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - // Disabled? - if (!debug.enabled) { - return; - } - - var self = debug; // Set `diff` timestamp - - var curr = Number(new Date()); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } // Apply any `formatters` transformations - - - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - - index++; - var formatter = createDebug.formatters[format]; - - if (typeof formatter === 'function') { - var val = args[index]; - match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` - - args.splice(index, 1); - index--; - } - - return match; - }); // Apply env-specific formatting (colors, etc.) - - createDebug.formatArgs.call(self, args); - var logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: function get() { - return enableOverride === null ? createDebug.enabled(namespace) : enableOverride; - }, - set: function set(v) { - enableOverride = v; - } - }); // Env-specific initialization logic for debug instances - - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - - - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.names = []; - createDebug.skips = []; - var i; - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } - - namespaces = split[i].replace(/\*/g, '.*?'); - - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - - - function disable() { - var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) { - return '-' + namespace; - }))).join(','); - createDebug.enable(''); - return namespaces; - } - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - - - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } - - var i; - var len; - - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } - - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } - - return false; - } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - - - function toNamespace(regexp) { - return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*'); - } - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - - - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - - return val; - } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - - - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - return createDebug; - } - - var common = setup; - - var browser$2 = createCommonjsModule(function (module, exports) { - /* eslint-env browser */ - - /** - * This is the web browser implementation of `debug()`. - */ - exports.formatArgs = formatArgs; - exports.save = save; - exports.load = load; - exports.useColors = useColors; - exports.storage = localstorage(); - - exports.destroy = function () { - var warned = false; - return function () { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; - }(); - /** - * Colors. - */ - - - exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33']; - /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - // eslint-disable-next-line complexity - - function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } // Internet Explorer and Edge do not support colors. - - - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - - - return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 - typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker - typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); - } - /** - * Colorize log arguments if enabled. - * - * @api public - */ - - - function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function (match) { - if (match === '%%') { - return; - } - - index++; - - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - args.splice(lastC, 0, c); - } - /** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ - - - exports.log = console.debug || console.log || function () {}; - /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - - - function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) {// Swallow - // XXX (@Qix-) should we be logging these? - } - } - /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - - - function load() { - var r; - - try { - r = exports.storage.getItem('debug'); - } catch (error) {// Swallow - // XXX (@Qix-) should we be logging these? - } // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - - - if (!r && typeof process$1 !== 'undefined' && 'env' in process$1) { - r = process$1.env.DEBUG; - } - - return r; - } - /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - - - function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) {// Swallow - // XXX (@Qix-) should we be logging these? - } - } - - module.exports = common(exports); - var formatters = module.exports.formatters; - /** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - - formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } - }; - }); - - var EventEmitter$1 = EventEmitter.EventEmitter; - var debug$1 = browser$2('mocha:runnable'); - var createInvalidExceptionError$1 = errors.createInvalidExceptionError, - createMultipleDoneError$1 = errors.createMultipleDoneError, - createTimeoutError$1 = errors.createTimeoutError; - /** - * Save timer references to avoid Sinon interfering (see GH-237). - * @private - */ - - var Date$1 = commonjsGlobal.Date; - var setTimeout$1 = commonjsGlobal.setTimeout; - var clearTimeout$1 = commonjsGlobal.clearTimeout; - var toString$4 = Object.prototype.toString; - var runnable = Runnable; - /** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @class - * @extends external:EventEmitter - * @public - * @param {String} title - * @param {Function} fn - */ - - function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.body = (fn || '').toString(); - this.async = fn && fn.length; - this.sync = !this.async; - this._timeout = 2000; - this._slow = 75; - this._retries = -1; - utils.assignNewMochaID(this); - Object.defineProperty(this, 'id', { - get: function get() { - return utils.getMochaID(this); - } - }); - this.reset(); - } - /** - * Inherit from `EventEmitter.prototype`. - */ - - - utils.inherits(Runnable, EventEmitter$1); - /** - * Resets the state initially or for a next run. - */ - - Runnable.prototype.reset = function () { - this.timedOut = false; - this._currentRetry = 0; - this.pending = false; - delete this.state; - delete this.err; - }; - /** - * Get current timeout value in msecs. - * - * @private - * @returns {number} current timeout threshold value - */ - - /** - * @summary - * Set timeout threshold value (msecs). - * - * @description - * A string argument can use shorthand (e.g., "2s") and will be converted. - * The value will be clamped to range [0, 2^31-1]. - * If clamped value matches either range endpoint, timeouts will be disabled. - * - * @private - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value} - * @param {number|string} ms - Timeout threshold value. - * @returns {Runnable} this - * @chainable - */ - - - Runnable.prototype.timeout = function (ms$1) { - if (!arguments.length) { - return this._timeout; - } - - if (typeof ms$1 === 'string') { - ms$1 = ms(ms$1); - } // Clamp to range - - - var INT_MAX = Math.pow(2, 31) - 1; - var range = [0, INT_MAX]; - ms$1 = utils.clamp(ms$1, range); // see #1652 for reasoning - - if (ms$1 === range[0] || ms$1 === range[1]) { - this._timeout = 0; - } else { - this._timeout = ms$1; - } - - debug$1('timeout %d', this._timeout); - - if (this.timer) { - this.resetTimeout(); - } - - return this; - }; - /** - * Set or get slow `ms`. - * - * @private - * @param {number|string} ms - * @return {Runnable|number} ms or Runnable instance. - */ - - - Runnable.prototype.slow = function (ms$1) { - if (!arguments.length || typeof ms$1 === 'undefined') { - return this._slow; - } - - if (typeof ms$1 === 'string') { - ms$1 = ms(ms$1); - } - - debug$1('slow %d', ms$1); - this._slow = ms$1; - return this; - }; - /** - * Halt and mark as pending. - * - * @memberof Mocha.Runnable - * @public - */ - - - Runnable.prototype.skip = function () { - this.pending = true; - throw new pending('sync skip; aborting execution'); - }; - /** - * Check if this runnable or its parent suite is marked as pending. - * - * @private - */ - - - Runnable.prototype.isPending = function () { - return this.pending || this.parent && this.parent.isPending(); - }; - /** - * Return `true` if this Runnable has failed. - * @return {boolean} - * @private - */ - - - Runnable.prototype.isFailed = function () { - return !this.isPending() && this.state === constants$1.STATE_FAILED; - }; - /** - * Return `true` if this Runnable has passed. - * @return {boolean} - * @private - */ - - - Runnable.prototype.isPassed = function () { - return !this.isPending() && this.state === constants$1.STATE_PASSED; - }; - /** - * Set or get number of retries. - * - * @private - */ - - - Runnable.prototype.retries = function (n) { - if (!arguments.length) { - return this._retries; - } - - this._retries = n; - }; - /** - * Set or get current retry - * - * @private - */ - - - Runnable.prototype.currentRetry = function (n) { - if (!arguments.length) { - return this._currentRetry; - } - - this._currentRetry = n; - }; - /** - * Return the full title generated by recursively concatenating the parent's - * full title. - * - * @memberof Mocha.Runnable - * @public - * @return {string} - */ - - - Runnable.prototype.fullTitle = function () { - return this.titlePath().join(' '); - }; - /** - * Return the title path generated by concatenating the parent's title path with the title. - * - * @memberof Mocha.Runnable - * @public - * @return {string} - */ - - - Runnable.prototype.titlePath = function () { - return this.parent.titlePath().concat([this.title]); - }; - /** - * Clear the timeout. - * - * @private - */ - - - Runnable.prototype.clearTimeout = function () { - clearTimeout$1(this.timer); - }; - /** - * Reset the timeout. - * - * @private - */ - - - Runnable.prototype.resetTimeout = function () { - var self = this; - var ms = this.timeout(); - - if (ms === 0) { - return; - } - - this.clearTimeout(); - this.timer = setTimeout$1(function () { - if (self.timeout() === 0) { - return; - } - - self.callback(self._timeoutError(ms)); - self.timedOut = true; - }, ms); - }; - /** - * Set or get a list of whitelisted globals for this test run. - * - * @private - * @param {string[]} globals - */ - - - Runnable.prototype.globals = function (globals) { - if (!arguments.length) { - return this._allowedGlobals; - } - - this._allowedGlobals = globals; - }; - /** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @private - */ - - - Runnable.prototype.run = function (fn) { - var self = this; - var start = new Date$1(); - var ctx = this.ctx; - var finished; - var errorWasHandled = false; - if (this.isPending()) return fn(); // Sometimes the ctx exists, but it is not runnable - - if (ctx && ctx.runnable) { - ctx.runnable(this); - } // called multiple times - - - function multiple(err) { - if (errorWasHandled) { - return; - } - - errorWasHandled = true; - self.emit('error', createMultipleDoneError$1(self, err)); - } // finished - - - function done(err) { - var ms = self.timeout(); - - if (self.timedOut) { - return; - } - - if (finished) { - return multiple(err); - } - - self.clearTimeout(); - self.duration = new Date$1() - start; - finished = true; - - if (!err && self.duration > ms && ms > 0) { - err = self._timeoutError(ms); - } - - fn(err); - } // for .resetTimeout() and Runner#uncaught() - - - this.callback = done; - - if (this.fn && typeof this.fn.call !== 'function') { - done(new TypeError('A runnable must be passed a function as its second argument.')); - return; - } // explicit async with `done` argument - - - if (this.async) { - this.resetTimeout(); // allows skip() to be used in an explicit async context - - this.skip = function asyncSkip() { - this.pending = true; - done(); // halt execution, the uncaught handler will ignore the failure. - - throw new pending('async skip; aborting execution'); - }; - - try { - callFnAsync(this.fn); - } catch (err) { - // handles async runnables which actually run synchronously - errorWasHandled = true; - - if (err instanceof pending) { - return; // done() is already called in this.skip() - } else if (this.allowUncaught) { - throw err; - } - - done(Runnable.toValueOrError(err)); - } - - return; - } // sync or promise-returning - - - try { - callFn(this.fn); - } catch (err) { - errorWasHandled = true; - - if (err instanceof pending) { - return done(); - } else if (this.allowUncaught) { - throw err; - } - - done(Runnable.toValueOrError(err)); - } - - function callFn(fn) { - var result = fn.call(ctx); - - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result.then(function () { - done(); // Return null so libraries like bluebird do not warn about - // subsequently constructed Promises. - - return null; - }, function (reason) { - done(reason || new Error('Promise rejected with no or falsy reason')); - }); - } else { - if (self.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()` or returning a promise')); - } - - done(); - } - } - - function callFnAsync(fn) { - var result = fn.call(ctx, function (err) { - if (err instanceof Error || toString$4.call(err) === '[object Error]') { - return done(err); - } - - if (err) { - if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); - } - - return done(new Error('done() invoked with non-Error: ' + err)); - } - - if (result && utils.isPromise(result)) { - return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.')); - } - - done(); - }); - } - }; - /** - * Instantiates a "timeout" error - * - * @param {number} ms - Timeout (in milliseconds) - * @returns {Error} a "timeout" error - * @private - */ - - - Runnable.prototype._timeoutError = function (ms) { - var msg = "Timeout of ".concat(ms, "ms exceeded. For async tests and hooks, ensure \"done()\" is called; if returning a Promise, ensure it resolves."); - - if (this.file) { - msg += ' (' + this.file + ')'; - } - - return createTimeoutError$1(msg, ms, this.file); - }; - - var constants$1 = utils.defineConstants( - /** - * {@link Runnable}-related constants. - * @public - * @memberof Runnable - * @readonly - * @static - * @alias constants - * @enum {string} - */ - { - /** - * Value of `state` prop when a `Runnable` has failed - */ - STATE_FAILED: 'failed', - - /** - * Value of `state` prop when a `Runnable` has passed - */ - STATE_PASSED: 'passed', - - /** - * Value of `state` prop when a `Runnable` has been skipped by user - */ - STATE_PENDING: 'pending' - }); - /** - * Given `value`, return identity if truthy, otherwise create an "invalid exception" error and return that. - * @param {*} [value] - Value to return, if present - * @returns {*|Error} `value`, otherwise an `Error` - * @private - */ - - Runnable.toValueOrError = function (value) { - return value || createInvalidExceptionError$1('Runnable failed with falsy or undefined exception. Please throw an Error instead.', value); - }; - - Runnable.constants = constants$1; - - var inherits$3 = utils.inherits, - constants$2 = utils.constants; - var MOCHA_ID_PROP_NAME = constants$2.MOCHA_ID_PROP_NAME; - /** - * Expose `Hook`. - */ - - var hook = Hook; - /** - * Initialize a new `Hook` with the given `title` and callback `fn` - * - * @class - * @extends Runnable - * @param {String} title - * @param {Function} fn - */ - - function Hook(title, fn) { - runnable.call(this, title, fn); - this.type = 'hook'; - } - /** - * Inherit from `Runnable.prototype`. - */ - - - inherits$3(Hook, runnable); - /** - * Resets the state for a next run. - */ - - Hook.prototype.reset = function () { - runnable.prototype.reset.call(this); - delete this._error; - }; - /** - * Get or set the test `err`. - * - * @memberof Hook - * @public - * @param {Error} err - * @return {Error} - */ - - - Hook.prototype.error = function (err) { - if (!arguments.length) { - err = this._error; - this._error = null; - return err; - } - - this._error = err; - }; - /** - * Returns an object suitable for IPC. - * Functions are represented by keys beginning with `$$`. - * @private - * @returns {Object} - */ - - - Hook.prototype.serialize = function serialize() { - return _defineProperty({ - $$isPending: this.isPending(), - $$titlePath: this.titlePath(), - ctx: this.ctx && this.ctx.currentTest ? { - currentTest: _defineProperty({ - title: this.ctx.currentTest.title - }, MOCHA_ID_PROP_NAME, this.ctx.currentTest.id) - } : {}, - parent: _defineProperty({}, MOCHA_ID_PROP_NAME, this.parent.id), - title: this.title, - type: this.type - }, MOCHA_ID_PROP_NAME, this.id); - }; - - var suite = createCommonjsModule(function (module, exports) { - /** - * Module dependencies. - * @private - */ - - var EventEmitter$1 = EventEmitter.EventEmitter; - var assignNewMochaID = utils.assignNewMochaID, - clamp = utils.clamp, - utilsConstants = utils.constants, - createMap = utils.createMap, - defineConstants = utils.defineConstants, - getMochaID = utils.getMochaID, - inherits = utils.inherits, - isString = utils.isString; - var debug = browser$2('mocha:suite'); - var MOCHA_ID_PROP_NAME = utilsConstants.MOCHA_ID_PROP_NAME; - /** - * Expose `Suite`. - */ - - module.exports = Suite; - /** - * Create a new `Suite` with the given `title` and parent `Suite`. - * - * @public - * @param {Suite} parent - Parent suite (required!) - * @param {string} title - Title - * @return {Suite} - */ - - Suite.create = function (parent, title) { - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; - }; - /** - * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`. - * - * @public - * @class - * @extends EventEmitter - * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter} - * @param {string} title - Suite title. - * @param {Context} parentContext - Parent context instance. - * @param {boolean} [isRoot=false] - Whether this is the root suite. - */ - - - function Suite(title, parentContext, isRoot) { - if (!isString(title)) { - throw errors.createInvalidArgumentTypeError('Suite argument "title" must be a string. Received type "' + _typeof(title) + '"', 'title', 'string'); - } - - this.title = title; - - function Context() {} - - Context.prototype = parentContext; - this.ctx = new Context(); - this.suites = []; - this.tests = []; - this.root = isRoot === true; - this.pending = false; - this._retries = -1; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this._timeout = 2000; - this._slow = 75; - this._bail = false; - this._onlyTests = []; - this._onlySuites = []; - assignNewMochaID(this); - Object.defineProperty(this, 'id', { - get: function get() { - return getMochaID(this); - } - }); - this.reset(); - this.on('newListener', function (event) { - if (deprecatedEvents[event]) { - errors.deprecate('Event "' + event + '" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'); - } - }); - } - /** - * Inherit from `EventEmitter.prototype`. - */ - - - inherits(Suite, EventEmitter$1); - /** - * Resets the state initially or for a next run. - */ - - Suite.prototype.reset = function () { - this.delayed = false; - - function doReset(thingToReset) { - thingToReset.reset(); - } - - this.suites.forEach(doReset); - this.tests.forEach(doReset); - - this._beforeEach.forEach(doReset); - - this._afterEach.forEach(doReset); - - this._beforeAll.forEach(doReset); - - this._afterAll.forEach(doReset); - }; - /** - * Return a clone of this `Suite`. - * - * @private - * @return {Suite} - */ - - - Suite.prototype.clone = function () { - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.root = this.root; - suite.timeout(this.timeout()); - suite.retries(this.retries()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; - }; - /** - * Set or get timeout `ms` or short-hand such as "2s". - * - * @private - * @todo Do not attempt to set value if `ms` is undefined - * @param {number|string} ms - * @return {Suite|number} for chaining - */ - - - Suite.prototype.timeout = function (ms$1) { - if (!arguments.length) { - return this._timeout; - } - - if (typeof ms$1 === 'string') { - ms$1 = ms(ms$1); - } // Clamp to range - - - var INT_MAX = Math.pow(2, 31) - 1; - var range = [0, INT_MAX]; - ms$1 = clamp(ms$1, range); - debug('timeout %d', ms$1); - this._timeout = parseInt(ms$1, 10); - return this; - }; - /** - * Set or get number of times to retry a failed test. - * - * @private - * @param {number|string} n - * @return {Suite|number} for chaining - */ - - - Suite.prototype.retries = function (n) { - if (!arguments.length) { - return this._retries; - } - - debug('retries %d', n); - this._retries = parseInt(n, 10) || 0; - return this; - }; - /** - * Set or get slow `ms` or short-hand such as "2s". - * - * @private - * @param {number|string} ms - * @return {Suite|number} for chaining - */ - - - Suite.prototype.slow = function (ms$1) { - if (!arguments.length) { - return this._slow; - } - - if (typeof ms$1 === 'string') { - ms$1 = ms(ms$1); - } - - debug('slow %d', ms$1); - this._slow = ms$1; - return this; - }; - /** - * Set or get whether to bail after first error. - * - * @private - * @param {boolean} bail - * @return {Suite|number} for chaining - */ - - - Suite.prototype.bail = function (bail) { - if (!arguments.length) { - return this._bail; - } - - debug('bail %s', bail); - this._bail = bail; - return this; - }; - /** - * Check if this suite or its parent suite is marked as pending. - * - * @private - */ - - - Suite.prototype.isPending = function () { - return this.pending || this.parent && this.parent.isPending(); - }; - /** - * Generic hook-creator. - * @private - * @param {string} title - Title of hook - * @param {Function} fn - Hook callback - * @returns {Hook} A new hook - */ - - - Suite.prototype._createHook = function (title, fn) { - var hook$1 = new hook(title, fn); - hook$1.parent = this; - hook$1.timeout(this.timeout()); - hook$1.retries(this.retries()); - hook$1.slow(this.slow()); - hook$1.ctx = this.ctx; - hook$1.file = this.file; - return hook$1; - }; - /** - * Run `fn(test[, done])` before running tests. - * - * @private - * @param {string} title - * @param {Function} fn - * @return {Suite} for chaining - */ - - - Suite.prototype.beforeAll = function (title, fn) { - if (this.isPending()) { - return this; - } - - if (typeof title === 'function') { - fn = title; - title = fn.name; - } - - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = this._createHook(title, fn); - - this._beforeAll.push(hook); - - this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook); - return this; - }; - /** - * Run `fn(test[, done])` after running tests. - * - * @private - * @param {string} title - * @param {Function} fn - * @return {Suite} for chaining - */ - - - Suite.prototype.afterAll = function (title, fn) { - if (this.isPending()) { - return this; - } - - if (typeof title === 'function') { - fn = title; - title = fn.name; - } - - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = this._createHook(title, fn); - - this._afterAll.push(hook); - - this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook); - return this; - }; - /** - * Run `fn(test[, done])` before each test case. - * - * @private - * @param {string} title - * @param {Function} fn - * @return {Suite} for chaining - */ - - - Suite.prototype.beforeEach = function (title, fn) { - if (this.isPending()) { - return this; - } - - if (typeof title === 'function') { - fn = title; - title = fn.name; - } - - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = this._createHook(title, fn); - - this._beforeEach.push(hook); - - this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook); - return this; - }; - /** - * Run `fn(test[, done])` after each test case. - * - * @private - * @param {string} title - * @param {Function} fn - * @return {Suite} for chaining - */ - - - Suite.prototype.afterEach = function (title, fn) { - if (this.isPending()) { - return this; - } - - if (typeof title === 'function') { - fn = title; - title = fn.name; - } - - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = this._createHook(title, fn); - - this._afterEach.push(hook); - - this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook); - return this; - }; - /** - * Add a test `suite`. - * - * @private - * @param {Suite} suite - * @return {Suite} for chaining - */ - - - Suite.prototype.addSuite = function (suite) { - suite.parent = this; - suite.root = false; - suite.timeout(this.timeout()); - suite.retries(this.retries()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit(constants.EVENT_SUITE_ADD_SUITE, suite); - return this; - }; - /** - * Add a `test` to this suite. - * - * @private - * @param {Test} test - * @return {Suite} for chaining - */ - - - Suite.prototype.addTest = function (test) { - test.parent = this; - test.timeout(this.timeout()); - test.retries(this.retries()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit(constants.EVENT_SUITE_ADD_TEST, test); - return this; - }; - /** - * Return the full title generated by recursively concatenating the parent's - * full title. - * - * @memberof Suite - * @public - * @return {string} - */ - - - Suite.prototype.fullTitle = function () { - return this.titlePath().join(' '); - }; - /** - * Return the title path generated by recursively concatenating the parent's - * title path. - * - * @memberof Suite - * @public - * @return {string} - */ - - - Suite.prototype.titlePath = function () { - var result = []; - - if (this.parent) { - result = result.concat(this.parent.titlePath()); - } - - if (!this.root) { - result.push(this.title); - } - - return result; - }; - /** - * Return the total number of tests. - * - * @memberof Suite - * @public - * @return {number} - */ - - - Suite.prototype.total = function () { - return this.suites.reduce(function (sum, suite) { - return sum + suite.total(); - }, 0) + this.tests.length; - }; - /** - * Iterates through each suite recursively to find all tests. Applies a - * function in the format `fn(test)`. - * - * @private - * @param {Function} fn - * @return {Suite} - */ - - - Suite.prototype.eachTest = function (fn) { - this.tests.forEach(fn); - this.suites.forEach(function (suite) { - suite.eachTest(fn); - }); - return this; - }; - /** - * This will run the root suite if we happen to be running in delayed mode. - * @private - */ - - - Suite.prototype.run = function run() { - if (this.root) { - this.emit(constants.EVENT_ROOT_SUITE_RUN); - } - }; - /** - * Determines whether a suite has an `only` test or suite as a descendant. - * - * @private - * @returns {Boolean} - */ - - - Suite.prototype.hasOnly = function hasOnly() { - return this._onlyTests.length > 0 || this._onlySuites.length > 0 || this.suites.some(function (suite) { - return suite.hasOnly(); - }); - }; - /** - * Filter suites based on `isOnly` logic. - * - * @private - * @returns {Boolean} - */ - - - Suite.prototype.filterOnly = function filterOnly() { - if (this._onlyTests.length) { - // If the suite contains `only` tests, run those and ignore any nested suites. - this.tests = this._onlyTests; - this.suites = []; - } else { - // Otherwise, do not run any of the tests in this suite. - this.tests = []; - - this._onlySuites.forEach(function (onlySuite) { - // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. - // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. - if (onlySuite.hasOnly()) { - onlySuite.filterOnly(); - } - }); // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. - - - var onlySuites = this._onlySuites; - this.suites = this.suites.filter(function (childSuite) { - return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly(); - }); - } // Keep the suite only if there is something to run - - - return this.tests.length > 0 || this.suites.length > 0; - }; - /** - * Adds a suite to the list of subsuites marked `only`. - * - * @private - * @param {Suite} suite - */ - - - Suite.prototype.appendOnlySuite = function (suite) { - this._onlySuites.push(suite); - }; - /** - * Marks a suite to be `only`. - * - * @private - */ - - - Suite.prototype.markOnly = function () { - this.parent && this.parent.appendOnlySuite(this); - }; - /** - * Adds a test to the list of tests marked `only`. - * - * @private - * @param {Test} test - */ - - - Suite.prototype.appendOnlyTest = function (test) { - this._onlyTests.push(test); - }; - /** - * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants. - * @private - */ - - - Suite.prototype.getHooks = function getHooks(name) { - return this['_' + name]; - }; - /** - * cleans all references from this suite and all child suites. - */ - - - Suite.prototype.dispose = function () { - this.suites.forEach(function (suite) { - suite.dispose(); - }); - this.cleanReferences(); - }; - /** - * Cleans up the references to all the deferred functions - * (before/after/beforeEach/afterEach) and tests of a Suite. - * These must be deleted otherwise a memory leak can happen, - * as those functions may reference variables from closures, - * thus those variables can never be garbage collected as long - * as the deferred functions exist. - * - * @private - */ - - - Suite.prototype.cleanReferences = function cleanReferences() { - function cleanArrReferences(arr) { - for (var i = 0; i < arr.length; i++) { - delete arr[i].fn; - } - } - - if (Array.isArray(this._beforeAll)) { - cleanArrReferences(this._beforeAll); - } - - if (Array.isArray(this._beforeEach)) { - cleanArrReferences(this._beforeEach); - } - - if (Array.isArray(this._afterAll)) { - cleanArrReferences(this._afterAll); - } - - if (Array.isArray(this._afterEach)) { - cleanArrReferences(this._afterEach); - } - - for (var i = 0; i < this.tests.length; i++) { - delete this.tests[i].fn; - } - }; - /** - * Returns an object suitable for IPC. - * Functions are represented by keys beginning with `$$`. - * @private - * @returns {Object} - */ - - - Suite.prototype.serialize = function serialize() { - return { - _bail: this._bail, - $$fullTitle: this.fullTitle(), - $$isPending: this.isPending(), - root: this.root, - title: this.title, - id: this.id, - parent: this.parent ? _defineProperty({}, MOCHA_ID_PROP_NAME, this.parent.id) : null - }; - }; - - var constants = defineConstants( - /** - * {@link Suite}-related constants. - * @public - * @memberof Suite - * @alias constants - * @readonly - * @static - * @enum {string} - */ - { - /** - * Event emitted after a test file has been loaded Not emitted in browser. - */ - EVENT_FILE_POST_REQUIRE: 'post-require', - - /** - * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected. - */ - EVENT_FILE_PRE_REQUIRE: 'pre-require', - - /** - * Event emitted immediately after a test file has been loaded. Not emitted in browser. - */ - EVENT_FILE_REQUIRE: 'require', - - /** - * Event emitted when `global.run()` is called (use with `delay` option) - */ - EVENT_ROOT_SUITE_RUN: 'run', - - /** - * Namespace for collection of a `Suite`'s "after all" hooks - */ - HOOK_TYPE_AFTER_ALL: 'afterAll', - - /** - * Namespace for collection of a `Suite`'s "after each" hooks - */ - HOOK_TYPE_AFTER_EACH: 'afterEach', - - /** - * Namespace for collection of a `Suite`'s "before all" hooks - */ - HOOK_TYPE_BEFORE_ALL: 'beforeAll', - - /** - * Namespace for collection of a `Suite`'s "before all" hooks - */ - HOOK_TYPE_BEFORE_EACH: 'beforeEach', - // the following events are all deprecated - - /** - * Emitted after an "after all" `Hook` has been added to a `Suite`. Deprecated - */ - EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll', - - /** - * Emitted after an "after each" `Hook` has been added to a `Suite` Deprecated - */ - EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach', - - /** - * Emitted after an "before all" `Hook` has been added to a `Suite` Deprecated - */ - EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll', - - /** - * Emitted after an "before each" `Hook` has been added to a `Suite` Deprecated - */ - EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach', - - /** - * Emitted after a child `Suite` has been added to a `Suite`. Deprecated - */ - EVENT_SUITE_ADD_SUITE: 'suite', - - /** - * Emitted after a `Test` has been added to a `Suite`. Deprecated - */ - EVENT_SUITE_ADD_TEST: 'test' - }); - /** - * @summary There are no known use cases for these events. - * @desc This is a `Set`-like object having all keys being the constant's string value and the value being `true`. - * @todo Remove eventually - * @type {Object} - * @ignore - */ - - var deprecatedEvents = Object.keys(constants).filter(function (constant) { - return constant.substring(0, 15) === 'EVENT_SUITE_ADD'; - }).reduce(function (acc, constant) { - acc[constants[constant]] = true; - return acc; - }, createMap()); - Suite.constants = constants; - }); - - /** - * Module dependencies. - * @private - */ - - - var EventEmitter$2 = EventEmitter.EventEmitter; - var debug$2 = browser$2('mocha:runner'); - var HOOK_TYPE_BEFORE_EACH = suite.constants.HOOK_TYPE_BEFORE_EACH; - var HOOK_TYPE_AFTER_EACH = suite.constants.HOOK_TYPE_AFTER_EACH; - var HOOK_TYPE_AFTER_ALL = suite.constants.HOOK_TYPE_AFTER_ALL; - var HOOK_TYPE_BEFORE_ALL = suite.constants.HOOK_TYPE_BEFORE_ALL; - var EVENT_ROOT_SUITE_RUN = suite.constants.EVENT_ROOT_SUITE_RUN; - var STATE_FAILED = runnable.constants.STATE_FAILED; - var STATE_PASSED = runnable.constants.STATE_PASSED; - var STATE_PENDING = runnable.constants.STATE_PENDING; - var dQuote = utils.dQuote; - var sQuote = utils.sQuote; - var stackFilter = utils.stackTraceFilter(); - var stringify = utils.stringify; - var createInvalidExceptionError$2 = errors.createInvalidExceptionError, - createUnsupportedError$1 = errors.createUnsupportedError, - createFatalError$1 = errors.createFatalError, - isMochaError$1 = errors.isMochaError, - errorConstants = errors.constants; - /** - * Non-enumerable globals. - * @private - * @readonly - */ - - var globals = ['setTimeout', 'clearTimeout', 'setInterval', 'clearInterval', 'XMLHttpRequest', 'Date', 'setImmediate', 'clearImmediate']; - var constants$3 = utils.defineConstants( - /** - * {@link Runner}-related constants. - * @public - * @memberof Runner - * @readonly - * @alias constants - * @static - * @enum {string} - */ - { - /** - * Emitted when {@link Hook} execution begins - */ - EVENT_HOOK_BEGIN: 'hook', - - /** - * Emitted when {@link Hook} execution ends - */ - EVENT_HOOK_END: 'hook end', - - /** - * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution) - */ - EVENT_RUN_BEGIN: 'start', - - /** - * Emitted when Root {@link Suite} execution has been delayed via `delay` option - */ - EVENT_DELAY_BEGIN: 'waiting', - - /** - * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()` - */ - EVENT_DELAY_END: 'ready', - - /** - * Emitted when Root {@link Suite} execution ends - */ - EVENT_RUN_END: 'end', - - /** - * Emitted when {@link Suite} execution begins - */ - EVENT_SUITE_BEGIN: 'suite', - - /** - * Emitted when {@link Suite} execution ends - */ - EVENT_SUITE_END: 'suite end', - - /** - * Emitted when {@link Test} execution begins - */ - EVENT_TEST_BEGIN: 'test', - - /** - * Emitted when {@link Test} execution ends - */ - EVENT_TEST_END: 'test end', - - /** - * Emitted when {@link Test} execution fails - */ - EVENT_TEST_FAIL: 'fail', - - /** - * Emitted when {@link Test} execution succeeds - */ - EVENT_TEST_PASS: 'pass', - - /** - * Emitted when {@link Test} becomes pending - */ - EVENT_TEST_PENDING: 'pending', - - /** - * Emitted when {@link Test} execution has failed, but will retry - */ - EVENT_TEST_RETRY: 'retry', - - /** - * Initial state of Runner - */ - STATE_IDLE: 'idle', - - /** - * State set to this value when the Runner has started running - */ - STATE_RUNNING: 'running', - - /** - * State set to this value when the Runner has stopped - */ - STATE_STOPPED: 'stopped' - }); - - var Runner = /*#__PURE__*/function (_EventEmitter) { - _inherits(Runner, _EventEmitter); - - var _super = _createSuper(Runner); - - /** - * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}. - * - * @extends external:EventEmitter - * @public - * @class - * @param {Suite} suite - Root suite - * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility). - * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready. - * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done. - */ - function Runner(suite, opts) { - var _this; - - _classCallCheck(this, Runner); - - _this = _super.call(this); - - if (opts === undefined) { - opts = {}; - } - - if (typeof opts === 'boolean') { - // TODO: deprecate this - _this._delay = opts; - opts = {}; - } else { - _this._delay = opts.delay; - } - - var self = _assertThisInitialized(_this); - - _this._globals = []; - _this._abort = false; - _this.suite = suite; - _this._opts = opts; - _this.state = constants$3.STATE_IDLE; - _this.total = suite.total(); - _this.failures = 0; - /** - * @type {Map>>} - */ - - _this._eventListeners = new Map(); - - _this.on(constants$3.EVENT_TEST_END, function (test) { - if (test.type === 'test' && test.retriedTest() && test.parent) { - var idx = test.parent.tests && test.parent.tests.indexOf(test.retriedTest()); - if (idx > -1) test.parent.tests[idx] = test; - } - - self.checkGlobals(test); - }); - - _this.on(constants$3.EVENT_HOOK_END, function (hook) { - self.checkGlobals(hook); - }); - - _this._defaultGrep = /.*/; - - _this.grep(_this._defaultGrep); - - _this.globals(_this.globalProps()); - - _this.uncaught = _this._uncaught.bind(_assertThisInitialized(_this)); - - _this.unhandled = function (reason, promise) { - if (isMochaError$1(reason)) { - debug$2('trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:', reason); - - _this.uncaught(reason); - } else { - debug$2('trapped unhandled rejection from (probably) user code; re-emitting on process'); - - _this._removeEventListener(process$1, 'unhandledRejection', _this.unhandled); - - try { - process$1.emit('unhandledRejection', reason, promise); - } finally { - _this._addEventListener(process$1, 'unhandledRejection', _this.unhandled); - } - } - }; - - return _this; - } - - return Runner; - }(EventEmitter$2); - /** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @private - */ - - - Runner.immediately = commonjsGlobal.setImmediate || nextTick; - /** - * Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed. - * @param {EventEmitter} target - The `EventEmitter` - * @param {string} eventName - The event name - * @param {string} fn - Listener function - * @private - */ - - Runner.prototype._addEventListener = function (target, eventName, listener) { - debug$2('_addEventListener(): adding for event %s; %d current listeners', eventName, target.listenerCount(eventName)); - /* istanbul ignore next */ - - if (this._eventListeners.has(target) && this._eventListeners.get(target).has(eventName) && this._eventListeners.get(target).get(eventName).has(listener)) { - debug$2('warning: tried to attach duplicate event listener for %s', eventName); - return; - } - - target.on(eventName, listener); - var targetListeners = this._eventListeners.has(target) ? this._eventListeners.get(target) : new Map(); - var targetEventListeners = targetListeners.has(eventName) ? targetListeners.get(eventName) : new Set(); - targetEventListeners.add(listener); - targetListeners.set(eventName, targetEventListeners); - - this._eventListeners.set(target, targetListeners); - }; - /** - * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping. - * @param {EventEmitter} target - The `EventEmitter` - * @param {string} eventName - The event name - * @param {function} listener - Listener function - * @private - */ - - - Runner.prototype._removeEventListener = function (target, eventName, listener) { - target.removeListener(eventName, listener); - - if (this._eventListeners.has(target)) { - var targetListeners = this._eventListeners.get(target); - - if (targetListeners.has(eventName)) { - var targetEventListeners = targetListeners.get(eventName); - targetEventListeners["delete"](listener); - - if (!targetEventListeners.size) { - targetListeners["delete"](eventName); - } - } - - if (!targetListeners.size) { - this._eventListeners["delete"](target); - } - } else { - debug$2('trying to remove listener for untracked object %s', target); - } - }; - /** - * Removes all event handlers set during a run on this instance. - * Remark: this does _not_ clean/dispose the tests or suites themselves. - */ - - - Runner.prototype.dispose = function () { - this.removeAllListeners(); - - this._eventListeners.forEach(function (targetListeners, target) { - targetListeners.forEach(function (targetEventListeners, eventName) { - targetEventListeners.forEach(function (listener) { - target.removeListener(eventName, listener); - }); - }); - }); - - this._eventListeners.clear(); - }; - /** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @public - * @memberof Runner - * @param {RegExp} re - * @param {boolean} invert - * @return {Runner} Runner instance. - */ - - - Runner.prototype.grep = function (re, invert) { - debug$2('grep(): setting to %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; - }; - /** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @memberof Runner - * @public - * @param {Suite} suite - * @return {number} - */ - - - Runner.prototype.grepTotal = function (suite) { - var self = this; - var total = 0; - suite.eachTest(function (test) { - var match = self._grep.test(test.fullTitle()); - - if (self._invert) { - match = !match; - } - - if (match) { - total++; - } - }); - return total; - }; - /** - * Return a list of global properties. - * - * @return {Array} - * @private - */ - - - Runner.prototype.globalProps = function () { - var props = Object.keys(commonjsGlobal); // non-enumerables - - for (var i = 0; i < globals.length; ++i) { - if (~props.indexOf(globals[i])) { - continue; - } - - props.push(globals[i]); - } - - return props; - }; - /** - * Allow the given `arr` of globals. - * - * @public - * @memberof Runner - * @param {Array} arr - * @return {Runner} Runner instance. - */ - - - Runner.prototype.globals = function (arr) { - if (!arguments.length) { - return this._globals; - } - - debug$2('globals(): setting to %O', arr); - this._globals = this._globals.concat(arr); - return this; - }; - /** - * Check for global variable leaks. - * - * @private - */ - - - Runner.prototype.checkGlobals = function (test) { - if (!this.checkLeaks) { - return; - } - - var ok = this._globals; - var globals = this.globalProps(); - var leaks; - - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } - - if (this.prevGlobalsLength === globals.length) { - return; - } - - this.prevGlobalsLength = globals.length; - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length) { - var msg = 'global leak(s) detected: %s'; - var error = new Error(util.format(msg, leaks.map(sQuote).join(', '))); - this.fail(test, error); - } - }; - /** - * Fail the given `test`. - * - * If `test` is a hook, failures work in the following pattern: - * - If bail, run corresponding `after each` and `after` hooks, - * then exit - * - Failed `before` hook skips all tests in a suite and subsuites, - * but jumps to corresponding `after` hook - * - Failed `before each` hook skips remaining tests in a - * suite and jumps to corresponding `after each` hook, - * which is run only once - * - Failed `after` hook does not alter execution order - * - Failed `after each` hook skips remaining tests in a - * suite and subsuites, but executes other `after each` - * hooks - * - * @private - * @param {Runnable} test - * @param {Error} err - * @param {boolean} [force=false] - Whether to fail a pending test. - */ - - - Runner.prototype.fail = function (test, err, force) { - force = force === true; - - if (test.isPending() && !force) { - return; - } - - if (this.state === constants$3.STATE_STOPPED) { - if (err.code === errorConstants.MULTIPLE_DONE) { - throw err; - } - - throw createFatalError$1('Test failed after root suite execution completed!', err); - } - - ++this.failures; - debug$2('total number of failures: %d', this.failures); - test.state = STATE_FAILED; - - if (!isError$1(err)) { - err = thrown2Error(err); - } - - try { - err.stack = this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack); - } catch (ignore) {// some environments do not take kindly to monkeying with the stack - } - - this.emit(constants$3.EVENT_TEST_FAIL, test, err); - }; - /** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @private - * @param {string} name - * @param {Function} fn - */ - - - Runner.prototype.hook = function (name, fn) { - var suite = this.suite; - var hooks = suite.getHooks(name); - var self = this; - - function next(i) { - var hook = hooks[i]; - - if (!hook) { - return fn(); - } - - self.currentRunnable = hook; - - if (name === HOOK_TYPE_BEFORE_ALL) { - hook.ctx.currentTest = hook.parent.tests[0]; - } else if (name === HOOK_TYPE_AFTER_ALL) { - hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1]; - } else { - hook.ctx.currentTest = self.test; - } - - setHookTitle(hook); - hook.allowUncaught = self.allowUncaught; - self.emit(constants$3.EVENT_HOOK_BEGIN, hook); - - if (!hook.listeners('error').length) { - self._addEventListener(hook, 'error', function (err) { - self.fail(hook, err); - }); - } - - hook.run(function cbHookRun(err) { - var testError = hook.error(); - - if (testError) { - self.fail(self.test, testError); - } // conditional skip - - - if (hook.pending) { - if (name === HOOK_TYPE_AFTER_EACH) { - // TODO define and implement use case - if (self.test) { - self.test.pending = true; - } - } else if (name === HOOK_TYPE_BEFORE_EACH) { - if (self.test) { - self.test.pending = true; - } - - self.emit(constants$3.EVENT_HOOK_END, hook); - hook.pending = false; // activates hook for next test - - return fn(new Error('abort hookDown')); - } else if (name === HOOK_TYPE_BEFORE_ALL) { - suite.tests.forEach(function (test) { - test.pending = true; - }); - suite.suites.forEach(function (suite) { - suite.pending = true; - }); - hooks = []; - } else { - hook.pending = false; - var errForbid = createUnsupportedError$1('`this.skip` forbidden'); - self.fail(hook, errForbid); - return fn(errForbid); - } - } else if (err) { - self.fail(hook, err); // stop executing hooks, notify callee of hook err - - return fn(err); - } - - self.emit(constants$3.EVENT_HOOK_END, hook); - delete hook.ctx.currentTest; - setHookTitle(hook); - next(++i); - }); - - function setHookTitle(hook) { - hook.originalTitle = hook.originalTitle || hook.title; - - if (hook.ctx && hook.ctx.currentTest) { - hook.title = hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title); - } else { - var parentTitle; - - if (hook.parent.title) { - parentTitle = hook.parent.title; - } else { - parentTitle = hook.parent.root ? '{root}' : ''; - } - - hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle); - } - } - } - - Runner.immediately(function () { - next(0); - }); - }; - /** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err, errSuite)`. - * - * @private - * @param {string} name - * @param {Array} suites - * @param {Function} fn - */ - - - Runner.prototype.hooks = function (name, suites, fn) { - var self = this; - var orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function (err) { - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); - }; - /** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @private - */ - - - Runner.prototype.hookUp = function (name, fn) { - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); - }; - /** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @private - */ - - - Runner.prototype.hookDown = function (name, fn) { - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); - }; - /** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @private - */ - - - Runner.prototype.parents = function () { - var suite = this.suite; - var suites = []; - - while (suite.parent) { - suite = suite.parent; - suites.push(suite); - } - - return suites; - }; - /** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @private - */ - - - Runner.prototype.runTest = function (fn) { - var self = this; - var test = this.test; - - if (!test) { - return; - } - - if (this.asyncOnly) { - test.asyncOnly = true; - } - - this._addEventListener(test, 'error', function (err) { - self.fail(test, err); - }); - - if (this.allowUncaught) { - test.allowUncaught = true; - return test.run(fn); - } - - try { - test.run(fn); - } catch (err) { - fn(err); - } - }; - /** - * Run tests in the given `suite` and invoke the callback `fn()` when complete. - * - * @private - * @param {Suite} suite - * @param {Function} fn - */ - - - Runner.prototype.runTests = function (suite, fn) { - var self = this; - var tests = suite.tests.slice(); - var test; - - function hookErr(_, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp(HOOK_TYPE_AFTER_EACH, function (err2, errSuite2) { - self.suite = orig; // some hooks may fail even now - - if (err2) { - return hookErr(err2, errSuite2, true); - } // report error suite - - - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) { - tests = []; - } - - if (self._abort) { - return fn(); - } - - if (err) { - return hookErr(err, errSuite, true); - } // next test - - - test = tests.shift(); // all done - - if (!test) { - return fn(); - } // grep - - - var match = self._grep.test(test.fullTitle()); - - if (self._invert) { - match = !match; - } - - if (!match) { - // Run immediately only if we have defined a grep. When we - // define a grep — It can cause maximum callstack error if - // the grep is doing a large recursive loop by neglecting - // all tests. The run immediately function also comes with - // a performance cost. So we don't want to run immediately - // if we run the whole test suite, because running the whole - // test suite don't do any immediate recursive loops. Thus, - // allowing a JS runtime to breathe. - if (self._grep !== self._defaultGrep) { - Runner.immediately(next); - } else { - next(); - } - - return; - } // static skip, no hooks are executed - - - if (test.isPending()) { - if (self.forbidPending) { - self.fail(test, new Error('Pending test forbidden'), true); - } else { - test.state = STATE_PENDING; - self.emit(constants$3.EVENT_TEST_PENDING, test); - } - - self.emit(constants$3.EVENT_TEST_END, test); - return next(); - } // execute test and hook(s) - - - self.emit(constants$3.EVENT_TEST_BEGIN, self.test = test); - self.hookDown(HOOK_TYPE_BEFORE_EACH, function (err, errSuite) { - // conditional skip within beforeEach - if (test.isPending()) { - if (self.forbidPending) { - self.fail(test, new Error('Pending test forbidden'), true); - } else { - test.state = STATE_PENDING; - self.emit(constants$3.EVENT_TEST_PENDING, test); - } - - self.emit(constants$3.EVENT_TEST_END, test); // skip inner afterEach hooks below errSuite level - - var origSuite = self.suite; - self.suite = errSuite || self.suite; - return self.hookUp(HOOK_TYPE_AFTER_EACH, function (e, eSuite) { - self.suite = origSuite; - next(e, eSuite); - }); - } - - if (err) { - return hookErr(err, errSuite, false); - } - - self.currentRunnable = self.test; - self.runTest(function (err) { - test = self.test; // conditional skip within it - - if (test.pending) { - if (self.forbidPending) { - self.fail(test, new Error('Pending test forbidden'), true); - } else { - test.state = STATE_PENDING; - self.emit(constants$3.EVENT_TEST_PENDING, test); - } - - self.emit(constants$3.EVENT_TEST_END, test); - return self.hookUp(HOOK_TYPE_AFTER_EACH, next); - } else if (err) { - var retry = test.currentRetry(); - - if (retry < test.retries()) { - var clonedTest = test.clone(); - clonedTest.currentRetry(retry + 1); - tests.unshift(clonedTest); - self.emit(constants$3.EVENT_TEST_RETRY, test, err); // Early return + hook trigger so that it doesn't - // increment the count wrong - - return self.hookUp(HOOK_TYPE_AFTER_EACH, next); - } else { - self.fail(test, err); - } - - self.emit(constants$3.EVENT_TEST_END, test); - return self.hookUp(HOOK_TYPE_AFTER_EACH, next); - } - - test.state = STATE_PASSED; - self.emit(constants$3.EVENT_TEST_PASS, test); - self.emit(constants$3.EVENT_TEST_END, test); - self.hookUp(HOOK_TYPE_AFTER_EACH, next); - }); - }); - } - - this.next = next; - this.hookErr = hookErr; - next(); - }; - /** - * Run the given `suite` and invoke the callback `fn()` when complete. - * - * @private - * @param {Suite} suite - * @param {Function} fn - */ - - - Runner.prototype.runSuite = function (suite, fn) { - var i = 0; - var self = this; - var total = this.grepTotal(suite); - debug$2('runSuite(): running %s', suite.fullTitle()); - - if (!total || self.failures && suite._bail) { - debug$2('runSuite(): bailing'); - return fn(); - } - - this.emit(constants$3.EVENT_SUITE_BEGIN, this.suite = suite); - - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite === suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - - - return done(errSuite); - } - - if (self._abort) { - return done(); - } - - var curr = suite.suites[i++]; - - if (!curr) { - return done(); - } // Avoid grep neglecting large number of tests causing a - // huge recursive loop and thus a maximum call stack error. - // See comment in `this.runTests()` for more information. - - - if (self._grep !== self._defaultGrep) { - Runner.immediately(function () { - self.runSuite(curr, next); - }); - } else { - self.runSuite(curr, next); - } - } - - function done(errSuite) { - self.suite = suite; - self.nextSuite = next; // remove reference to test - - delete self.test; - self.hook(HOOK_TYPE_AFTER_ALL, function () { - self.emit(constants$3.EVENT_SUITE_END, suite); - fn(errSuite); - }); - } - - this.nextSuite = next; - this.hook(HOOK_TYPE_BEFORE_ALL, function (err) { - if (err) { - return done(); - } - - self.runTests(suite, next); - }); - }; - /** - * Handle uncaught exceptions within runner. - * - * This function is bound to the instance as `Runner#uncaught` at instantiation - * time. It's intended to be listening on the `Process.uncaughtException` event. - * In order to not leak EE listeners, we need to ensure no more than a single - * `uncaughtException` listener exists per `Runner`. The only way to do - * this--because this function needs the context (and we don't have lambdas)--is - * to use `Function.prototype.bind`. We need strict equality to unregister and - * _only_ unregister the _one_ listener we set from the - * `Process.uncaughtException` event; would be poor form to just remove - * everything. See {@link Runner#run} for where the event listener is registered - * and unregistered. - * @param {Error} err - Some uncaught error - * @private - */ - - - Runner.prototype._uncaught = function (err) { - // this is defensive to prevent future developers from mis-calling this function. - // it's more likely that it'd be called with the incorrect context--say, the global - // `process` object--than it would to be called with a context that is not a "subclass" - // of `Runner`. - if (!(this instanceof Runner)) { - throw createFatalError$1('Runner#uncaught() called with invalid context', this); - } - - if (err instanceof pending) { - debug$2('uncaught(): caught a Pending'); - return; - } // browser does not exit script when throwing in global.onerror() - - - if (this.allowUncaught && !utils.isBrowser()) { - debug$2('uncaught(): bubbling exception due to --allow-uncaught'); - throw err; - } - - if (this.state === constants$3.STATE_STOPPED) { - debug$2('uncaught(): throwing after run has completed!'); - throw err; - } - - if (err) { - debug$2('uncaught(): got truthy exception %O', err); - } else { - debug$2('uncaught(): undefined/falsy exception'); - err = createInvalidExceptionError$2('Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger', err); - } - - if (!isError$1(err)) { - err = thrown2Error(err); - debug$2('uncaught(): converted "error" %o to Error', err); - } - - err.uncaught = true; - var runnable$1 = this.currentRunnable; - - if (!runnable$1) { - runnable$1 = new runnable('Uncaught error outside test suite'); - debug$2('uncaught(): no current Runnable; created a phony one'); - runnable$1.parent = this.suite; - - if (this.state === constants$3.STATE_RUNNING) { - debug$2('uncaught(): failing gracefully'); - this.fail(runnable$1, err); - } else { - // Can't recover from this failure - debug$2('uncaught(): test run has not yet started; unrecoverable'); - this.emit(constants$3.EVENT_RUN_BEGIN); - this.fail(runnable$1, err); - this.emit(constants$3.EVENT_RUN_END); - } - - return; - } - - runnable$1.clearTimeout(); - - if (runnable$1.isFailed()) { - debug$2('uncaught(): Runnable has already failed'); // Ignore error if already failed - - return; - } else if (runnable$1.isPending()) { - debug$2('uncaught(): pending Runnable wound up failing!'); // report 'pending test' retrospectively as failed - - this.fail(runnable$1, err, true); - return; - } // we cannot recover gracefully if a Runnable has already passed - // then fails asynchronously - - - if (runnable$1.isPassed()) { - debug$2('uncaught(): Runnable has already passed; bailing gracefully'); - this.fail(runnable$1, err); - this.abort(); - } else { - debug$2('uncaught(): forcing Runnable to complete with Error'); - return runnable$1.callback(err); - } - }; - /** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @public - * @memberof Runner - * @param {Function} fn - Callback when finished - * @param {{files: string[], options: Options}} [opts] - For subclasses - * @returns {Runner} Runner instance. - */ - - - Runner.prototype.run = function (fn) { - var _this2 = this; - - var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - var rootSuite = this.suite; - var options = opts.options || {}; - debug$2('run(): got options: %O', options); - - fn = fn || function () {}; - - var end = function end() { - debug$2('run(): root suite completed; emitting %s', constants$3.EVENT_RUN_END); - - _this2.emit(constants$3.EVENT_RUN_END); - }; - - var begin = function begin() { - debug$2('run(): emitting %s', constants$3.EVENT_RUN_BEGIN); - - _this2.emit(constants$3.EVENT_RUN_BEGIN); - - debug$2('run(): emitted %s', constants$3.EVENT_RUN_BEGIN); - - _this2.runSuite(rootSuite, end); - }; - - var prepare = function prepare() { - debug$2('run(): starting'); // If there is an `only` filter - - if (rootSuite.hasOnly()) { - rootSuite.filterOnly(); - debug$2('run(): filtered exclusive Runnables'); - } - - _this2.state = constants$3.STATE_RUNNING; - - if (_this2._delay) { - _this2.emit(constants$3.EVENT_DELAY_END); - - debug$2('run(): "delay" ended'); - } - - return begin(); - }; // references cleanup to avoid memory leaks - - - if (this._opts.cleanReferencesAfterRun) { - this.on(constants$3.EVENT_SUITE_END, function (suite) { - suite.cleanReferences(); - }); - } // callback - - - this.on(constants$3.EVENT_RUN_END, function () { - this.state = constants$3.STATE_STOPPED; - debug$2('run(): emitted %s', constants$3.EVENT_RUN_END); - fn(this.failures); - }); - - this._removeEventListener(process$1, 'uncaughtException', this.uncaught); - - this._removeEventListener(process$1, 'unhandledRejection', this.unhandled); - - this._addEventListener(process$1, 'uncaughtException', this.uncaught); - - this._addEventListener(process$1, 'unhandledRejection', this.unhandled); - - if (this._delay) { - // for reporters, I guess. - // might be nice to debounce some dots while we wait. - this.emit(constants$3.EVENT_DELAY_BEGIN, rootSuite); - rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare); - debug$2('run(): waiting for green light due to --delay'); - } else { - Runner.immediately(prepare); - } - - return this; - }; - /** - * Toggle partial object linking behavior; used for building object references from - * unique ID's. Does nothing in serial mode, because the object references already exist. - * Subclasses can implement this (e.g., `ParallelBufferedRunner`) - * @abstract - * @param {boolean} [value] - If `true`, enable partial object linking, otherwise disable - * @returns {Runner} - * @chainable - * @public - * @example - * // this reporter needs proper object references when run in parallel mode - * class MyReporter() { - * constructor(runner) { - * this.runner.linkPartialObjects(true) - * .on(EVENT_SUITE_BEGIN, suite => { - // this Suite may be the same object... - * }) - * .on(EVENT_TEST_BEGIN, test => { - * // ...as the `test.parent` property - * }); - * } - * } - */ - - - Runner.prototype.linkPartialObjects = function (value) { - return this; - }; - /* - * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`. - * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead. - * @public - * @memberof Runner - * @param {Object} [opts] - Options for {@link Runner#run} - * @returns {Promise} Failure count - */ - - - Runner.prototype.runAsync = /*#__PURE__*/function () { - var _runAsync = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { - var _this3 = this; - - var opts, - _args = arguments; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - opts = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}; - return _context.abrupt("return", new Promise(function (resolve) { - _this3.run(resolve, opts); - })); - - case 2: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - function runAsync() { - return _runAsync.apply(this, arguments); - } - - return runAsync; - }(); - /** - * Cleanly abort execution. - * - * @memberof Runner - * @public - * @return {Runner} Runner instance. - */ - - - Runner.prototype.abort = function () { - debug$2('abort(): aborting'); - this._abort = true; - return this; - }; - /** - * Returns `true` if Mocha is running in parallel mode. For reporters. - * - * Subclasses should return an appropriate value. - * @public - * @returns {false} - */ - - - Runner.prototype.isParallelMode = function isParallelMode() { - return false; - }; - /** - * Configures an alternate reporter for worker processes to use. Subclasses - * using worker processes should implement this. - * @public - * @param {string} path - Absolute path to alternate reporter for worker processes to use - * @returns {Runner} - * @throws When in serial mode - * @chainable - * @abstract - */ - - - Runner.prototype.workerReporter = function () { - throw createUnsupportedError$1('workerReporter() not supported in serial mode'); - }; - /** - * Filter leaks with the given globals flagged as `ok`. - * - * @private - * @param {Array} ok - * @param {Array} globals - * @return {Array} - */ - - - function filterLeaks(ok, globals) { - return globals.filter(function (key) { - // Firefox and Chrome exposes iframes as index inside the window object - if (/^\d+/.test(key)) { - return false; - } // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method - // not init at first it is assigned in some seconds - - - if (commonjsGlobal.navigator && /^getInterface/.test(key)) { - return false; - } // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - - - if (commonjsGlobal.navigator && /^\d+/.test(key)) { - return false; - } // Opera and IE expose global variables for HTML element IDs (issue #243) - - - if (/^mocha-/.test(key)) { - return false; - } - - var matched = ok.filter(function (ok) { - if (~ok.indexOf('*')) { - return key.indexOf(ok.split('*')[0]) === 0; - } - - return key === ok; - }); - return !matched.length && (!commonjsGlobal.navigator || key !== 'onerror'); - }); - } - /** - * Check if argument is an instance of Error object or a duck-typed equivalent. - * - * @private - * @param {Object} err - object to check - * @param {string} err.message - error message - * @returns {boolean} - */ - - - function isError$1(err) { - return err instanceof Error || err && typeof err.message === 'string'; - } - /** - * - * Converts thrown non-extensible type into proper Error. - * - * @private - * @param {*} thrown - Non-extensible type thrown by code - * @return {Error} - */ - - - function thrown2Error(err) { - return new Error("the ".concat(utils.canonicalType(err), " ").concat(stringify(err), " was thrown, throw an Error :)")); - } - - Runner.constants = constants$3; - /** - * Node.js' `EventEmitter` - * @external EventEmitter - * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter} - */ - - var runner$1 = Runner; - - var base = createCommonjsModule(function (module, exports) { - /** - * @module Base - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var isBrowser = utils.isBrowser(); - - function getBrowserWindowSize() { - if ('innerHeight' in commonjsGlobal) { - return [commonjsGlobal.innerHeight, commonjsGlobal.innerWidth]; - } // In a Web Worker, the DOM Window is not available. - - - return [640, 480]; - } - /** - * Expose `Base`. - */ - - - exports = module.exports = Base; - /** - * Check if both stdio streams are associated with a tty. - */ - - var isatty = isBrowser || process$1.stdout.isTTY && process$1.stderr.isTTY; - /** - * Save log references to avoid tests interfering (see GH-3604). - */ - - var consoleLog = console.log; - /** - * Enable coloring by default, except in the browser interface. - */ - - exports.useColors = !isBrowser && (require$$11.stdout || process$1.env.MOCHA_COLORS !== undefined); - /** - * Inline diffs instead of +/- - */ - - exports.inlineDiffs = false; - /** - * Default color map. - */ - - exports.colors = { - pass: 90, - fail: 31, - 'bright pass': 92, - 'bright fail': 91, - 'bright yellow': 93, - pending: 36, - suite: 0, - 'error title': 0, - 'error message': 31, - 'error stack': 90, - checkmark: 32, - fast: 90, - medium: 33, - slow: 31, - green: 32, - light: 90, - 'diff gutter': 90, - 'diff added': 32, - 'diff removed': 31, - 'diff added inline': '30;42', - 'diff removed inline': '30;41' - }; - /** - * Default symbol map. - */ - - exports.symbols = { - ok: '✓', - err: '✖', - dot: '․', - comma: ',', - bang: '!' - }; // With node.js on Windows: use symbols available in terminal default fonts - - if (process$1.platform === 'win32') { - exports.symbols.ok = "\u221A"; - exports.symbols.err = "\xD7"; - exports.symbols.dot = '.'; - } - /** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @private - * @param {string} type - * @param {string} str - * @return {string} - */ - - - var color = exports.color = function (type, str) { - if (!exports.useColors) { - return String(str); - } - - return "\x1B[" + exports.colors[type] + 'm' + str + "\x1B[0m"; - }; - /** - * Expose term window size, with some defaults for when stderr is not a tty. - */ - - - exports.window = { - width: 75 - }; - - if (isatty) { - if (isBrowser) { - exports.window.width = getBrowserWindowSize()[1]; - } else { - exports.window.width = process$1.stdout.getWindowSize(1)[0]; - } - } - /** - * Expose some basic cursor interactions that are common among reporters. - */ - - - exports.cursor = { - hide: function hide() { - isatty && process$1.stdout.write("\x1B[?25l"); - }, - show: function show() { - isatty && process$1.stdout.write("\x1B[?25h"); - }, - deleteLine: function deleteLine() { - isatty && process$1.stdout.write("\x1B[2K"); - }, - beginningOfLine: function beginningOfLine() { - isatty && process$1.stdout.write("\x1B[0G"); - }, - CR: function CR() { - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process$1.stdout.write('\r'); - } - } - }; - - var showDiff = exports.showDiff = function (err) { - return err && err.showDiff !== false && sameType(err.actual, err.expected) && err.expected !== undefined; - }; - - function stringifyDiffObjs(err) { - if (!utils.isString(err.actual) || !utils.isString(err.expected)) { - err.actual = utils.stringify(err.actual); - err.expected = utils.stringify(err.expected); - } - } - /** - * Returns a diff between 2 strings with coloured ANSI output. - * - * @description - * The diff will be either inline or unified dependent on the value - * of `Base.inlineDiff`. - * - * @param {string} actual - * @param {string} expected - * @return {string} Diff - */ - - - var generateDiff = exports.generateDiff = function (actual, expected) { - try { - return exports.inlineDiffs ? inlineDiff(actual, expected) : unifiedDiff(actual, expected); - } catch (err) { - var msg = '\n ' + color('diff added', '+ expected') + ' ' + color('diff removed', '- actual: failed to generate Mocha diff') + '\n'; - return msg; - } - }; - /** - * Outputs the given `failures` as a list. - * - * @public - * @memberof Mocha.reporters.Base - * @variation 1 - * @param {Object[]} failures - Each is Test instance with corresponding - * Error property - */ - - - exports.list = function (failures) { - var multipleErr, multipleTest; - Base.consoleLog(); - failures.forEach(function (test, i) { - // format - var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg - - var msg; - var err; - - if (test.err && test.err.multiple) { - if (multipleTest !== test) { - multipleTest = test; - multipleErr = [test.err].concat(test.err.multiple); - } - - err = multipleErr.shift(); - } else { - err = test.err; - } - - var message; - - if (err.message && typeof err.message.toString === 'function') { - message = err.message + ''; - } else if (typeof err.inspect === 'function') { - message = err.inspect() + ''; - } else { - message = ''; - } - - var stack = err.stack || message; - var index = message ? stack.indexOf(message) : -1; - - if (index === -1) { - msg = message; - } else { - index += message.length; - msg = stack.slice(0, index); // remove msg from stack - - stack = stack.slice(index + 1); - } // uncaught - - - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } // explicitly show diff - - - if (!exports.hideDiff && showDiff(err)) { - stringifyDiffObjs(err); - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - msg += generateDiff(err.actual, err.expected); - } // indent stack trace - - - stack = stack.replace(/^/gm, ' '); // indented test title - - var testTitle = ''; - test.titlePath().forEach(function (str, index) { - if (index !== 0) { - testTitle += '\n '; - } - - for (var i = 0; i < index; i++) { - testTitle += ' '; - } - - testTitle += str; - }); - Base.consoleLog(fmt, i + 1, testTitle, msg, stack); - }); - }; - /** - * Constructs a new `Base` reporter instance. - * - * @description - * All other reporters generally inherit from this reporter. - * - * @public - * @class - * @memberof Mocha.reporters - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - - function Base(runner, options) { - var failures = this.failures = []; - - if (!runner) { - throw new TypeError('Missing runner argument'); - } - - this.options = options || {}; - this.runner = runner; - this.stats = runner.stats; // assigned so Reporters keep a closer reference - - runner.on(EVENT_TEST_PASS, function (test) { - if (test.duration > test.slow()) { - test.speed = 'slow'; - } else if (test.duration > test.slow() / 2) { - test.speed = 'medium'; - } else { - test.speed = 'fast'; - } - }); - runner.on(EVENT_TEST_FAIL, function (test, err) { - if (showDiff(err)) { - stringifyDiffObjs(err); - } // more than one error per test - - - if (test.err && err instanceof Error) { - test.err.multiple = (test.err.multiple || []).concat(err); - } else { - test.err = err; - } - - failures.push(test); - }); - } - /** - * Outputs common epilogue used by many of the bundled reporters. - * - * @public - * @memberof Mocha.reporters - */ - - - Base.prototype.epilogue = function () { - var stats = this.stats; - var fmt; - Base.consoleLog(); // passes - - fmt = color('bright pass', ' ') + color('green', ' %d passing') + color('light', ' (%s)'); - Base.consoleLog(fmt, stats.passes || 0, ms(stats.duration)); // pending - - if (stats.pending) { - fmt = color('pending', ' ') + color('pending', ' %d pending'); - Base.consoleLog(fmt, stats.pending); - } // failures - - - if (stats.failures) { - fmt = color('fail', ' %d failing'); - Base.consoleLog(fmt, stats.failures); - Base.list(this.failures); - Base.consoleLog(); - } - - Base.consoleLog(); - }; - /** - * Pads the given `str` to `len`. - * - * @private - * @param {string} str - * @param {string} len - * @return {string} - */ - - - function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; - } - /** - * Returns inline diff between 2 strings with coloured ANSI output. - * - * @private - * @param {String} actual - * @param {String} expected - * @return {string} Diff - */ - - - function inlineDiff(actual, expected) { - var msg = errorDiff(actual, expected); // linenos - - var lines = msg.split('\n'); - - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function (str, i) { - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } // legend - - - msg = '\n' + color('diff removed inline', 'actual') + ' ' + color('diff added inline', 'expected') + '\n\n' + msg + '\n'; // indent - - msg = msg.replace(/^/gm, ' '); - return msg; - } - /** - * Returns unified diff between two strings with coloured ANSI output. - * - * @private - * @param {String} actual - * @param {String} expected - * @return {string} The diff. - */ - - - function unifiedDiff(actual, expected) { - var indent = ' '; - - function cleanUp(line) { - if (line[0] === '+') { - return indent + colorLines('diff added', line); - } - - if (line[0] === '-') { - return indent + colorLines('diff removed', line); - } - - if (line.match(/@@/)) { - return '--'; - } - - if (line.match(/\\ No newline/)) { - return null; - } - - return indent + line; - } - - function notBlank(line) { - return typeof line !== 'undefined' && line !== null; - } - - var msg = diff.createPatch('string', actual, expected); - var lines = msg.split('\n').splice(5); - return '\n ' + colorLines('diff added', '+ expected') + ' ' + colorLines('diff removed', '- actual') + '\n\n' + lines.map(cleanUp).filter(notBlank).join('\n'); - } - /** - * Returns character diff for `err`. - * - * @private - * @param {String} actual - * @param {String} expected - * @return {string} the diff - */ - - - function errorDiff(actual, expected) { - return diff.diffWordsWithSpace(actual, expected).map(function (str) { - if (str.added) { - return colorLines('diff added inline', str.value); - } - - if (str.removed) { - return colorLines('diff removed inline', str.value); - } - - return str.value; - }).join(''); - } - /** - * Colors lines for `str`, using the color `name`. - * - * @private - * @param {string} name - * @param {string} str - * @return {string} - */ - - - function colorLines(name, str) { - return str.split('\n').map(function (str) { - return color(name, str); - }).join('\n'); - } - /** - * Object#toString reference. - */ - - - var objToString = Object.prototype.toString; - /** - * Checks that a / b have the same type. - * - * @private - * @param {Object} a - * @param {Object} b - * @return {boolean} - */ - - function sameType(a, b) { - return objToString.call(a) === objToString.call(b); - } - - Base.consoleLog = consoleLog; - Base["abstract"] = true; - }); - - var dot = createCommonjsModule(function (module, exports) { - /** - * @module Dot - */ - - /** - * Module dependencies. - */ - - var inherits = utils.inherits; - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var EVENT_RUN_END = constants.EVENT_RUN_END; - /** - * Expose `Dot`. - */ - - module.exports = Dot; - /** - * Constructs a new `Dot` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Dot(runner, options) { - base.call(this, runner, options); - var self = this; - var width = base.window.width * 0.75 | 0; - var n = -1; - runner.on(EVENT_RUN_BEGIN, function () { - process$1.stdout.write('\n'); - }); - runner.on(EVENT_TEST_PENDING, function () { - if (++n % width === 0) { - process$1.stdout.write('\n '); - } - - process$1.stdout.write(base.color('pending', base.symbols.comma)); - }); - runner.on(EVENT_TEST_PASS, function (test) { - if (++n % width === 0) { - process$1.stdout.write('\n '); - } - - if (test.speed === 'slow') { - process$1.stdout.write(base.color('bright yellow', base.symbols.dot)); - } else { - process$1.stdout.write(base.color(test.speed, base.symbols.dot)); - } - }); - runner.on(EVENT_TEST_FAIL, function () { - if (++n % width === 0) { - process$1.stdout.write('\n '); - } - - process$1.stdout.write(base.color('fail', base.symbols.bang)); - }); - runner.once(EVENT_RUN_END, function () { - process$1.stdout.write('\n'); - self.epilogue(); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(Dot, base); - Dot.description = 'dot matrix representation'; - }); - - var doc = createCommonjsModule(function (module, exports) { - /** - * @module Doc - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; - var EVENT_SUITE_END = constants.EVENT_SUITE_END; - /** - * Expose `Doc`. - */ - - module.exports = Doc; - /** - * Constructs a new `Doc` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Doc(runner, options) { - base.call(this, runner, options); - var indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on(EVENT_SUITE_BEGIN, function (suite) { - if (suite.root) { - return; - } - - ++indents; - base.consoleLog('%s
    ', indent()); - ++indents; - base.consoleLog('%s

    %s

    ', indent(), utils.escape(suite.title)); - base.consoleLog('%s
    ', indent()); - }); - runner.on(EVENT_SUITE_END, function (suite) { - if (suite.root) { - return; - } - - base.consoleLog('%s
    ', indent()); - --indents; - base.consoleLog('%s
    ', indent()); - --indents; - }); - runner.on(EVENT_TEST_PASS, function (test) { - base.consoleLog('%s
    %s
    ', indent(), utils.escape(test.title)); - base.consoleLog('%s
    %s
    ', indent(), utils.escape(test.file)); - var code = utils.escape(utils.clean(test.body)); - base.consoleLog('%s
    %s
    ', indent(), code); - }); - runner.on(EVENT_TEST_FAIL, function (test, err) { - base.consoleLog('%s
    %s
    ', indent(), utils.escape(test.title)); - base.consoleLog('%s
    %s
    ', indent(), utils.escape(test.file)); - var code = utils.escape(utils.clean(test.body)); - base.consoleLog('%s
    %s
    ', indent(), code); - base.consoleLog('%s
    %s
    ', indent(), utils.escape(err)); - }); - } - - Doc.description = 'HTML documentation'; - }); - - var tap = createCommonjsModule(function (module, exports) { - /** - * @module TAP - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var EVENT_TEST_END = constants.EVENT_TEST_END; - var inherits = utils.inherits; - var sprintf = util.format; - /** - * Expose `TAP`. - */ - - module.exports = TAP; - /** - * Constructs a new `TAP` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function TAP(runner, options) { - base.call(this, runner, options); - var self = this; - var n = 1; - var tapVersion = '12'; - - if (options && options.reporterOptions) { - if (options.reporterOptions.tapVersion) { - tapVersion = options.reporterOptions.tapVersion.toString(); - } - } - - this._producer = createProducer(tapVersion); - runner.once(EVENT_RUN_BEGIN, function () { - self._producer.writeVersion(); - }); - runner.on(EVENT_TEST_END, function () { - ++n; - }); - runner.on(EVENT_TEST_PENDING, function (test) { - self._producer.writePending(n, test); - }); - runner.on(EVENT_TEST_PASS, function (test) { - self._producer.writePass(n, test); - }); - runner.on(EVENT_TEST_FAIL, function (test, err) { - self._producer.writeFail(n, test, err); - }); - runner.once(EVENT_RUN_END, function () { - self._producer.writeEpilogue(runner.stats); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(TAP, base); - /** - * Returns a TAP-safe title of `test`. - * - * @private - * @param {Test} test - Test instance. - * @return {String} title with any hash character removed - */ - - function title(test) { - return test.fullTitle().replace(/#/g, ''); - } - /** - * Writes newline-terminated formatted string to reporter output stream. - * - * @private - * @param {string} format - `printf`-like format string - * @param {...*} [varArgs] - Format string arguments - */ - - - function println(format, varArgs) { - var vargs = Array.from(arguments); - vargs[0] += '\n'; - process$1.stdout.write(sprintf.apply(null, vargs)); - } - /** - * Returns a `tapVersion`-appropriate TAP producer instance, if possible. - * - * @private - * @param {string} tapVersion - Version of TAP specification to produce. - * @returns {TAPProducer} specification-appropriate instance - * @throws {Error} if specification version has no associated producer. - */ - - - function createProducer(tapVersion) { - var producers = { - '12': new TAP12Producer(), - '13': new TAP13Producer() - }; - var producer = producers[tapVersion]; - - if (!producer) { - throw new Error('invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)); - } - - return producer; - } - /** - * @summary - * Constructs a new TAPProducer. - * - * @description - * Only to be used as an abstract base class. - * - * @private - * @constructor - */ - - - function TAPProducer() {} - /** - * Writes the TAP version to reporter output stream. - * - * @abstract - */ - - - TAPProducer.prototype.writeVersion = function () {}; - /** - * Writes the plan to reporter output stream. - * - * @abstract - * @param {number} ntests - Number of tests that are planned to run. - */ - - - TAPProducer.prototype.writePlan = function (ntests) { - println('%d..%d', 1, ntests); - }; - /** - * Writes that test passed to reporter output stream. - * - * @abstract - * @param {number} n - Index of test that passed. - * @param {Test} test - Instance containing test information. - */ - - - TAPProducer.prototype.writePass = function (n, test) { - println('ok %d %s', n, title(test)); - }; - /** - * Writes that test was skipped to reporter output stream. - * - * @abstract - * @param {number} n - Index of test that was skipped. - * @param {Test} test - Instance containing test information. - */ - - - TAPProducer.prototype.writePending = function (n, test) { - println('ok %d %s # SKIP -', n, title(test)); - }; - /** - * Writes that test failed to reporter output stream. - * - * @abstract - * @param {number} n - Index of test that failed. - * @param {Test} test - Instance containing test information. - * @param {Error} err - Reason the test failed. - */ - - - TAPProducer.prototype.writeFail = function (n, test, err) { - println('not ok %d %s', n, title(test)); - }; - /** - * Writes the summary epilogue to reporter output stream. - * - * @abstract - * @param {Object} stats - Object containing run statistics. - */ - - - TAPProducer.prototype.writeEpilogue = function (stats) { - // :TBD: Why is this not counting pending tests? - println('# tests ' + (stats.passes + stats.failures)); - println('# pass ' + stats.passes); // :TBD: Why are we not showing pending results? - - println('# fail ' + stats.failures); - this.writePlan(stats.passes + stats.failures + stats.pending); - }; - /** - * @summary - * Constructs a new TAP12Producer. - * - * @description - * Produces output conforming to the TAP12 specification. - * - * @private - * @constructor - * @extends TAPProducer - * @see {@link https://testanything.org/tap-specification.html|Specification} - */ - - - function TAP12Producer() { - /** - * Writes that test failed to reporter output stream, with error formatting. - * @override - */ - this.writeFail = function (n, test, err) { - TAPProducer.prototype.writeFail.call(this, n, test, err); - - if (err.message) { - println(err.message.replace(/^/gm, ' ')); - } - - if (err.stack) { - println(err.stack.replace(/^/gm, ' ')); - } - }; - } - /** - * Inherit from `TAPProducer.prototype`. - */ - - - inherits(TAP12Producer, TAPProducer); - /** - * @summary - * Constructs a new TAP13Producer. - * - * @description - * Produces output conforming to the TAP13 specification. - * - * @private - * @constructor - * @extends TAPProducer - * @see {@link https://testanything.org/tap-version-13-specification.html|Specification} - */ - - function TAP13Producer() { - /** - * Writes the TAP version to reporter output stream. - * @override - */ - this.writeVersion = function () { - println('TAP version 13'); - }; - /** - * Writes that test failed to reporter output stream, with error formatting. - * @override - */ - - - this.writeFail = function (n, test, err) { - TAPProducer.prototype.writeFail.call(this, n, test, err); - var emitYamlBlock = err.message != null || err.stack != null; - - if (emitYamlBlock) { - println(indent(1) + '---'); - - if (err.message) { - println(indent(2) + 'message: |-'); - println(err.message.replace(/^/gm, indent(3))); - } - - if (err.stack) { - println(indent(2) + 'stack: |-'); - println(err.stack.replace(/^/gm, indent(3))); - } - - println(indent(1) + '...'); - } - }; - - function indent(level) { - return Array(level + 1).join(' '); - } - } - /** - * Inherit from `TAPProducer.prototype`. - */ - - - inherits(TAP13Producer, TAPProducer); - TAP.description = 'TAP-compatible output'; - }); - - var json = createCommonjsModule(function (module, exports) { - /** - * @module JSON - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_TEST_END = constants.EVENT_TEST_END; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - /** - * Expose `JSON`. - */ - - module.exports = JSONReporter; - /** - * Constructs a new `JSON` reporter instance. - * - * @public - * @class JSON - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function JSONReporter(runner, options) { - base.call(this, runner, options); - var self = this; - var tests = []; - var pending = []; - var failures = []; - var passes = []; - runner.on(EVENT_TEST_END, function (test) { - tests.push(test); - }); - runner.on(EVENT_TEST_PASS, function (test) { - passes.push(test); - }); - runner.on(EVENT_TEST_FAIL, function (test) { - failures.push(test); - }); - runner.on(EVENT_TEST_PENDING, function (test) { - pending.push(test); - }); - runner.once(EVENT_RUN_END, function () { - var obj = { - stats: self.stats, - tests: tests.map(clean), - pending: pending.map(clean), - failures: failures.map(clean), - passes: passes.map(clean) - }; - runner.testResults = obj; - process$1.stdout.write(JSON.stringify(obj, null, 2)); - }); - } - /** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @private - * @param {Object} test - * @return {Object} - */ - - - function clean(test) { - var err = test.err || {}; - - if (err instanceof Error) { - err = errorJSON(err); - } - - return { - title: test.title, - fullTitle: test.fullTitle(), - file: test.file, - duration: test.duration, - currentRetry: test.currentRetry(), - speed: test.speed, - err: cleanCycles(err) - }; - } - /** - * Replaces any circular references inside `obj` with '[object Object]' - * - * @private - * @param {Object} obj - * @return {Object} - */ - - - function cleanCycles(obj) { - var cache = []; - return JSON.parse(JSON.stringify(obj, function (key, value) { - if (_typeof(value) === 'object' && value !== null) { - if (cache.indexOf(value) !== -1) { - // Instead of going in a circle, we'll print [object Object] - return '' + value; - } - - cache.push(value); - } - - return value; - })); - } - /** - * Transform an Error object into a JSON object. - * - * @private - * @param {Error} err - * @return {Object} - */ - - - function errorJSON(err) { - var res = {}; - Object.getOwnPropertyNames(err).forEach(function (key) { - res[key] = err[key]; - }, err); - return res; - } - - JSONReporter.description = 'single JSON object'; - }); - - // `thisNumberValue` abstract operation - // https://tc39.es/ecma262/#sec-thisnumbervalue - var thisNumberValue = function (value) { - if (typeof value != 'number' && classofRaw(value) != 'Number') { - throw TypeError('Incorrect invocation'); - } - return +value; - }; - - // `String.prototype.repeat` method implementation - // https://tc39.es/ecma262/#sec-string.prototype.repeat - var stringRepeat = ''.repeat || function repeat(count) { - var str = String(requireObjectCoercible(this)); - var result = ''; - var n = toInteger(count); - if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions'); - for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str; - return result; - }; - - var nativeToFixed = 1.0.toFixed; - var floor$4 = Math.floor; - - var pow$1 = function (x, n, acc) { - return n === 0 ? acc : n % 2 === 1 ? pow$1(x, n - 1, acc * x) : pow$1(x * x, n / 2, acc); - }; - - var log$2 = function (x) { - var n = 0; - var x2 = x; - while (x2 >= 4096) { - n += 12; - x2 /= 4096; - } - while (x2 >= 2) { - n += 1; - x2 /= 2; - } return n; - }; - - var FORCED$8 = nativeToFixed && ( - 0.00008.toFixed(3) !== '0.000' || - 0.9.toFixed(0) !== '1' || - 1.255.toFixed(2) !== '1.25' || - 1000000000000000128.0.toFixed(0) !== '1000000000000000128' - ) || !fails(function () { - // V8 ~ Android 4.3- - nativeToFixed.call({}); - }); - - // `Number.prototype.toFixed` method - // https://tc39.es/ecma262/#sec-number.prototype.tofixed - _export({ target: 'Number', proto: true, forced: FORCED$8 }, { - // eslint-disable-next-line max-statements - toFixed: function toFixed(fractionDigits) { - var number = thisNumberValue(this); - var fractDigits = toInteger(fractionDigits); - var data = [0, 0, 0, 0, 0, 0]; - var sign = ''; - var result = '0'; - var e, z, j, k; - - var multiply = function (n, c) { - var index = -1; - var c2 = c; - while (++index < 6) { - c2 += n * data[index]; - data[index] = c2 % 1e7; - c2 = floor$4(c2 / 1e7); - } - }; - - var divide = function (n) { - var index = 6; - var c = 0; - while (--index >= 0) { - c += data[index]; - data[index] = floor$4(c / n); - c = (c % n) * 1e7; - } - }; - - var dataToString = function () { - var index = 6; - var s = ''; - while (--index >= 0) { - if (s !== '' || index === 0 || data[index] !== 0) { - var t = String(data[index]); - s = s === '' ? t : s + stringRepeat.call('0', 7 - t.length) + t; - } - } return s; - }; - - if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits'); - // eslint-disable-next-line no-self-compare - if (number != number) return 'NaN'; - if (number <= -1e21 || number >= 1e21) return String(number); - if (number < 0) { - sign = '-'; - number = -number; - } - if (number > 1e-21) { - e = log$2(number * pow$1(2, 69, 1)) - 69; - z = e < 0 ? number * pow$1(2, -e, 1) : number / pow$1(2, e, 1); - z *= 0x10000000000000; - e = 52 - e; - if (e > 0) { - multiply(0, z); - j = fractDigits; - while (j >= 7) { - multiply(1e7, 0); - j -= 7; - } - multiply(pow$1(10, j, 1), 0); - j = e - 1; - while (j >= 23) { - divide(1 << 23); - j -= 23; - } - divide(1 << j); - multiply(1, 1); - divide(2); - result = dataToString(); - } else { - multiply(0, z); - multiply(1 << -e, 0); - result = dataToString() + stringRepeat.call('0', fractDigits); - } - } - if (fractDigits > 0) { - k = result.length; - result = sign + (k <= fractDigits - ? '0.' + stringRepeat.call('0', fractDigits - k) + result - : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits)); - } else { - result = sign + result; - } return result; - } - }); - - /** - @module browser/Progress - */ - - /** - * Expose `Progress`. - */ - - var progress = Progress; - /** - * Initialize a new `Progress` indicator. - */ - - function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); - } - /** - * Set progress size to `size`. - * - * @public - * @param {number} size - * @return {Progress} Progress instance. - */ - - - Progress.prototype.size = function (size) { - this._size = size; - return this; - }; - /** - * Set text to `text`. - * - * @public - * @param {string} text - * @return {Progress} Progress instance. - */ - - - Progress.prototype.text = function (text) { - this._text = text; - return this; - }; - /** - * Set font size to `size`. - * - * @public - * @param {number} size - * @return {Progress} Progress instance. - */ - - - Progress.prototype.fontSize = function (size) { - this._fontSize = size; - return this; - }; - /** - * Set font to `family`. - * - * @param {string} family - * @return {Progress} Progress instance. - */ - - - Progress.prototype.font = function (family) { - this._font = family; - return this; - }; - /** - * Update percentage to `n`. - * - * @param {number} n - * @return {Progress} Progress instance. - */ - - - Progress.prototype.update = function (n) { - this.percent = n; - return this; - }; - /** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} Progress instance. - */ - - - Progress.prototype.draw = function (ctx) { - try { - var percent = Math.min(this.percent, 100); - var size = this._size; - var half = size / 2; - var x = half; - var y = half; - var rad = half - 1; - var fontSize = this._fontSize; - ctx.font = fontSize + 'px ' + this._font; - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); // outer circle - - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); // inner circle - - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); // text - - var text = this._text || (percent | 0) + '%'; - var w = ctx.measureText(text).width; - ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1); - } catch (ignore) {// don't fail if we can't render progress - } - - return this; - }; - - var html$1 = createCommonjsModule(function (module, exports) { - /* eslint-env browser */ - - /** - * @module HTML - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; - var EVENT_SUITE_END = constants.EVENT_SUITE_END; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var escape = utils.escape; - /** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - - var Date = commonjsGlobal.Date; - /** - * Expose `HTML`. - */ - - module.exports = HTML; - /** - * Stats template. - */ - - var statsTemplate = '
    '; - var playIcon = '‣'; - /** - * Constructs a new `HTML` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function HTML(runner, options) { - base.call(this, runner, options); - var self = this; - var stats = this.stats; - var stat = fragment(statsTemplate); - var items = stat.getElementsByTagName('li'); - var passes = items[1].getElementsByTagName('em')[0]; - var passesLink = items[1].getElementsByTagName('a')[0]; - var failures = items[2].getElementsByTagName('em')[0]; - var failuresLink = items[2].getElementsByTagName('a')[0]; - var duration = items[3].getElementsByTagName('em')[0]; - var canvas = stat.getElementsByTagName('canvas')[0]; - var report = fragment('
      '); - var stack = [report]; - var progress$1; - var ctx; - var root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress$1 = new progress(); - } - - if (!root) { - return error('#mocha div missing, add it to your document'); - } // pass toggle - - - on(passesLink, 'click', function (evt) { - evt.preventDefault(); - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - - if (report.className.trim()) { - hideSuitesWithout('test pass'); - } - }); // failure toggle - - on(failuresLink, 'click', function (evt) { - evt.preventDefault(); - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - - if (report.className.trim()) { - hideSuitesWithout('test fail'); - } - }); - root.appendChild(stat); - root.appendChild(report); - - if (progress$1) { - progress$1.size(40); - } - - runner.on(EVENT_SUITE_BEGIN, function (suite) { - if (suite.root) { - return; - } // suite - - - var url = self.suiteURL(suite); - var el = fragment('
    • %s

    • ', url, escape(suite.title)); // container - - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - runner.on(EVENT_SUITE_END, function (suite) { - if (suite.root) { - updateStats(); - return; - } - - stack.shift(); - }); - runner.on(EVENT_TEST_PASS, function (test) { - var url = self.testURL(test); - var markup = '
    • %e%ems ' + '' + playIcon + '

    • '; - var el = fragment(markup, test.speed, test.title, test.duration, url); - self.addCodeToggle(el, test.body); - appendToStack(el); - updateStats(); - }); - runner.on(EVENT_TEST_FAIL, function (test) { - var el = fragment('
    • %e ' + playIcon + '

    • ', test.title, self.testURL(test)); - var stackString; // Note: Includes leading newline - - var message = test.err.toString(); // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - - if (message === '[object Error]') { - message = test.err.message; - } - - if (test.err.stack) { - var indexOfMessage = test.err.stack.indexOf(test.err.message); - - if (indexOfMessage === -1) { - stackString = test.err.stack; - } else { - stackString = test.err.stack.substr(test.err.message.length + indexOfMessage); - } - } else if (test.err.sourceURL && test.err.line !== undefined) { - // Safari doesn't give you a stack. Let's at least provide a source line. - stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; - } - - stackString = stackString || ''; - - if (test.err.htmlMessage && stackString) { - el.appendChild(fragment('
      %s\n
      %e
      ', test.err.htmlMessage, stackString)); - } else if (test.err.htmlMessage) { - el.appendChild(fragment('
      %s
      ', test.err.htmlMessage)); - } else { - el.appendChild(fragment('
      %e%e
      ', message, stackString)); - } - - self.addCodeToggle(el, test.body); - appendToStack(el); - updateStats(); - }); - runner.on(EVENT_TEST_PENDING, function (test) { - var el = fragment('
    • %e

    • ', test.title); - appendToStack(el); - updateStats(); - }); - - function appendToStack(el) { - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) { - stack[0].appendChild(el); - } - } - - function updateStats() { - // TODO: add to stats - var percent = stats.tests / runner.total * 100 | 0; - - if (progress$1) { - progress$1.update(percent).draw(ctx); - } // update stats - - - var ms = new Date() - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - } - } - /** - * Makes a URL, preserving querystring ("search") parameters. - * - * @param {string} s - * @return {string} A new URL. - */ - - - function makeUrl(s) { - var search = window.location.search; // Remove previous grep query parameter if present - - if (search) { - search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); - } - - return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeStringRegexp(s)); - } - /** - * Provide suite URL. - * - * @param {Object} [suite] - */ - - - HTML.prototype.suiteURL = function (suite) { - return makeUrl(suite.fullTitle()); - }; - /** - * Provide test URL. - * - * @param {Object} [test] - */ - - - HTML.prototype.testURL = function (test) { - return makeUrl(test.fullTitle()); - }; - /** - * Adds code toggle functionality for the provided test's list element. - * - * @param {HTMLLIElement} el - * @param {string} contents - */ - - - HTML.prototype.addCodeToggle = function (el, contents) { - var h2 = el.getElementsByTagName('h2')[0]; - on(h2, 'click', function () { - pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; - }); - var pre = fragment('
      %e
      ', utils.clean(contents)); - el.appendChild(pre); - pre.style.display = 'none'; - }; - /** - * Display error `msg`. - * - * @param {string} msg - */ - - - function error(msg) { - document.body.appendChild(fragment('
      %s
      ', msg)); - } - /** - * Return a DOM fragment from `html`. - * - * @param {string} html - */ - - - function fragment(html) { - var args = arguments; - var div = document.createElement('div'); - var i = 1; - div.innerHTML = html.replace(/%([se])/g, function (_, type) { - switch (type) { - case 's': - return String(args[i++]); - - case 'e': - return escape(args[i++]); - // no default - } - }); - return div.firstChild; - } - /** - * Check for suites that do not have elements - * with `classname`, and hide them. - * - * @param {text} classname - */ - - - function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - - if (!els.length) { - suites[i].className += ' hidden'; - } - } - } - /** - * Unhide .hidden suites. - */ - - - function unhide() { - var els = document.getElementsByClassName('suite hidden'); - - while (els.length > 0) { - els[0].className = els[0].className.replace('suite hidden', 'suite'); - } - } - /** - * Set an element's text contents. - * - * @param {HTMLElement} el - * @param {string} contents - */ - - - function text(el, contents) { - if (el.textContent) { - el.textContent = contents; - } else { - el.innerText = contents; - } - } - /** - * Listen on `event` with callback `fn`. - */ - - - function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } - } - - HTML.browserOnly = true; - }); - - var list = createCommonjsModule(function (module, exports) { - /** - * @module List - */ - - /** - * Module dependencies. - */ - - var inherits = utils.inherits; - var constants = runner$1.constants; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var color = base.color; - var cursor = base.cursor; - /** - * Expose `List`. - */ - - module.exports = List; - /** - * Constructs a new `List` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function List(runner, options) { - base.call(this, runner, options); - var self = this; - var n = 0; - runner.on(EVENT_RUN_BEGIN, function () { - base.consoleLog(); - }); - runner.on(EVENT_TEST_BEGIN, function (test) { - process$1.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - runner.on(EVENT_TEST_PENDING, function (test) { - var fmt = color('checkmark', ' -') + color('pending', ' %s'); - base.consoleLog(fmt, test.fullTitle()); - }); - runner.on(EVENT_TEST_PASS, function (test) { - var fmt = color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s: ') + color(test.speed, '%dms'); - cursor.CR(); - base.consoleLog(fmt, test.fullTitle(), test.duration); - }); - runner.on(EVENT_TEST_FAIL, function (test) { - cursor.CR(); - base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - runner.once(EVENT_RUN_END, self.epilogue.bind(self)); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(List, base); - List.description = 'like "spec" reporter but flat'; - }); - - var min$7 = createCommonjsModule(function (module, exports) { - /** - * @module Min - */ - - /** - * Module dependencies. - */ - - var inherits = utils.inherits; - var constants = runner$1.constants; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - /** - * Expose `Min`. - */ - - module.exports = Min; - /** - * Constructs a new `Min` reporter instance. - * - * @description - * This minimal test reporter is best used with '--watch'. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Min(runner, options) { - base.call(this, runner, options); - runner.on(EVENT_RUN_BEGIN, function () { - // clear screen - process$1.stdout.write("\x1B[2J"); // set cursor position - - process$1.stdout.write("\x1B[1;3H"); - }); - runner.once(EVENT_RUN_END, this.epilogue.bind(this)); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(Min, base); - Min.description = 'essentially just a summary'; - }); - - var spec = createCommonjsModule(function (module, exports) { - /** - * @module Spec - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; - var EVENT_SUITE_END = constants.EVENT_SUITE_END; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var inherits = utils.inherits; - var color = base.color; - /** - * Expose `Spec`. - */ - - module.exports = Spec; - /** - * Constructs a new `Spec` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Spec(runner, options) { - base.call(this, runner, options); - var self = this; - var indents = 0; - var n = 0; - - function indent() { - return Array(indents).join(' '); - } - - runner.on(EVENT_RUN_BEGIN, function () { - base.consoleLog(); - }); - runner.on(EVENT_SUITE_BEGIN, function (suite) { - ++indents; - base.consoleLog(color('suite', '%s%s'), indent(), suite.title); - }); - runner.on(EVENT_SUITE_END, function () { - --indents; - - if (indents === 1) { - base.consoleLog(); - } - }); - runner.on(EVENT_TEST_PENDING, function (test) { - var fmt = indent() + color('pending', ' - %s'); - base.consoleLog(fmt, test.title); - }); - runner.on(EVENT_TEST_PASS, function (test) { - var fmt; - - if (test.speed === 'fast') { - fmt = indent() + color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s'); - base.consoleLog(fmt, test.title); - } else { - fmt = indent() + color('checkmark', ' ' + base.symbols.ok) + color('pass', ' %s') + color(test.speed, ' (%dms)'); - base.consoleLog(fmt, test.title, test.duration); - } - }); - runner.on(EVENT_TEST_FAIL, function (test) { - base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - runner.once(EVENT_RUN_END, self.epilogue.bind(self)); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(Spec, base); - Spec.description = 'hierarchical & verbose [default]'; - }); - - var nyan = createCommonjsModule(function (module, exports) { - /** - * @module Nyan - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var inherits = utils.inherits; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - /** - * Expose `Dot`. - */ - - module.exports = NyanCat; - /** - * Constructs a new `Nyan` reporter instance. - * - * @public - * @class Nyan - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function NyanCat(runner, options) { - base.call(this, runner, options); - var self = this; - var width = base.window.width * 0.75 | 0; - var nyanCatWidth = this.nyanCatWidth = 11; - this.colorIndex = 0; - this.numberOfLines = 4; - this.rainbowColors = self.generateColors(); - this.scoreboardWidth = 5; - this.tick = 0; - this.trajectories = [[], [], [], []]; - this.trajectoryWidthMax = width - nyanCatWidth; - runner.on(EVENT_RUN_BEGIN, function () { - base.cursor.hide(); - self.draw(); - }); - runner.on(EVENT_TEST_PENDING, function () { - self.draw(); - }); - runner.on(EVENT_TEST_PASS, function () { - self.draw(); - }); - runner.on(EVENT_TEST_FAIL, function () { - self.draw(); - }); - runner.once(EVENT_RUN_END, function () { - base.cursor.show(); - - for (var i = 0; i < self.numberOfLines; i++) { - write('\n'); - } - - self.epilogue(); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(NyanCat, base); - /** - * Draw the nyan cat - * - * @private - */ - - NyanCat.prototype.draw = function () { - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; - }; - /** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @private - */ - - - NyanCat.prototype.drawScoreboard = function () { - var stats = this.stats; - - function draw(type, n) { - write(' '); - write(base.color(type, n)); - write('\n'); - } - - draw('green', stats.passes); - draw('fail', stats.failures); - draw('pending', stats.pending); - write('\n'); - this.cursorUp(this.numberOfLines); - }; - /** - * Append the rainbow. - * - * @private - */ - - - NyanCat.prototype.appendRainbow = function () { - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - - if (trajectory.length >= this.trajectoryWidthMax) { - trajectory.shift(); - } - - trajectory.push(rainbowified); - } - }; - /** - * Draw the rainbow. - * - * @private - */ - - - NyanCat.prototype.drawRainbow = function () { - var self = this; - this.trajectories.forEach(function (line) { - write("\x1B[" + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - this.cursorUp(this.numberOfLines); - }; - /** - * Draw the nyan cat - * - * @private - */ - - - NyanCat.prototype.drawNyanCat = function () { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var dist = "\x1B[" + startWidth + 'C'; - var padding = ''; - write(dist); - write('_,------,'); - write('\n'); - write(dist); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - write(dist); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); - write(dist); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - this.cursorUp(this.numberOfLines); - }; - /** - * Draw nyan cat face. - * - * @private - * @return {string} - */ - - - NyanCat.prototype.face = function () { - var stats = this.stats; - - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if (stats.passes) { - return '( ^ .^)'; - } - - return '( - .-)'; - }; - /** - * Move cursor up `n`. - * - * @private - * @param {number} n - */ - - - NyanCat.prototype.cursorUp = function (n) { - write("\x1B[" + n + 'A'); - }; - /** - * Move cursor down `n`. - * - * @private - * @param {number} n - */ - - - NyanCat.prototype.cursorDown = function (n) { - write("\x1B[" + n + 'B'); - }; - /** - * Generate rainbow colors. - * - * @private - * @return {Array} - */ - - - NyanCat.prototype.generateColors = function () { - var colors = []; - - for (var i = 0; i < 6 * 7; i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = i * (1.0 / 6); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; - }; - /** - * Apply rainbow to the given `str`. - * - * @private - * @param {string} str - * @return {string} - */ - - - NyanCat.prototype.rainbowify = function (str) { - if (!base.useColors) { - return str; - } - - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return "\x1B[38;5;" + color + 'm' + str + "\x1B[0m"; - }; - /** - * Stdout helper. - * - * @param {string} string A message to write to stdout. - */ - - - function write(string) { - process$1.stdout.write(string); - } - - NyanCat.description = '"nyan cat"'; - }); - - var fs = {}; - - var xunit = createCommonjsModule(function (module, exports) { - /** - * @module XUnit - */ - - /** - * Module dependencies. - */ - - var createUnsupportedError = errors.createUnsupportedError; - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; - var STATE_FAILED = runnable.constants.STATE_FAILED; - var inherits = utils.inherits; - var escape = utils.escape; - /** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - - var Date = commonjsGlobal.Date; - /** - * Expose `XUnit`. - */ - - module.exports = XUnit; - /** - * Constructs a new `XUnit` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function XUnit(runner, options) { - base.call(this, runner, options); - var stats = this.stats; - var tests = []; - var self = this; // the name of the test suite, as it will appear in the resulting XML file - - var suiteName; // the default name of the test suite if none is provided - - var DEFAULT_SUITE_NAME = 'Mocha Tests'; - - if (options && options.reporterOptions) { - if (options.reporterOptions.output) { - if (!fs.createWriteStream) { - throw createUnsupportedError('file output not supported in browser'); - } - - fs.mkdirSync(path$1.dirname(options.reporterOptions.output), { - recursive: true - }); - self.fileStream = fs.createWriteStream(options.reporterOptions.output); - } // get the suite name from the reporter options (if provided) - - - suiteName = options.reporterOptions.suiteName; - } // fall back to the default suite name - - - suiteName = suiteName || DEFAULT_SUITE_NAME; - runner.on(EVENT_TEST_PENDING, function (test) { - tests.push(test); - }); - runner.on(EVENT_TEST_PASS, function (test) { - tests.push(test); - }); - runner.on(EVENT_TEST_FAIL, function (test) { - tests.push(test); - }); - runner.once(EVENT_RUN_END, function () { - self.write(tag('testsuite', { - name: suiteName, - tests: stats.tests, - failures: 0, - errors: stats.failures, - skipped: stats.tests - stats.failures - stats.passes, - timestamp: new Date().toUTCString(), - time: stats.duration / 1000 || 0 - }, false)); - tests.forEach(function (t) { - self.test(t); - }); - self.write(''); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(XUnit, base); - /** - * Override done to close the stream (if it's a file). - * - * @param failures - * @param {Function} fn - */ - - XUnit.prototype.done = function (failures, fn) { - if (this.fileStream) { - this.fileStream.end(function () { - fn(failures); - }); - } else { - fn(failures); - } - }; - /** - * Write out the given line. - * - * @param {string} line - */ - - - XUnit.prototype.write = function (line) { - if (this.fileStream) { - this.fileStream.write(line + '\n'); - } else if (_typeof(process$1) === 'object' && process$1.stdout) { - process$1.stdout.write(line + '\n'); - } else { - base.consoleLog(line); - } - }; - /** - * Output tag for the given `test.` - * - * @param {Test} test - */ - - - XUnit.prototype.test = function (test) { - base.useColors = false; - var attrs = { - classname: test.parent.fullTitle(), - name: test.title, - time: test.duration / 1000 || 0 - }; - - if (test.state === STATE_FAILED) { - var err = test.err; - var diff = !base.hideDiff && base.showDiff(err) ? '\n' + base.generateDiff(err.actual, err.expected) : ''; - this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + escape(diff) + '\n' + escape(err.stack)))); - } else if (test.isPending()) { - this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - this.write(tag('testcase', attrs, true)); - } - }; - /** - * HTML tag helper. - * - * @param name - * @param attrs - * @param close - * @param content - * @return {string} - */ - - - function tag(name, attrs, close, content) { - var end = close ? '/>' : '>'; - var pairs = []; - var tag; - - for (var key in attrs) { - if (Object.prototype.hasOwnProperty.call(attrs, key)) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - - if (content) { - tag += content + '' + '\n'; - buf += title(suite.title) + '\n'; - }); - runner.on(EVENT_SUITE_END, function () { - --level; - }); - runner.on(EVENT_TEST_PASS, function (test) { - var code = utils.clean(test.body); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - runner.once(EVENT_RUN_END, function () { - process$1.stdout.write('# TOC\n'); - process$1.stdout.write(generateTOC(runner.suite)); - process$1.stdout.write(buf); - }); - } - - Markdown.description = 'GitHub Flavored Markdown'; - }); - - var progress$1 = createCommonjsModule(function (module, exports) { - /** - * @module Progress - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_TEST_END = constants.EVENT_TEST_END; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var inherits = utils.inherits; - var color = base.color; - var cursor = base.cursor; - /** - * Expose `Progress`. - */ - - module.exports = Progress; - /** - * General progress bar color. - */ - - base.colors.progress = 90; - /** - * Constructs a new `Progress` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Progress(runner, options) { - base.call(this, runner, options); - var self = this; - var width = base.window.width * 0.5 | 0; - var total = runner.total; - var complete = 0; - var lastN = -1; // default chars - - options = options || {}; - var reporterOptions = options.reporterOptions || {}; - options.open = reporterOptions.open || '['; - options.complete = reporterOptions.complete || '▬'; - options.incomplete = reporterOptions.incomplete || base.symbols.dot; - options.close = reporterOptions.close || ']'; - options.verbose = reporterOptions.verbose || false; // tests started - - runner.on(EVENT_RUN_BEGIN, function () { - process$1.stdout.write('\n'); - cursor.hide(); - }); // tests complete - - runner.on(EVENT_TEST_END, function () { - complete++; - var percent = complete / total; - var n = width * percent | 0; - var i = width - n; - - if (n === lastN && !options.verbose) { - // Don't re-render the line if it hasn't changed - return; - } - - lastN = n; - cursor.CR(); - process$1.stdout.write("\x1B[J"); - process$1.stdout.write(color('progress', ' ' + options.open)); - process$1.stdout.write(Array(n).join(options.complete)); - process$1.stdout.write(Array(i).join(options.incomplete)); - process$1.stdout.write(color('progress', options.close)); - - if (options.verbose) { - process$1.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); // tests are complete, output some stats - // and the failures if any - - runner.once(EVENT_RUN_END, function () { - cursor.show(); - process$1.stdout.write('\n'); - self.epilogue(); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(Progress, base); - Progress.description = 'a progress bar'; - }); - - var landing = createCommonjsModule(function (module, exports) { - /** - * @module Landing - */ - - /** - * Module dependencies. - */ - - var inherits = utils.inherits; - var constants = runner$1.constants; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_RUN_END = constants.EVENT_RUN_END; - var EVENT_TEST_END = constants.EVENT_TEST_END; - var STATE_FAILED = runnable.constants.STATE_FAILED; - var cursor = base.cursor; - var color = base.color; - /** - * Expose `Landing`. - */ - - module.exports = Landing; - /** - * Airplane color. - */ - - base.colors.plane = 0; - /** - * Airplane crash color. - */ - - base.colors['plane crash'] = 31; - /** - * Runway color. - */ - - base.colors.runway = 90; - /** - * Constructs a new `Landing` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function Landing(runner, options) { - base.call(this, runner, options); - var self = this; - var width = base.window.width * 0.75 | 0; - var stream = process$1.stdout; - var plane = color('plane', '✈'); - var crashed = -1; - var n = 0; - var total = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on(EVENT_RUN_BEGIN, function () { - stream.write('\n\n\n '); - cursor.hide(); - }); - runner.on(EVENT_TEST_END, function (test) { - // check if the plane crashed - var col = crashed === -1 ? width * ++n / ++total | 0 : crashed; // show the crash - - if (test.state === STATE_FAILED) { - plane = color('plane crash', '✈'); - crashed = col; - } // render landing strip - - - stream.write("\x1B[" + (width + 1) + "D\x1B[2A"); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane); - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write("\x1B[0m"); - }); - runner.once(EVENT_RUN_END, function () { - cursor.show(); - process$1.stdout.write('\n'); - self.epilogue(); - }); // if cursor is hidden when we ctrl-C, then it will remain hidden unless... - - process$1.once('SIGINT', function () { - cursor.show(); - nextTick(function () { - process$1.kill(process$1.pid, 'SIGINT'); - }); - }); - } - /** - * Inherit from `Base.prototype`. - */ - - - inherits(Landing, base); - Landing.description = 'Unicode landing strip'; - }); - - var jsonStream = createCommonjsModule(function (module, exports) { - /** - * @module JSONStream - */ - - /** - * Module dependencies. - */ - - var constants = runner$1.constants; - var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; - var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; - var EVENT_RUN_END = constants.EVENT_RUN_END; - /** - * Expose `JSONStream`. - */ - - module.exports = JSONStream; - /** - * Constructs a new `JSONStream` reporter instance. - * - * @public - * @class - * @memberof Mocha.reporters - * @extends Mocha.reporters.Base - * @param {Runner} runner - Instance triggers reporter actions. - * @param {Object} [options] - runner options - */ - - function JSONStream(runner, options) { - base.call(this, runner, options); - var self = this; - var total = runner.total; - runner.once(EVENT_RUN_BEGIN, function () { - writeEvent(['start', { - total: total - }]); - }); - runner.on(EVENT_TEST_PASS, function (test) { - writeEvent(['pass', clean(test)]); - }); - runner.on(EVENT_TEST_FAIL, function (test, err) { - test = clean(test); - test.err = err.message; - test.stack = err.stack || null; - writeEvent(['fail', test]); - }); - runner.once(EVENT_RUN_END, function () { - writeEvent(['end', self.stats]); - }); - } - /** - * Mocha event to be written to the output stream. - * @typedef {Array} JSONStream~MochaEvent - */ - - /** - * Writes Mocha event to reporter output stream. - * - * @private - * @param {JSONStream~MochaEvent} event - Mocha event to be output. - */ - - - function writeEvent(event) { - process$1.stdout.write(JSON.stringify(event) + '\n'); - } - /** - * Returns an object literal representation of `test` - * free of cyclic properties, etc. - * - * @private - * @param {Test} test - Instance used as data source. - * @return {Object} object containing pared-down test instance data - */ - - - function clean(test) { - return { - title: test.title, - fullTitle: test.fullTitle(), - file: test.file, - duration: test.duration, - currentRetry: test.currentRetry(), - speed: test.speed - }; - } - - JSONStream.description = 'newline delimited JSON events'; - }); - - var reporters = createCommonjsModule(function (module, exports) { - // for dynamic (try/catch) requires, which Browserify doesn't handle. - - exports.Base = exports.base = base; - exports.Dot = exports.dot = dot; - exports.Doc = exports.doc = doc; - exports.TAP = exports.tap = tap; - exports.JSON = exports.json = json; - exports.HTML = exports.html = html$1; - exports.List = exports.list = list; - exports.Min = exports.min = min$7; - exports.Spec = exports.spec = spec; - exports.Nyan = exports.nyan = nyan; - exports.XUnit = exports.xunit = xunit; - exports.Markdown = exports.markdown = markdown; - exports.Progress = exports.progress = progress$1; - exports.Landing = exports.landing = landing; - exports.JSONStream = exports['json-stream'] = jsonStream; - }); - - var name = "mocha"; - var version$2 = "8.4.0"; - var homepage = "https://mochajs.org/"; - var notifyLogo = "https://ibin.co/4QuRuGjXvl36.png"; - var _package = { - name: name, - version: version$2, - homepage: homepage, - notifyLogo: notifyLogo - }; - - var _package$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - name: name, - version: version$2, - homepage: homepage, - notifyLogo: notifyLogo, - 'default': _package - }); - - var require$$10 = getCjsExportFromNamespace(_package$1); - - /** - * Web Notifications module. - * @module Growl - */ - - /** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - - - var Date$2 = commonjsGlobal.Date; - var setTimeout$2 = commonjsGlobal.setTimeout; - var EVENT_RUN_END = runner$1.constants.EVENT_RUN_END; - var isBrowser = utils.isBrowser; - /** - * Checks if browser notification support exists. - * - * @public - * @see {@link https://caniuse.com/#feat=notifications|Browser support (notifications)} - * @see {@link https://caniuse.com/#feat=promises|Browser support (promises)} - * @see {@link Mocha#growl} - * @see {@link Mocha#isGrowlCapable} - * @return {boolean} whether browser notification support exists - */ - - var isCapable = function isCapable() { - var hasNotificationSupport = ('Notification' in window); - var hasPromiseSupport = typeof Promise === 'function'; - return isBrowser() && hasNotificationSupport && hasPromiseSupport; - }; - /** - * Implements browser notifications as a pseudo-reporter. - * - * @public - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/notification|Notification API} - * @see {@link https://developers.google.com/web/fundamentals/push-notifications/display-a-notification|Displaying a Notification} - * @see {@link Growl#isPermitted} - * @see {@link Mocha#_growl} - * @param {Runner} runner - Runner instance. - */ - - - var notify$2 = function notify(runner) { - var promise = isPermitted(); - /** - * Attempt notification. - */ - - var sendNotification = function sendNotification() { - // If user hasn't responded yet... "No notification for you!" (Seinfeld) - Promise.race([promise, Promise.resolve(undefined)]).then(canNotify).then(function () { - display(runner); - })["catch"](notPermitted); - }; - - runner.once(EVENT_RUN_END, sendNotification); - }; - /** - * Checks if browser notification is permitted by user. - * - * @private - * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission} - * @see {@link Mocha#growl} - * @see {@link Mocha#isGrowlPermitted} - * @returns {Promise} promise determining if browser notification - * permissible when fulfilled. - */ - - - function isPermitted() { - var permitted = { - granted: function allow() { - return Promise.resolve(true); - }, - denied: function deny() { - return Promise.resolve(false); - }, - "default": function ask() { - return Notification.requestPermission().then(function (permission) { - return permission === 'granted'; - }); - } - }; - return permitted[Notification.permission](); - } - /** - * @summary - * Determines if notification should proceed. - * - * @description - * Notification shall not proceed unless `value` is true. - * - * `value` will equal one of: - *
        - *
      • true (from `isPermitted`)
      • - *
      • false (from `isPermitted`)
      • - *
      • undefined (from `Promise.race`)
      • - *
      - * - * @private - * @param {boolean|undefined} value - Determines if notification permissible. - * @returns {Promise} Notification can proceed - */ - - - function canNotify(value) { - if (!value) { - var why = value === false ? 'blocked' : 'unacknowledged'; - var reason = 'not permitted by user (' + why + ')'; - return Promise.reject(new Error(reason)); - } - - return Promise.resolve(); - } - /** - * Displays the notification. - * - * @private - * @param {Runner} runner - Runner instance. - */ - - - function display(runner) { - var stats = runner.stats; - var symbol = { - cross: "\u274C", - tick: "\u2705" - }; - var logo = require$$10.notifyLogo; - - var _message; - - var message; - var title; - - if (stats.failures) { - _message = stats.failures + ' of ' + stats.tests + ' tests failed'; - message = symbol.cross + ' ' + _message; - title = 'Failed'; - } else { - _message = stats.passes + ' tests passed in ' + stats.duration + 'ms'; - message = symbol.tick + ' ' + _message; - title = 'Passed'; - } // Send notification - - - var options = { - badge: logo, - body: message, - dir: 'ltr', - icon: logo, - lang: 'en-US', - name: 'mocha', - requireInteraction: false, - timestamp: Date$2.now() - }; - var notification = new Notification(title, options); // Autoclose after brief delay (makes various browsers act same) - - var FORCE_DURATION = 4000; - setTimeout$2(notification.close.bind(notification), FORCE_DURATION); - } - /** - * As notifications are tangential to our purpose, just log the error. - * - * @private - * @param {Error} err - Why notification didn't happen. - */ - - - function notPermitted(err) { - console.error('notification error:', err.message); - } - - var growl = { - isCapable: isCapable, - notify: notify$2 - }; - - var diff$1 = true; - var extension = [ - "js", - "cjs", - "mjs" - ]; - var reporter = "spec"; - var slow = 75; - var timeout = 2000; - var ui = "bdd"; - var mocharc = { - diff: diff$1, - extension: extension, - "package": "./package.json", - reporter: reporter, - slow: slow, - timeout: timeout, - ui: ui, - "watch-ignore": [ - "node_modules", - ".git" - ] - }; - - var mocharc$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - diff: diff$1, - extension: extension, - reporter: reporter, - slow: slow, - timeout: timeout, - ui: ui, - 'default': mocharc - }); - - /** - * Provides a factory function for a {@link StatsCollector} object. - * @module - */ - - - var constants$4 = runner$1.constants; - var EVENT_TEST_PASS = constants$4.EVENT_TEST_PASS; - var EVENT_TEST_FAIL = constants$4.EVENT_TEST_FAIL; - var EVENT_SUITE_BEGIN = constants$4.EVENT_SUITE_BEGIN; - var EVENT_RUN_BEGIN = constants$4.EVENT_RUN_BEGIN; - var EVENT_TEST_PENDING = constants$4.EVENT_TEST_PENDING; - var EVENT_RUN_END$1 = constants$4.EVENT_RUN_END; - var EVENT_TEST_END = constants$4.EVENT_TEST_END; - /** - * Test statistics collector. - * - * @public - * @typedef {Object} StatsCollector - * @property {number} suites - integer count of suites run. - * @property {number} tests - integer count of tests run. - * @property {number} passes - integer count of passing tests. - * @property {number} pending - integer count of pending tests. - * @property {number} failures - integer count of failed tests. - * @property {Date} start - time when testing began. - * @property {Date} end - time when testing concluded. - * @property {number} duration - number of msecs that testing took. - */ - - var Date$3 = commonjsGlobal.Date; - /** - * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`. - * - * @private - * @param {Runner} runner - Runner instance - * @throws {TypeError} If falsy `runner` - */ - - function createStatsCollector(runner) { - /** - * @type StatsCollector - */ - var stats = { - suites: 0, - tests: 0, - passes: 0, - pending: 0, - failures: 0 - }; - - if (!runner) { - throw new TypeError('Missing runner argument'); - } - - runner.stats = stats; - runner.once(EVENT_RUN_BEGIN, function () { - stats.start = new Date$3(); - }); - runner.on(EVENT_SUITE_BEGIN, function (suite) { - suite.root || stats.suites++; - }); - runner.on(EVENT_TEST_PASS, function () { - stats.passes++; - }); - runner.on(EVENT_TEST_FAIL, function () { - stats.failures++; - }); - runner.on(EVENT_TEST_PENDING, function () { - stats.pending++; - }); - runner.on(EVENT_TEST_END, function () { - stats.tests++; - }); - runner.once(EVENT_RUN_END$1, function () { - stats.end = new Date$3(); - stats.duration = stats.end - stats.start; - }); - } - - var statsCollector = createStatsCollector; - - var createInvalidArgumentTypeError$1 = errors.createInvalidArgumentTypeError; - var isString$1 = utils.isString; - var MOCHA_ID_PROP_NAME$1 = utils.constants.MOCHA_ID_PROP_NAME; - var test$1 = Test; - /** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @public - * @class - * @extends Runnable - * @param {String} title - Test title (required) - * @param {Function} [fn] - Test callback. If omitted, the Test is considered "pending" - */ - - function Test(title, fn) { - if (!isString$1(title)) { - throw createInvalidArgumentTypeError$1('Test argument "title" should be a string. Received type "' + _typeof(title) + '"', 'title', 'string'); - } - - this.type = 'test'; - runnable.call(this, title, fn); - this.reset(); - } - /** - * Inherit from `Runnable.prototype`. - */ - - - utils.inherits(Test, runnable); - /** - * Resets the state initially or for a next run. - */ - - Test.prototype.reset = function () { - runnable.prototype.reset.call(this); - this.pending = !this.fn; - delete this.state; - }; - /** - * Set or get retried test - * - * @private - */ - - - Test.prototype.retriedTest = function (n) { - if (!arguments.length) { - return this._retriedTest; - } - - this._retriedTest = n; - }; - /** - * Add test to the list of tests marked `only`. - * - * @private - */ - - - Test.prototype.markOnly = function () { - this.parent.appendOnlyTest(this); - }; - - Test.prototype.clone = function () { - var test = new Test(this.title, this.fn); - test.timeout(this.timeout()); - test.slow(this.slow()); - test.retries(this.retries()); - test.currentRetry(this.currentRetry()); - test.retriedTest(this.retriedTest() || this); - test.globals(this.globals()); - test.parent = this.parent; - test.file = this.file; - test.ctx = this.ctx; - return test; - }; - /** - * Returns an minimal object suitable for transmission over IPC. - * Functions are represented by keys beginning with `$$`. - * @private - * @returns {Object} - */ - - - Test.prototype.serialize = function serialize() { - return _defineProperty({ - $$currentRetry: this._currentRetry, - $$fullTitle: this.fullTitle(), - $$isPending: this.pending, - $$retriedTest: this._retriedTest || null, - $$slow: this._slow, - $$titlePath: this.titlePath(), - body: this.body, - duration: this.duration, - err: this.err, - parent: _defineProperty({ - $$fullTitle: this.parent.fullTitle() - }, MOCHA_ID_PROP_NAME$1, this.parent.id), - speed: this.speed, - state: this.state, - title: this.title, - type: this.type, - file: this.file - }, MOCHA_ID_PROP_NAME$1, this.id); - }; - - /** - @module interfaces/common - */ - - - var createMissingArgumentError$1 = errors.createMissingArgumentError; - var createUnsupportedError$2 = errors.createUnsupportedError; - var createForbiddenExclusivityError$1 = errors.createForbiddenExclusivityError; - /** - * Functions common to more than one interface. - * - * @private - * @param {Suite[]} suites - * @param {Context} context - * @param {Mocha} mocha - * @return {Object} An object containing common functions. - */ - - var common$1 = function common(suites, context, mocha) { - /** - * Check if the suite should be tested. - * - * @private - * @param {Suite} suite - suite to check - * @returns {boolean} - */ - function shouldBeTested(suite) { - return !mocha.options.grep || mocha.options.grep && mocha.options.grep.test(suite.fullTitle()) && !mocha.options.invert; - } - - return { - /** - * This is only present if flag --delay is passed into Mocha. It triggers - * root suite execution. - * - * @param {Suite} suite The root suite. - * @return {Function} A function which runs the root suite - */ - runWithSuite: function runWithSuite(suite) { - return function run() { - suite.run(); - }; - }, - - /** - * Execute before running tests. - * - * @param {string} name - * @param {Function} fn - */ - before: function before(name, fn) { - suites[0].beforeAll(name, fn); - }, - - /** - * Execute after running tests. - * - * @param {string} name - * @param {Function} fn - */ - after: function after(name, fn) { - suites[0].afterAll(name, fn); - }, - - /** - * Execute before each test case. - * - * @param {string} name - * @param {Function} fn - */ - beforeEach: function beforeEach(name, fn) { - suites[0].beforeEach(name, fn); - }, - - /** - * Execute after each test case. - * - * @param {string} name - * @param {Function} fn - */ - afterEach: function afterEach(name, fn) { - suites[0].afterEach(name, fn); - }, - suite: { - /** - * Create an exclusive Suite; convenience function - * See docstring for create() below. - * - * @param {Object} opts - * @returns {Suite} - */ - only: function only(opts) { - if (mocha.options.forbidOnly) { - throw createForbiddenExclusivityError$1(mocha); - } - - opts.isOnly = true; - return this.create(opts); - }, - - /** - * Create a Suite, but skip it; convenience function - * See docstring for create() below. - * - * @param {Object} opts - * @returns {Suite} - */ - skip: function skip(opts) { - opts.pending = true; - return this.create(opts); - }, - - /** - * Creates a suite. - * - * @param {Object} opts Options - * @param {string} opts.title Title of Suite - * @param {Function} [opts.fn] Suite Function (not always applicable) - * @param {boolean} [opts.pending] Is Suite pending? - * @param {string} [opts.file] Filepath where this Suite resides - * @param {boolean} [opts.isOnly] Is Suite exclusive? - * @returns {Suite} - */ - create: function create(opts) { - var suite$1 = suite.create(suites[0], opts.title); - suite$1.pending = Boolean(opts.pending); - suite$1.file = opts.file; - suites.unshift(suite$1); - - if (opts.isOnly) { - suite$1.markOnly(); - } - - if (suite$1.pending && mocha.options.forbidPending && shouldBeTested(suite$1)) { - throw createUnsupportedError$2('Pending test forbidden'); - } - - if (typeof opts.fn === 'function') { - opts.fn.call(suite$1); - suites.shift(); - } else if (typeof opts.fn === 'undefined' && !suite$1.pending) { - throw createMissingArgumentError$1('Suite "' + suite$1.fullTitle() + '" was defined but no callback was supplied. ' + 'Supply a callback or explicitly skip the suite.', 'callback', 'function'); - } else if (!opts.fn && suite$1.pending) { - suites.shift(); - } - - return suite$1; - } - }, - test: { - /** - * Exclusive test-case. - * - * @param {Object} mocha - * @param {Function} test - * @returns {*} - */ - only: function only(mocha, test) { - if (mocha.options.forbidOnly) { - throw createForbiddenExclusivityError$1(mocha); - } - - test.markOnly(); - return test; - }, - - /** - * Pending test case. - * - * @param {string} title - */ - skip: function skip(title) { - context.test(title); - } - } - }; - }; - - var EVENT_FILE_PRE_REQUIRE = suite.constants.EVENT_FILE_PRE_REQUIRE; - /** - * BDD-style interface: - * - * describe('Array', function() { - * describe('#indexOf()', function() { - * it('should return -1 when not present', function() { - * // ... - * }); - * - * it('should return the index when present', function() { - * // ... - * }); - * }); - * }); - * - * @param {Suite} suite Root suite. - */ - - var bdd = function bddInterface(suite) { - var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) { - var common = common$1(suites, context, mocha); - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function (title, fn) { - return common.suite.create({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Pending describe. - */ - - - context.xdescribe = context.xcontext = context.describe.skip = function (title, fn) { - return common.suite.skip({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Exclusive suite. - */ - - - context.describe.only = function (title, fn) { - return common.suite.only({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - - context.it = context.specify = function (title, fn) { - var suite = suites[0]; - - if (suite.isPending()) { - fn = null; - } - - var test = new test$1(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - /** - * Exclusive test-case. - */ - - - context.it.only = function (title, fn) { - return common.test.only(mocha, context.it(title, fn)); - }; - /** - * Pending test case. - */ - - - context.xit = context.xspecify = context.it.skip = function (title) { - return context.it(title); - }; - }); - }; - - var description = 'BDD or RSpec style [default]'; - bdd.description = description; - - var EVENT_FILE_PRE_REQUIRE$1 = suite.constants.EVENT_FILE_PRE_REQUIRE; - /** - * TDD-style interface: - * - * suite('Array', function() { - * suite('#indexOf()', function() { - * suiteSetup(function() { - * - * }); - * - * test('should return -1 when not present', function() { - * - * }); - * - * test('should return the index when present', function() { - * - * }); - * - * suiteTeardown(function() { - * - * }); - * }); - * }); - * - * @param {Suite} suite Root suite. - */ - - var tdd = function tdd(suite) { - var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE$1, function (context, file, mocha) { - var common = common$1(suites, context, mocha); - context.setup = common.beforeEach; - context.teardown = common.afterEach; - context.suiteSetup = common.before; - context.suiteTeardown = common.after; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title` and callback `fn` containing - * nested suites and/or tests. - */ - - context.suite = function (title, fn) { - return common.suite.create({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Pending suite. - */ - - - context.suite.skip = function (title, fn) { - return common.suite.skip({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Exclusive test-case. - */ - - - context.suite.only = function (title, fn) { - return common.suite.only({ - title: title, - file: file, - fn: fn - }); - }; - /** - * Describe a specification or test-case with the given `title` and - * callback `fn` acting as a thunk. - */ - - - context.test = function (title, fn) { - var suite = suites[0]; - - if (suite.isPending()) { - fn = null; - } - - var test = new test$1(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - /** - * Exclusive test-case. - */ - - - context.test.only = function (title, fn) { - return common.test.only(mocha, context.test(title, fn)); - }; - - context.test.skip = common.test.skip; - }); - }; - - var description$1 = 'traditional "suite"/"test" instead of BDD\'s "describe"/"it"'; - tdd.description = description$1; - - var EVENT_FILE_PRE_REQUIRE$2 = suite.constants.EVENT_FILE_PRE_REQUIRE; - /** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function() { - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function() { - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function() { - * ok('foo'.length == 3); - * }); - * - * @param {Suite} suite Root suite. - */ - - var qunit = function qUnitInterface(suite) { - var suites = [suite]; - suite.on(EVENT_FILE_PRE_REQUIRE$2, function (context, file, mocha) { - var common = common$1(suites, context, mocha); - context.before = common.before; - context.after = common.after; - context.beforeEach = common.beforeEach; - context.afterEach = common.afterEach; - context.run = mocha.options.delay && common.runWithSuite(suite); - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function (title) { - if (suites.length > 1) { - suites.shift(); - } - - return common.suite.create({ - title: title, - file: file, - fn: false - }); - }; - /** - * Exclusive Suite. - */ - - - context.suite.only = function (title) { - if (suites.length > 1) { - suites.shift(); - } - - return common.suite.only({ - title: title, - file: file, - fn: false - }); - }; - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - - context.test = function (title, fn) { - var test = new test$1(title, fn); - test.file = file; - suites[0].addTest(test); - return test; - }; - /** - * Exclusive test-case. - */ - - - context.test.only = function (title, fn) { - return common.test.only(mocha, context.test(title, fn)); - }; - - context.test.skip = common.test.skip; - }); - }; - - var description$2 = 'QUnit style'; - qunit.description = description$2; - - /** - * Exports-style (as Node.js module) interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function() { - * - * }, - * - * 'should return the correct index when the value is present': function() { - * - * } - * } - * }; - * - * @param {Suite} suite Root suite. - */ - - - var exports$1 = function exports(suite$1) { - var suites = [suite$1]; - suite$1.on(suite.constants.EVENT_FILE_REQUIRE, visit); - - function visit(obj, file) { - var suite$1; - - for (var key in obj) { - if (typeof obj[key] === 'function') { - var fn = obj[key]; - - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - - case 'after': - suites[0].afterAll(fn); - break; - - case 'beforeEach': - suites[0].beforeEach(fn); - break; - - case 'afterEach': - suites[0].afterEach(fn); - break; - - default: - var test = new test$1(key, fn); - test.file = file; - suites[0].addTest(test); - } - } else { - suite$1 = suite.create(suites[0], key); - suites.unshift(suite$1); - visit(obj[key], file); - suites.shift(); - } - } - } - }; - - var description$3 = 'Node.js module ("exports") style'; - exports$1.description = description$3; - - var bdd$1 = bdd; - var tdd$1 = tdd; - var qunit$1 = qunit; - var exports$2 = exports$1; - var interfaces = { - bdd: bdd$1, - tdd: tdd$1, - qunit: qunit$1, - exports: exports$2 - }; - - /** - * @module Context - */ - - /** - * Expose `Context`. - */ - - var context = Context; - /** - * Initialize a new `Context`. - * - * @private - */ - - function Context() {} - /** - * Set or get the context `Runnable` to `runnable`. - * - * @private - * @param {Runnable} runnable - * @return {Context} context - */ - - - Context.prototype.runnable = function (runnable) { - if (!arguments.length) { - return this._runnable; - } - - this.test = this._runnable = runnable; - return this; - }; - /** - * Set or get test timeout `ms`. - * - * @private - * @param {number} ms - * @return {Context} self - */ - - - Context.prototype.timeout = function (ms) { - if (!arguments.length) { - return this.runnable().timeout(); - } - - this.runnable().timeout(ms); - return this; - }; - /** - * Set or get test slowness threshold `ms`. - * - * @private - * @param {number} ms - * @return {Context} self - */ - - - Context.prototype.slow = function (ms) { - if (!arguments.length) { - return this.runnable().slow(); - } - - this.runnable().slow(ms); - return this; - }; - /** - * Mark a test as skipped. - * - * @private - * @throws Pending - */ - - - Context.prototype.skip = function () { - this.runnable().skip(); - }; - /** - * Set or get a number of allowed retries on failed tests - * - * @private - * @param {number} n - * @return {Context} self - */ - - - Context.prototype.retries = function (n) { - if (!arguments.length) { - return this.runnable().retries(); - } - - this.runnable().retries(n); - return this; - }; - - var mocharc$2 = getCjsExportFromNamespace(mocharc$1); - - var mocha = createCommonjsModule(function (module, exports) { - /*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - - var esmUtils = utils.supportsEsModules(true) ? require$$11 : undefined; - var warn = errors.warn, - createInvalidReporterError = errors.createInvalidReporterError, - createInvalidInterfaceError = errors.createInvalidInterfaceError, - createMochaInstanceAlreadyDisposedError = errors.createMochaInstanceAlreadyDisposedError, - createMochaInstanceAlreadyRunningError = errors.createMochaInstanceAlreadyRunningError, - createUnsupportedError = errors.createUnsupportedError; - var _Suite$constants = suite.constants, - EVENT_FILE_PRE_REQUIRE = _Suite$constants.EVENT_FILE_PRE_REQUIRE, - EVENT_FILE_POST_REQUIRE = _Suite$constants.EVENT_FILE_POST_REQUIRE, - EVENT_FILE_REQUIRE = _Suite$constants.EVENT_FILE_REQUIRE; - var sQuote = utils.sQuote; - var debug = browser$2('mocha:mocha'); - exports = module.exports = Mocha; - /** - * A Mocha instance is a finite state machine. - * These are the states it can be in. - * @private - */ - - var mochaStates = utils.defineConstants({ - /** - * Initial state of the mocha instance - * @private - */ - INIT: 'init', - - /** - * Mocha instance is running tests - * @private - */ - RUNNING: 'running', - - /** - * Mocha instance is done running tests and references to test functions and hooks are cleaned. - * You can reset this state by unloading the test files. - * @private - */ - REFERENCES_CLEANED: 'referencesCleaned', - - /** - * Mocha instance is disposed and can no longer be used. - * @private - */ - DISPOSED: 'disposed' - }); - /** - * To require local UIs and reporters when running in node. - */ - - if (!utils.isBrowser() && typeof module.paths !== 'undefined') { - var cwd = utils.cwd(); - module.paths.push(cwd, path$1.join(cwd, 'node_modules')); - } - /** - * Expose internals. - * @private - */ - - - exports.utils = utils; - exports.interfaces = interfaces; - /** - * @public - * @memberof Mocha - */ - - exports.reporters = reporters; - exports.Runnable = runnable; - exports.Context = context; - /** - * - * @memberof Mocha - */ - - exports.Runner = runner$1; - exports.Suite = suite; - exports.Hook = hook; - exports.Test = test$1; - var currentContext; - - exports.afterEach = function () { - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - return (currentContext.afterEach || currentContext.teardown).apply(this, args); - }; - - exports.after = function () { - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - - return (currentContext.after || currentContext.suiteTeardown).apply(this, args); - }; - - exports.beforeEach = function () { - for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { - args[_key3] = arguments[_key3]; - } - - return (currentContext.beforeEach || currentContext.setup).apply(this, args); - }; - - exports.before = function () { - for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { - args[_key4] = arguments[_key4]; - } - - return (currentContext.before || currentContext.suiteSetup).apply(this, args); - }; - - exports.describe = function () { - for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { - args[_key5] = arguments[_key5]; - } - - return (currentContext.describe || currentContext.suite).apply(this, args); - }; - - exports.describe.only = function () { - for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { - args[_key6] = arguments[_key6]; - } - - return (currentContext.describe || currentContext.suite).only.apply(this, args); - }; - - exports.describe.skip = function () { - for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { - args[_key7] = arguments[_key7]; - } - - return (currentContext.describe || currentContext.suite).skip.apply(this, args); - }; - - exports.it = function () { - for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { - args[_key8] = arguments[_key8]; - } - - return (currentContext.it || currentContext.test).apply(this, args); - }; - - exports.it.only = function () { - for (var _len9 = arguments.length, args = new Array(_len9), _key9 = 0; _key9 < _len9; _key9++) { - args[_key9] = arguments[_key9]; - } - - return (currentContext.it || currentContext.test).only.apply(this, args); - }; - - exports.it.skip = function () { - for (var _len10 = arguments.length, args = new Array(_len10), _key10 = 0; _key10 < _len10; _key10++) { - args[_key10] = arguments[_key10]; - } - - return (currentContext.it || currentContext.test).skip.apply(this, args); - }; - - exports.xdescribe = exports.describe.skip; - exports.xit = exports.it.skip; - exports.setup = exports.beforeEach; - exports.suiteSetup = exports.before; - exports.suiteTeardown = exports.after; - exports.suite = exports.describe; - exports.teardown = exports.afterEach; - exports.test = exports.it; - - exports.run = function () { - for (var _len11 = arguments.length, args = new Array(_len11), _key11 = 0; _key11 < _len11; _key11++) { - args[_key11] = arguments[_key11]; - } - - return currentContext.run.apply(this, args); - }; - /** - * Constructs a new Mocha instance with `options`. - * - * @public - * @class Mocha - * @param {Object} [options] - Settings object. - * @param {boolean} [options.allowUncaught] - Propagate uncaught errors? - * @param {boolean} [options.asyncOnly] - Force `done` callback or promise? - * @param {boolean} [options.bail] - Bail after first test failure? - * @param {boolean} [options.checkLeaks] - Check for global variable leaks? - * @param {boolean} [options.color] - Color TTY output from reporter? - * @param {boolean} [options.delay] - Delay root suite execution? - * @param {boolean} [options.diff] - Show diff on failure? - * @param {string} [options.fgrep] - Test filter given string. - * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite? - * @param {boolean} [options.forbidPending] - Pending tests fail the suite? - * @param {boolean} [options.fullTrace] - Full stacktrace upon failure? - * @param {string[]} [options.global] - Variables expected in global scope. - * @param {RegExp|string} [options.grep] - Test filter given regular expression. - * @param {boolean} [options.growl] - Enable desktop notifications? - * @param {boolean} [options.inlineDiffs] - Display inline diffs? - * @param {boolean} [options.invert] - Invert test filter matches? - * @param {boolean} [options.noHighlighting] - Disable syntax highlighting? - * @param {string|constructor} [options.reporter] - Reporter name or constructor. - * @param {Object} [options.reporterOption] - Reporter settings object. - * @param {number} [options.retries] - Number of times to retry failed tests. - * @param {number} [options.slow] - Slow threshold value. - * @param {number|string} [options.timeout] - Timeout threshold value. - * @param {string} [options.ui] - Interface name. - * @param {boolean} [options.parallel] - Run jobs in parallel. - * @param {number} [options.jobs] - Max number of worker processes for parallel runs. - * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with. - * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs. - * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process. - */ - - - function Mocha() { - var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - options = _objectSpread2(_objectSpread2({}, mocharc$2), options); - this.files = []; - this.options = options; // root suite - - this.suite = new exports.Suite('', new exports.Context(), true); - this._cleanReferencesAfterRun = true; - this._state = mochaStates.INIT; - this.grep(options.grep).fgrep(options.fgrep).ui(options.ui).reporter(options.reporter, options.reporterOption || options.reporterOptions // reporterOptions was previously the only way to specify options to reporter - ).slow(options.slow).global(options.global); // this guard exists because Suite#timeout does not consider `undefined` to be valid input - - if (typeof options.timeout !== 'undefined') { - this.timeout(options.timeout === false ? 0 : options.timeout); - } - - if ('retries' in options) { - this.retries(options.retries); - } - - ['allowUncaught', 'asyncOnly', 'bail', 'checkLeaks', 'color', 'delay', 'diff', 'forbidOnly', 'forbidPending', 'fullTrace', 'growl', 'inlineDiffs', 'invert'].forEach(function (opt) { - if (options[opt]) { - this[opt](); - } - }, this); - - if (options.rootHooks) { - this.rootHooks(options.rootHooks); - } - /** - * The class which we'll instantiate in {@link Mocha#run}. Defaults to - * {@link Runner} in serial mode; changes in parallel mode. - * @memberof Mocha - * @private - */ - - - this._runnerClass = exports.Runner; - /** - * Whether or not to call {@link Mocha#loadFiles} implicitly when calling - * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call - * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}. - * @private - * @memberof Mocha - */ - - this._lazyLoadFiles = false; - /** - * It's useful for a Mocha instance to know if it's running in a worker process. - * We could derive this via other means, but it's helpful to have a flag to refer to. - * @memberof Mocha - * @private - */ - - this.isWorker = Boolean(options.isWorker); - this.globalSetup(options.globalSetup).globalTeardown(options.globalTeardown).enableGlobalSetup(options.enableGlobalSetup).enableGlobalTeardown(options.enableGlobalTeardown); - - if (options.parallel && (typeof options.jobs === 'undefined' || options.jobs > 1)) { - debug('attempting to enable parallel mode'); - this.parallelMode(true); - } - } - /** - * Enables or disables bailing on the first failure. - * - * @public - * @see [CLI option](../#-bail-b) - * @param {boolean} [bail=true] - Whether to bail on first error. - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.bail = function (bail) { - this.suite.bail(bail !== false); - return this; - }; - /** - * @summary - * Adds `file` to be loaded for execution. - * - * @description - * Useful for generic setup code that must be included within test suite. - * - * @public - * @see [CLI option](../#-file-filedirectoryglob) - * @param {string} file - Pathname of file to be loaded. - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.addFile = function (file) { - this.files.push(file); - return this; - }; - /** - * Sets reporter to `reporter`, defaults to "spec". - * - * @public - * @see [CLI option](../#-reporter-name-r-name) - * @see [Reporters](../#reporters) - * @param {String|Function} reporterName - Reporter name or constructor. - * @param {Object} [reporterOptions] - Options used to configure the reporter. - * @returns {Mocha} this - * @chainable - * @throws {Error} if requested reporter cannot be loaded - * @example - * - * // Use XUnit reporter and direct its output to file - * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' }); - */ - - - Mocha.prototype.reporter = function (reporterName, reporterOptions) { - if (typeof reporterName === 'function') { - this._reporter = reporterName; - } else { - reporterName = reporterName || 'spec'; - var reporter; // Try to load a built-in reporter. - - if (reporters[reporterName]) { - reporter = reporters[reporterName]; - } // Try to load reporters from process.cwd() and node_modules - - - if (!reporter) { - try { - reporter = commonjsRequire(reporterName); - } catch (err) { - if (err.code === 'MODULE_NOT_FOUND') { - // Try to load reporters from a path (absolute or relative) - try { - reporter = commonjsRequire(path$1.resolve(utils.cwd(), reporterName)); - } catch (_err) { - _err.code === 'MODULE_NOT_FOUND' ? warn(sQuote(reporterName) + ' reporter not found') : warn(sQuote(reporterName) + ' reporter blew up with error:\n' + err.stack); - } - } else { - warn(sQuote(reporterName) + ' reporter blew up with error:\n' + err.stack); - } - } - } - - if (!reporter) { - throw createInvalidReporterError('invalid reporter ' + sQuote(reporterName), reporterName); - } - - this._reporter = reporter; - } - - this.options.reporterOption = reporterOptions; // alias option name is used in public reporters xunit/tap/progress - - this.options.reporterOptions = reporterOptions; - return this; - }; - /** - * Sets test UI `name`, defaults to "bdd". - * - * @public - * @see [CLI option](../#-ui-name-u-name) - * @see [Interface DSLs](../#interfaces) - * @param {string|Function} [ui=bdd] - Interface name or class. - * @returns {Mocha} this - * @chainable - * @throws {Error} if requested interface cannot be loaded - */ - - - Mocha.prototype.ui = function (ui) { - var bindInterface; - - if (typeof ui === 'function') { - bindInterface = ui; - } else { - ui = ui || 'bdd'; - bindInterface = exports.interfaces[ui]; - - if (!bindInterface) { - try { - bindInterface = commonjsRequire(ui); - } catch (err) { - throw createInvalidInterfaceError('invalid interface ' + sQuote(ui), ui); - } - } - } - - bindInterface(this.suite); - this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) { - currentContext = context; - }); - return this; - }; - /** - * Loads `files` prior to execution. Does not support ES Modules. - * - * @description - * The implementation relies on Node's `require` to execute - * the test interface functions and will be subject to its cache. - * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync. - * - * @private - * @see {@link Mocha#addFile} - * @see {@link Mocha#run} - * @see {@link Mocha#unloadFiles} - * @see {@link Mocha#loadFilesAsync} - * @param {Function} [fn] - Callback invoked upon completion. - */ - - - Mocha.prototype.loadFiles = function (fn) { - var self = this; - var suite = this.suite; - this.files.forEach(function (file) { - file = path$1.resolve(file); - suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self); - suite.emit(EVENT_FILE_REQUIRE, commonjsRequire(), file, self); - suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self); - }); - fn && fn(); - }; - /** - * Loads `files` prior to execution. Supports Node ES Modules. - * - * @description - * The implementation relies on Node's `require` and `import` to execute - * the test interface functions and will be subject to its cache. - * Supports both CJS and ESM modules. - * - * @public - * @see {@link Mocha#addFile} - * @see {@link Mocha#run} - * @see {@link Mocha#unloadFiles} - * @returns {Promise} - * @example - * - * // loads ESM (and CJS) test files asynchronously, then runs root suite - * mocha.loadFilesAsync() - * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0)) - * .catch(() => process.exitCode = 1); - */ - - - Mocha.prototype.loadFilesAsync = function () { - var self = this; - var suite = this.suite; - this.lazyLoadFiles(true); - - if (!esmUtils) { - return new Promise(function (resolve) { - self.loadFiles(resolve); - }); - } - - return esmUtils.loadFilesAsync(this.files, function (file) { - suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self); - }, function (file, resultModule) { - suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self); - suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self); - }); - }; - /** - * Removes a previously loaded file from Node's `require` cache. - * - * @private - * @static - * @see {@link Mocha#unloadFiles} - * @param {string} file - Pathname of file to be unloaded. - */ - - - Mocha.unloadFile = function (file) { - if (utils.isBrowser()) { - throw createUnsupportedError('unloadFile() is only suported in a Node.js environment'); - } - - return require$$11.unloadFile(file); - }; - /** - * Unloads `files` from Node's `require` cache. - * - * @description - * This allows required files to be "freshly" reloaded, providing the ability - * to reuse a Mocha instance programmatically. - * Note: does not clear ESM module files from the cache - * - * Intended for consumers — not used internally - * - * @public - * @see {@link Mocha#run} - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.unloadFiles = function () { - if (this._state === mochaStates.DISPOSED) { - throw createMochaInstanceAlreadyDisposedError('Mocha instance is already disposed, it cannot be used again.', this._cleanReferencesAfterRun, this); - } - - this.files.forEach(function (file) { - Mocha.unloadFile(file); - }); - this._state = mochaStates.INIT; - return this; - }; - /** - * Sets `grep` filter after escaping RegExp special characters. - * - * @public - * @see {@link Mocha#grep} - * @param {string} str - Value to be converted to a regexp. - * @returns {Mocha} this - * @chainable - * @example - * - * // Select tests whose full title begins with `"foo"` followed by a period - * mocha.fgrep('foo.'); - */ - - - Mocha.prototype.fgrep = function (str) { - if (!str) { - return this; - } - - return this.grep(new RegExp(escapeStringRegexp(str))); - }; - /** - * @summary - * Sets `grep` filter used to select specific tests for execution. - * - * @description - * If `re` is a regexp-like string, it will be converted to regexp. - * The regexp is tested against the full title of each test (i.e., the - * name of the test preceded by titles of each its ancestral suites). - * As such, using an exact-match fixed pattern against the - * test name itself will not yield any matches. - *
      - * Previous filter value will be overwritten on each call! - * - * @public - * @see [CLI option](../#-grep-regexp-g-regexp) - * @see {@link Mocha#fgrep} - * @see {@link Mocha#invert} - * @param {RegExp|String} re - Regular expression used to select tests. - * @return {Mocha} this - * @chainable - * @example - * - * // Select tests whose full title contains `"match"`, ignoring case - * mocha.grep(/match/i); - * @example - * - * // Same as above but with regexp-like string argument - * mocha.grep('/match/i'); - * @example - * - * // ## Anti-example - * // Given embedded test `it('only-this-test')`... - * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this! - */ - - - Mocha.prototype.grep = function (re) { - if (utils.isString(re)) { - // extract args if it's regex-like, i.e: [string, pattern, flag] - var arg = re.match(/^\/(.*)\/(g|i|)$|.*/); - this.options.grep = new RegExp(arg[1] || arg[0], arg[2]); - } else { - this.options.grep = re; - } - - return this; - }; - /** - * Inverts `grep` matches. - * - * @public - * @see {@link Mocha#grep} - * @return {Mocha} this - * @chainable - * @example - * - * // Select tests whose full title does *not* contain `"match"`, ignoring case - * mocha.grep(/match/i).invert(); - */ - - - Mocha.prototype.invert = function () { - this.options.invert = true; - return this; - }; - /** - * Enables or disables checking for global variables leaked while running tests. - * - * @public - * @see [CLI option](../#-check-leaks) - * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.checkLeaks = function (checkLeaks) { - this.options.checkLeaks = checkLeaks !== false; - return this; - }; - /** - * Enables or disables whether or not to dispose after each test run. - * Disable this to ensure you can run the test suite multiple times. - * If disabled, be sure to dispose mocha when you're done to prevent memory leaks. - * @public - * @see {@link Mocha#dispose} - * @param {boolean} cleanReferencesAfterRun - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) { - this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false; - return this; - }; - /** - * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests. - * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector. - * @public - */ - - - Mocha.prototype.dispose = function () { - if (this._state === mochaStates.RUNNING) { - throw createMochaInstanceAlreadyRunningError('Cannot dispose while the mocha instance is still running tests.'); - } - - this.unloadFiles(); - this._previousRunner && this._previousRunner.dispose(); - this.suite.dispose(); - this._state = mochaStates.DISPOSED; - }; - /** - * Displays full stack trace upon test failure. - * - * @public - * @see [CLI option](../#-full-trace) - * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.fullTrace = function (fullTrace) { - this.options.fullTrace = fullTrace !== false; - return this; - }; - /** - * Enables desktop notification support if prerequisite software installed. - * - * @public - * @see [CLI option](../#-growl-g) - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.growl = function () { - this.options.growl = this.isGrowlCapable(); - - if (!this.options.growl) { - var detail = utils.isBrowser() ? 'notification support not available in this browser...' : 'notification support prerequisites not installed...'; - console.error(detail + ' cannot enable!'); - } - - return this; - }; - /** - * @summary - * Determines if Growl support seems likely. - * - * @description - * Not available when run in browser. - * - * @private - * @see {@link Growl#isCapable} - * @see {@link Mocha#growl} - * @return {boolean} whether Growl support can be expected - */ - - - Mocha.prototype.isGrowlCapable = growl.isCapable; - /** - * Implements desktop notifications using a pseudo-reporter. - * - * @private - * @see {@link Mocha#growl} - * @see {@link Growl#notify} - * @param {Runner} runner - Runner instance. - */ - - Mocha.prototype._growl = growl.notify; - /** - * Specifies whitelist of variable names to be expected in global scope. - * - * @public - * @see [CLI option](../#-global-variable-name) - * @see {@link Mocha#checkLeaks} - * @param {String[]|String} global - Accepted global variable name(s). - * @return {Mocha} this - * @chainable - * @example - * - * // Specify variables to be expected in global scope - * mocha.global(['jQuery', 'MyLib']); - */ - - Mocha.prototype.global = function (global) { - this.options.global = (this.options.global || []).concat(global).filter(Boolean).filter(function (elt, idx, arr) { - return arr.indexOf(elt) === idx; - }); - return this; - }; // for backwards compability, 'globals' is an alias of 'global' - - - Mocha.prototype.globals = Mocha.prototype.global; - /** - * Enables or disables TTY color output by screen-oriented reporters. - * - * @public - * @see [CLI option](../#-color-c-colors) - * @param {boolean} [color=true] - Whether to enable color output. - * @return {Mocha} this - * @chainable - */ - - Mocha.prototype.color = function (color) { - this.options.color = color !== false; - return this; - }; - /** - * Enables or disables reporter to use inline diffs (rather than +/-) - * in test failure output. - * - * @public - * @see [CLI option](../#-inline-diffs) - * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.inlineDiffs = function (inlineDiffs) { - this.options.inlineDiffs = inlineDiffs !== false; - return this; - }; - /** - * Enables or disables reporter to include diff in test failure output. - * - * @public - * @see [CLI option](../#-diff) - * @param {boolean} [diff=true] - Whether to show diff on failure. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.diff = function (diff) { - this.options.diff = diff !== false; - return this; - }; - /** - * @summary - * Sets timeout threshold value. - * - * @description - * A string argument can use shorthand (such as "2s") and will be converted. - * If the value is `0`, timeouts will be disabled. - * - * @public - * @see [CLI option](../#-timeout-ms-t-ms) - * @see [Timeouts](../#timeouts) - * @param {number|string} msecs - Timeout threshold value. - * @return {Mocha} this - * @chainable - * @example - * - * // Sets timeout to one second - * mocha.timeout(1000); - * @example - * - * // Same as above but using string argument - * mocha.timeout('1s'); - */ - - - Mocha.prototype.timeout = function (msecs) { - this.suite.timeout(msecs); - return this; - }; - /** - * Sets the number of times to retry failed tests. - * - * @public - * @see [CLI option](../#-retries-n) - * @see [Retry Tests](../#retry-tests) - * @param {number} retry - Number of times to retry failed tests. - * @return {Mocha} this - * @chainable - * @example - * - * // Allow any failed test to retry one more time - * mocha.retries(1); - */ - - - Mocha.prototype.retries = function (retry) { - this.suite.retries(retry); - return this; - }; - /** - * Sets slowness threshold value. - * - * @public - * @see [CLI option](../#-slow-ms-s-ms) - * @param {number} msecs - Slowness threshold value. - * @return {Mocha} this - * @chainable - * @example - * - * // Sets "slow" threshold to half a second - * mocha.slow(500); - * @example - * - * // Same as above but using string argument - * mocha.slow('0.5s'); - */ - - - Mocha.prototype.slow = function (msecs) { - this.suite.slow(msecs); - return this; - }; - /** - * Forces all tests to either accept a `done` callback or return a promise. - * - * @public - * @see [CLI option](../#-async-only-a) - * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.asyncOnly = function (asyncOnly) { - this.options.asyncOnly = asyncOnly !== false; - return this; - }; - /** - * Disables syntax highlighting (in browser). - * - * @public - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.noHighlighting = function () { - this.options.noHighlighting = true; - return this; - }; - /** - * Enables or disables uncaught errors to propagate. - * - * @public - * @see [CLI option](../#-allow-uncaught) - * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors. - * @return {Mocha} this - * @chainable - */ - - - Mocha.prototype.allowUncaught = function (allowUncaught) { - this.options.allowUncaught = allowUncaught !== false; - return this; - }; - /** - * @summary - * Delays root suite execution. - * - * @description - * Used to perform async operations before any suites are run. - * - * @public - * @see [delayed root suite](../#delayed-root-suite) - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.delay = function delay() { - this.options.delay = true; - return this; - }; - /** - * Causes tests marked `only` to fail the suite. - * - * @public - * @see [CLI option](../#-forbid-only) - * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite. - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.forbidOnly = function (forbidOnly) { - this.options.forbidOnly = forbidOnly !== false; - return this; - }; - /** - * Causes pending tests and tests marked `skip` to fail the suite. - * - * @public - * @see [CLI option](../#-forbid-pending) - * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite. - * @returns {Mocha} this - * @chainable - */ - - - Mocha.prototype.forbidPending = function (forbidPending) { - this.options.forbidPending = forbidPending !== false; - return this; - }; - /** - * Throws an error if mocha is in the wrong state to be able to transition to a "running" state. - * @private - */ - - - Mocha.prototype._guardRunningStateTransition = function () { - if (this._state === mochaStates.RUNNING) { - throw createMochaInstanceAlreadyRunningError('Mocha instance is currently running tests, cannot start a next test run until this one is done', this); - } - - if (this._state === mochaStates.DISPOSED || this._state === mochaStates.REFERENCES_CLEANED) { - throw createMochaInstanceAlreadyDisposedError('Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.', this._cleanReferencesAfterRun, this); - } - }; - /** - * Mocha version as specified by "package.json". - * - * @name Mocha#version - * @type string - * @readonly - */ - - - Object.defineProperty(Mocha.prototype, 'version', { - value: require$$10.version, - configurable: false, - enumerable: true, - writable: false - }); - /** - * Callback to be invoked when test execution is complete. - * - * @private - * @callback DoneCB - * @param {number} failures - Number of failures that occurred. - */ - - /** - * Runs root suite and invokes `fn()` when complete. - * - * @description - * To run tests multiple times (or to run tests in files that are - * already in the `require` cache), make sure to clear them from - * the cache first! - * - * @public - * @see {@link Mocha#unloadFiles} - * @see {@link Runner#run} - * @param {DoneCB} [fn] - Callback invoked when test execution completed. - * @returns {Runner} runner instance - * @example - * - * // exit with non-zero status if there were test failures - * mocha.run(failures => process.exitCode = failures ? 1 : 0); - */ - - Mocha.prototype.run = function (fn) { - var _this = this; - - this._guardRunningStateTransition(); - - this._state = mochaStates.RUNNING; - - if (this._previousRunner) { - this._previousRunner.dispose(); - - this.suite.reset(); - } - - if (this.files.length && !this._lazyLoadFiles) { - this.loadFiles(); - } - - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new this._runnerClass(suite, { - delay: options.delay, - cleanReferencesAfterRun: this._cleanReferencesAfterRun - }); - statsCollector(runner); - var reporter = new this._reporter(runner, options); - runner.checkLeaks = options.checkLeaks === true; - runner.fullStackTrace = options.fullTrace; - runner.asyncOnly = options.asyncOnly; - runner.allowUncaught = options.allowUncaught; - runner.forbidOnly = options.forbidOnly; - runner.forbidPending = options.forbidPending; - - if (options.grep) { - runner.grep(options.grep, options.invert); - } - - if (options.global) { - runner.globals(options.global); - } - - if (options.growl) { - this._growl(runner); - } - - if (options.color !== undefined) { - exports.reporters.Base.useColors = options.color; - } - - exports.reporters.Base.inlineDiffs = options.inlineDiffs; - exports.reporters.Base.hideDiff = !options.diff; - - var done = function done(failures) { - _this._previousRunner = runner; - _this._state = _this._cleanReferencesAfterRun ? mochaStates.REFERENCES_CLEANED : mochaStates.INIT; - fn = fn || utils.noop; - - if (typeof reporter.done === 'function') { - reporter.done(failures, fn); - } else { - fn(failures); - } - }; - - var runAsync = /*#__PURE__*/function () { - var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(runner) { - var context, failureCount; - return regeneratorRuntime.wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!(_this.options.enableGlobalSetup && _this.hasGlobalSetupFixtures())) { - _context.next = 6; - break; - } - - _context.next = 3; - return _this.runGlobalSetup(runner); - - case 3: - _context.t0 = _context.sent; - _context.next = 7; - break; - - case 6: - _context.t0 = {}; - - case 7: - context = _context.t0; - _context.next = 10; - return runner.runAsync({ - files: _this.files, - options: options - }); - - case 10: - failureCount = _context.sent; - - if (!(_this.options.enableGlobalTeardown && _this.hasGlobalTeardownFixtures())) { - _context.next = 14; - break; - } - - _context.next = 14; - return _this.runGlobalTeardown(runner, { - context: context - }); - - case 14: - return _context.abrupt("return", failureCount); - - case 15: - case "end": - return _context.stop(); - } - } - }, _callee); - })); - - return function runAsync(_x) { - return _ref.apply(this, arguments); - }; - }(); // no "catch" here is intentional. errors coming out of - // Runner#run are considered uncaught/unhandled and caught - // by the `process` event listeners. - // also: returning anything other than `runner` would be a breaking - // change - - - runAsync(runner).then(done); - return runner; - }; - /** - * Assigns hooks to the root suite - * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite - * @chainable - */ - - - Mocha.prototype.rootHooks = function rootHooks() { - var _this2 = this; - - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref2$beforeAll = _ref2.beforeAll, - beforeAll = _ref2$beforeAll === void 0 ? [] : _ref2$beforeAll, - _ref2$beforeEach = _ref2.beforeEach, - beforeEach = _ref2$beforeEach === void 0 ? [] : _ref2$beforeEach, - _ref2$afterAll = _ref2.afterAll, - afterAll = _ref2$afterAll === void 0 ? [] : _ref2$afterAll, - _ref2$afterEach = _ref2.afterEach, - afterEach = _ref2$afterEach === void 0 ? [] : _ref2$afterEach; - - beforeAll = utils.castArray(beforeAll); - beforeEach = utils.castArray(beforeEach); - afterAll = utils.castArray(afterAll); - afterEach = utils.castArray(afterEach); - beforeAll.forEach(function (hook) { - _this2.suite.beforeAll(hook); - }); - beforeEach.forEach(function (hook) { - _this2.suite.beforeEach(hook); - }); - afterAll.forEach(function (hook) { - _this2.suite.afterAll(hook); - }); - afterEach.forEach(function (hook) { - _this2.suite.afterEach(hook); - }); - return this; - }; - /** - * Toggles parallel mode. - * - * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to - * use; also enables lazy file loading if not already done so. - * - * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel - * mode, but parallel mode is _not_ a prerequisite for lazy loading! - * @param {boolean} [enable] - If `true`, enable; otherwise disable. - * @throws If run in browser - * @throws If Mocha not in `INIT` state - * @returns {Mocha} - * @chainable - * @public - */ - - - Mocha.prototype.parallelMode = function parallelMode() { - var enable = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - - if (utils.isBrowser()) { - throw createUnsupportedError('parallel mode is only supported in Node.js'); - } - - var parallel = Boolean(enable); - - if (parallel === this.options.parallel && this._lazyLoadFiles && this._runnerClass !== exports.Runner) { - return this; - } - - if (this._state !== mochaStates.INIT) { - throw createUnsupportedError('cannot change parallel mode after having called run()'); - } - - this.options.parallel = parallel; // swap Runner class - - this._runnerClass = parallel ? require$$11 : exports.Runner; // lazyLoadFiles may have been set `true` otherwise (for ESM loading), - // so keep `true` if so. - - return this.lazyLoadFiles(this._lazyLoadFiles || parallel); - }; - /** - * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This - * setting is used by watch mode, parallel mode, and for loading ESM files. - * @todo This should throw if we've already loaded files; such behavior - * necessitates adding a new state. - * @param {boolean} [enable] - If `true`, disable eager loading of files in - * {@link Mocha#run} - * @chainable - * @public - */ - - - Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) { - this._lazyLoadFiles = enable === true; - debug('set lazy load to %s', enable); - return this; - }; - /** - * Configures one or more global setup fixtures. - * - * If given no parameters, _unsets_ any previously-set fixtures. - * @chainable - * @public - * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s) - * @returns {Mocha} - */ - - - Mocha.prototype.globalSetup = function globalSetup() { - var setupFns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - setupFns = utils.castArray(setupFns); - this.options.globalSetup = setupFns; - debug('configured %d global setup functions', setupFns.length); - return this; - }; - /** - * Configures one or more global teardown fixtures. - * - * If given no parameters, _unsets_ any previously-set fixtures. - * @chainable - * @public - * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s) - * @returns {Mocha} - */ - - - Mocha.prototype.globalTeardown = function globalTeardown() { - var teardownFns = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - teardownFns = utils.castArray(teardownFns); - this.options.globalTeardown = teardownFns; - debug('configured %d global teardown functions', teardownFns.length); - return this; - }; - /** - * Run any global setup fixtures sequentially, if any. - * - * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}. - * - * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}. - * @param {object} [context] - Context object if already have one - * @public - * @returns {Promise} Context object - */ - - - Mocha.prototype.runGlobalSetup = /*#__PURE__*/function () { - var _runGlobalSetup = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() { - var context, - globalSetup, - _args2 = arguments; - return regeneratorRuntime.wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - context = _args2.length > 0 && _args2[0] !== undefined ? _args2[0] : {}; - globalSetup = this.options.globalSetup; - - if (!(globalSetup && globalSetup.length)) { - _context2.next = 7; - break; - } - - debug('run(): global setup starting'); - _context2.next = 6; - return this._runGlobalFixtures(globalSetup, context); - - case 6: - debug('run(): global setup complete'); - - case 7: - return _context2.abrupt("return", context); - - case 8: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function runGlobalSetup() { - return _runGlobalSetup.apply(this, arguments); - } - - return runGlobalSetup; - }(); - /** - * Run any global teardown fixtures sequentially, if any. - * - * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}. - * - * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable. - * @param {object} [context] - Context object if already have one - * @public - * @returns {Promise} Context object - */ - - - Mocha.prototype.runGlobalTeardown = /*#__PURE__*/function () { - var _runGlobalTeardown = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { - var context, - globalTeardown, - _args3 = arguments; - return regeneratorRuntime.wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - context = _args3.length > 0 && _args3[0] !== undefined ? _args3[0] : {}; - globalTeardown = this.options.globalTeardown; - - if (!(globalTeardown && globalTeardown.length)) { - _context3.next = 6; - break; - } - - debug('run(): global teardown starting'); - _context3.next = 6; - return this._runGlobalFixtures(globalTeardown, context); - - case 6: - debug('run(): global teardown complete'); - return _context3.abrupt("return", context); - - case 8: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function runGlobalTeardown() { - return _runGlobalTeardown.apply(this, arguments); - } - - return runGlobalTeardown; - }(); - /** - * Run global fixtures sequentially with context `context` - * @private - * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run - * @param {object} [context] - context object - * @returns {Promise} context object - */ - - - Mocha.prototype._runGlobalFixtures = /*#__PURE__*/function () { - var _runGlobalFixtures2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() { - var fixtureFns, - context, - _iteratorNormalCompletion, - _didIteratorError, - _iteratorError, - _iterator, - _step, - _value, - fixtureFn, - _args4 = arguments; - - return regeneratorRuntime.wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - fixtureFns = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : []; - context = _args4.length > 1 && _args4[1] !== undefined ? _args4[1] : {}; - _iteratorNormalCompletion = true; - _didIteratorError = false; - _context4.prev = 4; - _iterator = _asyncIterator(fixtureFns); - - case 6: - _context4.next = 8; - return _iterator.next(); - - case 8: - _step = _context4.sent; - _iteratorNormalCompletion = _step.done; - _context4.next = 12; - return _step.value; - - case 12: - _value = _context4.sent; - - if (_iteratorNormalCompletion) { - _context4.next = 20; - break; - } - - fixtureFn = _value; - _context4.next = 17; - return fixtureFn.call(context); - - case 17: - _iteratorNormalCompletion = true; - _context4.next = 6; - break; - - case 20: - _context4.next = 26; - break; - - case 22: - _context4.prev = 22; - _context4.t0 = _context4["catch"](4); - _didIteratorError = true; - _iteratorError = _context4.t0; - - case 26: - _context4.prev = 26; - _context4.prev = 27; - - if (!(!_iteratorNormalCompletion && _iterator["return"] != null)) { - _context4.next = 31; - break; - } - - _context4.next = 31; - return _iterator["return"](); - - case 31: - _context4.prev = 31; - - if (!_didIteratorError) { - _context4.next = 34; - break; - } - - throw _iteratorError; - - case 34: - return _context4.finish(31); - - case 35: - return _context4.finish(26); - - case 36: - return _context4.abrupt("return", context); - - case 37: - case "end": - return _context4.stop(); - } - } - }, _callee4, null, [[4, 22, 26, 36], [27,, 31, 35]]); - })); - - function _runGlobalFixtures() { - return _runGlobalFixtures2.apply(this, arguments); - } - - return _runGlobalFixtures; - }(); - /** - * Toggle execution of any global setup fixture(s) - * - * @chainable - * @public - * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture - * @returns {Mocha} - */ - - - Mocha.prototype.enableGlobalSetup = function enableGlobalSetup() { - var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - this.options.enableGlobalSetup = Boolean(enabled); - return this; - }; - /** - * Toggle execution of any global teardown fixture(s) - * - * @chainable - * @public - * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture - * @returns {Mocha} - */ - - - Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown() { - var enabled = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - this.options.enableGlobalTeardown = Boolean(enabled); - return this; - }; - /** - * Returns `true` if one or more global setup fixtures have been supplied. - * @public - * @returns {boolean} - */ - - - Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() { - return Boolean(this.options.globalSetup.length); - }; - /** - * Returns `true` if one or more global teardown fixtures have been supplied. - * @public - * @returns {boolean} - */ - - - Mocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures() { - return Boolean(this.options.globalTeardown.length); - }; - /** - * An alternative way to define root hooks that works with parallel runs. - * @typedef {Object} MochaRootHookObject - * @property {Function|Function[]} [beforeAll] - "Before all" hook(s) - * @property {Function|Function[]} [beforeEach] - "Before each" hook(s) - * @property {Function|Function[]} [afterAll] - "After all" hook(s) - * @property {Function|Function[]} [afterEach] - "After each" hook(s) - */ - - /** - * An function that returns a {@link MochaRootHookObject}, either sync or async. - @callback MochaRootHookFunction - * @returns {MochaRootHookObject|Promise} - */ - - /** - * A function that's invoked _once_ which is either sync or async. - * Can be a "teardown" or "setup". These will all share the same context. - * @callback MochaGlobalFixture - * @returns {void|Promise} - */ - - /** - * An object making up all necessary parts of a plugin loader and aggregator - * @typedef {Object} PluginDefinition - * @property {string} exportName - Named export to use - * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted) - * @property {PluginValidator} [validate] - Validator function - * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function - */ - - /** - * A (sync) function to assert a user-supplied plugin implementation is valid. - * - * Defined in a {@link PluginDefinition}. - - * @callback PluginValidator - * @param {*} value - Value to check - * @this {PluginDefinition} - * @returns {void} - */ - - /** - * A function to finalize plugins impls of a particular ilk - * @callback PluginFinalizer - * @param {Array<*>} impls - User-supplied implementations - * @returns {Promise<*>|*} - */ - - }); - - /* eslint no-unused-vars: off */ - - /* eslint-env commonjs */ - - /** - * Shim process.stdout. - */ - - - process$1.stdout = browserStdout({ - label: false - }); - /** - * Create a Mocha instance. - * - * @return {undefined} - */ - - var mocha$1 = new mocha({ - reporter: 'html' - }); - /** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - - var Date$4 = commonjsGlobal.Date; - var setTimeout$3 = commonjsGlobal.setTimeout; - var uncaughtExceptionHandlers = []; - var originalOnerrorHandler = commonjsGlobal.onerror; - /** - * Remove uncaughtException listener. - * Revert to original onerror handler if previously defined. - */ - - process$1.removeListener = function (e, fn) { - if (e === 'uncaughtException') { - if (originalOnerrorHandler) { - commonjsGlobal.onerror = originalOnerrorHandler; - } else { - commonjsGlobal.onerror = function () {}; - } - - var i = uncaughtExceptionHandlers.indexOf(fn); - - if (i !== -1) { - uncaughtExceptionHandlers.splice(i, 1); - } - } - }; - /** - * Implements listenerCount for 'uncaughtException'. - */ - - - process$1.listenerCount = function (name) { - if (name === 'uncaughtException') { - return uncaughtExceptionHandlers.length; - } - - return 0; - }; - /** - * Implements uncaughtException listener. - */ - - - process$1.on = function (e, fn) { - if (e === 'uncaughtException') { - commonjsGlobal.onerror = function (err, url, line) { - fn(new Error(err + ' (' + url + ':' + line + ')')); - return !mocha$1.options.allowUncaught; - }; - - uncaughtExceptionHandlers.push(fn); - } - }; - - process$1.listeners = function (e) { - if (e === 'uncaughtException') { - return uncaughtExceptionHandlers; - } - - return []; - }; // The BDD UI is registered by default, but no UI will be functional in the - // browser without an explicit call to the overridden `mocha.ui` (see below). - // Ensure that this default UI does not expose its methods to the global scope. - - - mocha$1.suite.removeAllListeners('pre-require'); - var immediateQueue = []; - var immediateTimeout; - - function timeslice() { - var immediateStart = new Date$4().getTime(); - - while (immediateQueue.length && new Date$4().getTime() - immediateStart < 100) { - immediateQueue.shift()(); - } - - if (immediateQueue.length) { - immediateTimeout = setTimeout$3(timeslice, 0); - } else { - immediateTimeout = null; - } - } - /** - * High-performance override of Runner.immediately. - */ - - - mocha.Runner.immediately = function (callback) { - immediateQueue.push(callback); - - if (!immediateTimeout) { - immediateTimeout = setTimeout$3(timeslice, 0); - } - }; - /** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. - */ - - - mocha$1.throwError = function (err) { - uncaughtExceptionHandlers.forEach(function (fn) { - fn(err); - }); - throw err; - }; - /** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - - - mocha$1.ui = function (ui) { - mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', commonjsGlobal, null, this); - return this; - }; - /** - * Setup mocha with the given setting options. - */ - - - mocha$1.setup = function (opts) { - if (typeof opts === 'string') { - opts = { - ui: opts - }; - } - - if (opts.delay === true) { - this.delay(); - } - - var self = this; - Object.keys(opts).filter(function (opt) { - return opt !== 'delay'; - }).forEach(function (opt) { - if (Object.prototype.hasOwnProperty.call(opts, opt)) { - self[opt](opts[opt]); - } - }); - return this; - }; - /** - * Run mocha, returning the Runner. - */ - - - mocha$1.run = function (fn) { - var options = mocha$1.options; - mocha$1.globals('location'); - var query = parseQuery(commonjsGlobal.location.search || ''); - - if (query.grep) { - mocha$1.grep(query.grep); - } - - if (query.fgrep) { - mocha$1.fgrep(query.fgrep); - } - - if (query.invert) { - mocha$1.invert(); - } - - return mocha.prototype.run.call(mocha$1, function (err) { - // The DOM Document is not available in Web Workers. - var document = commonjsGlobal.document; - - if (document && document.getElementById('mocha') && options.noHighlighting !== true) { - highlightTags('code'); - } - - if (fn) { - fn(err); - } - }); - }; - /** - * Expose the process shim. - * https://github.com/mochajs/mocha/pull/916 - */ - - - mocha.process = process$1; - /** - * Expose mocha. - */ - - commonjsGlobal.Mocha = mocha; - commonjsGlobal.mocha = mocha$1; // this allows test/acceptance/required-tokens.js to pass; thus, - // you can now do `const describe = require('mocha').describe` in a - // browser context (assuming browserification). should fix #880 - - var browserEntry = Object.assign(mocha$1, commonjsGlobal); - - return browserEntry; - -}))); + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.mocha = factory()); +})(this, (function () { 'use strict'; + + var global$2 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var global$1 = (typeof global$2 !== "undefined" ? global$2 : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout$1() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout$1 () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout$1 = defaultSetTimout$1; + var cachedClearTimeout$1 = defaultClearTimeout$1; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout$1 = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout$1 = clearTimeout; + } + + function runTimeout$1(fun) { + if (cachedSetTimeout$1 === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout$1 === defaultSetTimout$1 || !cachedSetTimeout$1) && setTimeout) { + cachedSetTimeout$1 = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout$1(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout$1.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout$1.call(this, fun, 0); + } + } + + + } + function runClearTimeout$1(marker) { + if (cachedClearTimeout$1 === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout$1 === defaultClearTimeout$1 || !cachedClearTimeout$1) && clearTimeout) { + cachedClearTimeout$1 = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout$1(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout$1.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout$1.call(this, marker); + } + } + + + + } + var queue$1 = []; + var draining$1 = false; + var currentQueue$1; + var queueIndex$1 = -1; + + function cleanUpNextTick$1() { + if (!draining$1 || !currentQueue$1) { + return; + } + draining$1 = false; + if (currentQueue$1.length) { + queue$1 = currentQueue$1.concat(queue$1); + } else { + queueIndex$1 = -1; + } + if (queue$1.length) { + drainQueue$1(); + } + } + + function drainQueue$1() { + if (draining$1) { + return; + } + var timeout = runTimeout$1(cleanUpNextTick$1); + draining$1 = true; + + var len = queue$1.length; + while(len) { + currentQueue$1 = queue$1; + queue$1 = []; + while (++queueIndex$1 < len) { + if (currentQueue$1) { + currentQueue$1[queueIndex$1].run(); + } + } + queueIndex$1 = -1; + len = queue$1.length; + } + currentQueue$1 = null; + draining$1 = false; + runClearTimeout$1(timeout); + } + function nextTick$1(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue$1.push(new Item$1(fun, args)); + if (queue$1.length === 1 && !draining$1) { + runTimeout$1(drainQueue$1); + } + } + // v8 likes predictible objects + function Item$1(fun, array) { + this.fun = fun; + this.array = array; + } + Item$1.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title$1 = 'browser'; + var platform$1 = 'browser'; + var browser$4 = true; + var env$1 = {}; + var argv$1 = []; + var version$2 = ''; // empty string to avoid regexp issues + var versions$1 = {}; + var release$1 = {}; + var config$1 = {}; + + function noop$1() {} + + var on$1 = noop$1; + var addListener$1 = noop$1; + var once$1 = noop$1; + var off$1 = noop$1; + var removeListener$1 = noop$1; + var removeAllListeners$1 = noop$1; + var emit$1 = noop$1; + + function binding$1(name) { + throw new Error('process.binding is not supported'); + } + + function cwd$1 () { return '/' } + function chdir$1 (dir) { + throw new Error('process.chdir is not supported'); + }function umask$1() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance$1 = global$1.performance || {}; + var performanceNow$1 = + performance$1.now || + performance$1.mozNow || + performance$1.msNow || + performance$1.oNow || + performance$1.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime$1(previousTimestamp){ + var clocktime = performanceNow$1.call(performance$1)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime$1 = new Date(); + function uptime$1() { + var currentTime = new Date(); + var dif = currentTime - startTime$1; + return dif / 1000; + } + + var process = { + nextTick: nextTick$1, + title: title$1, + browser: browser$4, + env: env$1, + argv: argv$1, + version: version$2, + versions: versions$1, + on: on$1, + addListener: addListener$1, + once: once$1, + off: off$1, + removeListener: removeListener$1, + removeAllListeners: removeAllListeners$1, + emit: emit$1, + binding: binding$1, + cwd: cwd$1, + chdir: chdir$1, + umask: umask$1, + hrtime: hrtime$1, + platform: platform$1, + release: release$1, + config: config$1, + uptime: uptime$1 + }; + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; + } + + function commonjsRequire (path) { + throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.'); + } + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter$2() { + EventEmitter$2.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter$2.EventEmitter = EventEmitter$2; + + EventEmitter$2.usingDomains = false; + + EventEmitter$2.prototype.domain = undefined; + EventEmitter$2.prototype._events = undefined; + EventEmitter$2.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter$2.defaultMaxListeners = 10; + + EventEmitter$2.init = function() { + this.domain = null; + if (EventEmitter$2.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter$2.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter$2.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter$2.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter$2.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning$1(w); + } + } + } + + return target; + } + function emitWarning$1(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter$2.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter$2.prototype.on = EventEmitter$2.prototype.addListener; + + EventEmitter$2.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter$2.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter$2.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter$2.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + // Alias for removeListener added in NodeJS 10.0 + // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener + EventEmitter$2.prototype.off = function(type, listener){ + return this.removeListener(type, listener); + }; + + EventEmitter$2.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter$2.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter$2.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter$2.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter$2.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var _polyfillNode_events = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': EventEmitter$2, + EventEmitter: EventEmitter$2 + }); + + var lookup$1 = []; + var revLookup$1 = []; + var Arr$1 = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited$1 = false; + function init$1 () { + inited$1 = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup$1[i] = code[i]; + revLookup$1[code.charCodeAt(i)] = i; + } + + revLookup$1['-'.charCodeAt(0)] = 62; + revLookup$1['_'.charCodeAt(0)] = 63; + } + + function toByteArray$1 (b64) { + if (!inited$1) { + init$1(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr$1(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup$1[b64.charCodeAt(i)] << 18) | (revLookup$1[b64.charCodeAt(i + 1)] << 12) | (revLookup$1[b64.charCodeAt(i + 2)] << 6) | revLookup$1[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup$1[b64.charCodeAt(i)] << 2) | (revLookup$1[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup$1[b64.charCodeAt(i)] << 10) | (revLookup$1[b64.charCodeAt(i + 1)] << 4) | (revLookup$1[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64$1 (num) { + return lookup$1[num >> 18 & 0x3F] + lookup$1[num >> 12 & 0x3F] + lookup$1[num >> 6 & 0x3F] + lookup$1[num & 0x3F] + } + + function encodeChunk$1 (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64$1(tmp)); + } + return output.join('') + } + + function fromByteArray$1 (uint8) { + if (!inited$1) { + init$1(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk$1(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup$1[tmp >> 2]; + output += lookup$1[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup$1[tmp >> 10]; + output += lookup$1[(tmp >> 4) & 0x3F]; + output += lookup$1[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read$1 (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write$1 (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString$2 = {}.toString; + + var isArray$2 = Array.isArray || function (arr) { + return toString$2.call(arr) == '[object Array]'; + }; + + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + + var INSPECT_MAX_BYTES$1 = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer$1.TYPED_ARRAY_SUPPORT = global$2.TYPED_ARRAY_SUPPORT !== undefined + ? global$2.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength$1(); + + function kMaxLength$1 () { + return Buffer$1.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer$1 (that, length) { + if (kMaxLength$1() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer$1(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer$1 (arg, encodingOrOffset, length) { + if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { + return new Buffer$1(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe$1(this, arg) + } + return from$1(this, arg, encodingOrOffset, length) + } + + Buffer$1.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer$1._augment = function (arr) { + arr.__proto__ = Buffer$1.prototype; + return arr + }; + + function from$1 (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer$1(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString$1(that, value, encodingOrOffset) + } + + return fromObject$1(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer$1.from = function (value, encodingOrOffset, length) { + return from$1(null, value, encodingOrOffset, length) + }; + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + Buffer$1.prototype.__proto__ = Uint8Array.prototype; + Buffer$1.__proto__ = Uint8Array; + } + + function assertSize$1 (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc$1 (that, size, fill, encoding) { + assertSize$1(size); + if (size <= 0) { + return createBuffer$1(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer$1(that, size).fill(fill, encoding) + : createBuffer$1(that, size).fill(fill) + } + return createBuffer$1(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer$1.alloc = function (size, fill, encoding) { + return alloc$1(null, size, fill, encoding) + }; + + function allocUnsafe$1 (that, size) { + assertSize$1(size); + that = createBuffer$1(that, size < 0 ? 0 : checked$1(size) | 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer$1.allocUnsafe = function (size) { + return allocUnsafe$1(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer$1.allocUnsafeSlow = function (size) { + return allocUnsafe$1(null, size) + }; + + function fromString$1 (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer$1.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength$1(string, encoding) | 0; + that = createBuffer$1(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike$1 (that, array) { + var length = array.length < 0 ? 0 : checked$1(array.length) | 0; + that = createBuffer$1(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer$1 (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer$1.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike$1(that, array); + } + return that + } + + function fromObject$1 (that, obj) { + if (internalIsBuffer$1(obj)) { + var len = checked$1(obj.length) | 0; + that = createBuffer$1(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan$1(obj.length)) { + return createBuffer$1(that, 0) + } + return fromArrayLike$1(that, obj) + } + + if (obj.type === 'Buffer' && isArray$2(obj.data)) { + return fromArrayLike$1(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked$1 (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength$1()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength$1().toString(16) + ' bytes') + } + return length | 0 + } + Buffer$1.isBuffer = isBuffer$2; + function internalIsBuffer$1 (b) { + return !!(b != null && b._isBuffer) + } + + Buffer$1.compare = function compare (a, b) { + if (!internalIsBuffer$1(a) || !internalIsBuffer$1(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer$1.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer$1.concat = function concat (list, length) { + if (!isArray$2(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer$1.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer$1.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer$1(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength$1 (string, encoding) { + if (internalIsBuffer$1(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes$1(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes$1(string).length + default: + if (loweredCase) return utf8ToBytes$1(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer$1.byteLength = byteLength$1; + + function slowToString$1 (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice$1(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice$1(this, start, end) + + case 'ascii': + return asciiSlice$1(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice$1(this, start, end) + + case 'base64': + return base64Slice$1(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice$1(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer$1.prototype._isBuffer = true; + + function swap$1 (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer$1.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap$1(this, i, i + 1); + } + return this + }; + + Buffer$1.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap$1(this, i, i + 3); + swap$1(this, i + 1, i + 2); + } + return this + }; + + Buffer$1.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap$1(this, i, i + 7); + swap$1(this, i + 1, i + 6); + swap$1(this, i + 2, i + 5); + swap$1(this, i + 3, i + 4); + } + return this + }; + + Buffer$1.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice$1(this, 0, length) + return slowToString$1.apply(this, arguments) + }; + + Buffer$1.prototype.equals = function equals (b) { + if (!internalIsBuffer$1(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer$1.compare(this, b) === 0 + }; + + Buffer$1.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES$1; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer$1(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf$1 (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer$1.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer$1(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf$1(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer$1.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf$1(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf$1 (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf$1(this, val, byteOffset, encoding, true) + }; + + Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf$1(this, val, byteOffset, encoding, false) + }; + + function hexWrite$1 (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write$1 (buf, string, offset, length) { + return blitBuffer$1(utf8ToBytes$1(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite$1 (buf, string, offset, length) { + return blitBuffer$1(asciiToBytes$1(string), buf, offset, length) + } + + function latin1Write$1 (buf, string, offset, length) { + return asciiWrite$1(buf, string, offset, length) + } + + function base64Write$1 (buf, string, offset, length) { + return blitBuffer$1(base64ToBytes$1(string), buf, offset, length) + } + + function ucs2Write$1 (buf, string, offset, length) { + return blitBuffer$1(utf16leToBytes$1(string, buf.length - offset), buf, offset, length) + } + + Buffer$1.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite$1(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write$1(this, string, offset, length) + + case 'ascii': + return asciiWrite$1(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write$1(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write$1(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write$1(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer$1.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice$1 (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray$1(buf) + } else { + return fromByteArray$1(buf.slice(start, end)) + } + } + + function utf8Slice$1 (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray$1(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH$1 = 0x1000; + + function decodeCodePointsArray$1 (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH$1) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH$1) + ); + } + return res + } + + function asciiSlice$1 (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice$1 (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice$1 (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex$1(buf[i]); + } + return out + } + + function utf16leSlice$1 (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer$1.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer$1.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer$1(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset$1 (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset$1(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 1, this.length); + return this[offset] + }; + + Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset$1(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + return read$1(this, offset, true, 23, 4) + }; + + Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 4, this.length); + return read$1(this, offset, false, 23, 4) + }; + + Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 8, this.length); + return read$1(this, offset, true, 52, 8) + }; + + Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset$1(offset, 8, this.length); + return read$1(this, offset, false, 52, 8) + }; + + function checkInt$1 (buf, value, offset, ext, max, min) { + if (!internalIsBuffer$1(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt$1(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt$1(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 1, 0xff, 0); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16$1 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16$1(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0xffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16$1(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32$1 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0xffffffff, 0); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, false); + } + return offset + 4 + }; + + Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt$1(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt$1(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16$1(this, value, offset, true); + } + return offset + 2 + }; + + Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16$1(this, value, offset, false); + } + return offset + 2 + }; + + Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32$1(this, value, offset, true); + } + return offset + 4 + }; + + Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt$1(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer$1.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32$1(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754$1 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat$1 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754$1(buf, value, offset, 4); + } + write$1(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat$1(this, value, offset, true, noAssert) + }; + + Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat$1(this, value, offset, false, noAssert) + }; + + function writeDouble$1 (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754$1(buf, value, offset, 8); + } + write$1(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble$1(this, value, offset, true, noAssert) + }; + + Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble$1(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer$1.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer$1(val) + ? val + : utf8ToBytes$1(new Buffer$1(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE$1 = /[^+\/0-9A-Za-z-_]/g; + + function base64clean$1 (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim$1(str).replace(INVALID_BASE64_RE$1, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim$1 (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex$1 (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes$1 (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes$1 (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes$1 (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes$1 (str) { + return toByteArray$1(base64clean$1(str)) + } + + function blitBuffer$1 (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan$1 (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$2(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer$1(obj) || isSlowBuffer$1(obj)) + } + + function isFastBuffer$1 (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer$1 (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer$1(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$2.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$2.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$3 = true; + var env = {}; + var argv = []; + var version$1 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$2.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var browser$1$1 = { + nextTick: nextTick, + title: title, + browser: browser$3, + env: env, + argv: argv, + version: version$1, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits$2; + if (typeof Object.create === 'function'){ + inherits$2 = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits$2 = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$3 = inherits$2; + + var formatRegExp = /%[sdj%]/g; + function format$1(f) { + if (!isString$1(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate$1(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$2.process)) { + return function() { + return deprecate$1(fn, msg).apply(this, arguments); + }; + } + + if (browser$1$1.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (browser$1$1.throwDeprecation) { + throw new Error(msg); + } else if (browser$1$1.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = browser$1$1.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format$1.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString$1(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError$1(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError$1(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray$1(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError$1(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString$1(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$1(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString$1(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError$1(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer$1(maybeBuf) { + return Buffer$1.isBuffer(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format$1.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var _polyfillNode_util = { + inherits: inherits$3, + _extend: _extend, + log: log, + isBuffer: isBuffer$1, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError$1, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString$1, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$1, + inspect: inspect, + deprecate: deprecate$1, + format: format$1, + debuglog: debuglog + }; + + var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + format: format$1, + deprecate: deprecate$1, + debuglog: debuglog, + inspect: inspect, + isArray: isArray$1, + isBoolean: isBoolean, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined, + isNumber: isNumber, + isString: isString$1, + isSymbol: isSymbol, + isUndefined: isUndefined, + isRegExp: isRegExp, + isObject: isObject, + isDate: isDate, + isError: isError$1, + isFunction: isFunction, + isPrimitive: isPrimitive, + isBuffer: isBuffer$1, + log: log, + inherits: inherits$3, + _extend: _extend, + 'default': _polyfillNode_util + }); + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer$1.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer$1.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node contributors. + var isBufferEncoding = Buffer$1.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer$1(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug$2 = debuglog('stream'); + inherits$3(Readable, EventEmitter$2); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter$2.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer$1.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug$2('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug$2('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug$2('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug$2('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug$2('reading or ended', doRead); + } else if (doRead) { + debug$2('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug$2('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug$2('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug$2('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug$2('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug$2('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug$2('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug$2('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug$2('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug$2('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug$2('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug$2('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug$2('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug$2('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug$2('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter$2.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug$2('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug$2('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug$2('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug$2('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug$2('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug$2('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug$2('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug$2('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug$2('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer$1.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + Writable.WritableState = WritableState; + inherits$3(Writable, EventEmitter$2); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate$1(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter$2.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer$1.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$3(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + inherits$3(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$3(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$3(Stream, EventEmitter$2); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter$2.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter$2.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + var _polyfillNode_stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': Stream, + Readable: Readable, + Writable: Writable, + Duplex: Duplex, + Transform: Transform, + PassThrough: PassThrough, + Stream: Stream + }); + + var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_stream); + + var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1); + + var WritableStream = require$$0$2.Writable; + var inherits$1 = require$$0$1.inherits; + + var browserStdout = BrowserStdout; + + + inherits$1(BrowserStdout, WritableStream); + + function BrowserStdout(opts) { + if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts) + + opts = opts || {}; + WritableStream.call(this, opts); + this.label = (opts.label !== undefined) ? opts.label : 'stdout'; + } + + BrowserStdout.prototype._write = function(chunks, encoding, cb) { + var output = chunks.toString ? chunks.toString() : chunks; + if (this.label === false) { + console.log(output); + } else { + console.log(this.label+':', output); + } + nextTick$1(cb); + }; + + /** + * Parse the given `qs`. + * + * @private + * @param {string} qs + * @return {Object} + */ + var parseQuery$1 = function parseQuery(qs) { + return qs + .replace('?', '') + .split('&') + .reduce(function (obj, pair) { + var i = pair.indexOf('='); + var key = pair.slice(0, i); + var val = pair.slice(++i); + + // Due to how the URLSearchParams API treats spaces + obj[key] = decodeURIComponent(val.replace(/\+/g, '%20')); + + return obj; + }, {}); + }; + + /** + * Highlight the given string of `js`. + * + * @private + * @param {string} js + * @return {string} + */ + function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace( + /\bnew[ \t]+(\w+)/gm, + 'new $1' + ) + .replace( + /\b(function|new|throw|return|var|if|else)\b/gm, + '$1' + ); + } + + /** + * Highlight the contents of tag `name`. + * + * @private + * @param {string} name + */ + var highlightTags$1 = function highlightTags(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } + }; + + var mocha$1 = {exports: {}}; + + var escapeStringRegexp = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } + + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); + }; + + // Copyright Joyent, Inc. and other Node 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. + + // resolves . and .. elements in a path array with directory names there + // must be no slashes, empty elements, or device names (c:\) in the array + // (so also no leading and trailing slashes - it does not distinguish + // relative and absolute paths) + function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } else if (last === '..') { + parts.splice(i, 1); + up++; + } else if (up) { + parts.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + for (; up--; up) { + parts.unshift('..'); + } + } + + return parts; + } + + // Split a filename into [root, dir, basename, ext], unix version + // 'root' is just a slash, or nothing. + var splitPathRe = + /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; + var splitPath = function(filename) { + return splitPathRe.exec(filename).slice(1); + }; + + // path.resolve([from ...], to) + // posix version + function resolve() { + var resolvedPath = '', + resolvedAbsolute = false; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = (i >= 0) ? arguments[i] : '/'; + + // Skip empty and invalid entries + if (typeof path !== 'string') { + throw new TypeError('Arguments to path.resolve must be strings'); + } else if (!path) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { + return !!p; + }), !resolvedAbsolute).join('/'); + + return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; + } + // path.normalize(path) + // posix version + function normalize(path) { + var isPathAbsolute = isAbsolute(path), + trailingSlash = substr(path, -1) === '/'; + + // Normalize the path + path = normalizeArray(filter(path.split('/'), function(p) { + return !!p; + }), !isPathAbsolute).join('/'); + + if (!path && !isPathAbsolute) { + path = '.'; + } + if (path && trailingSlash) { + path += '/'; + } + + return (isPathAbsolute ? '/' : '') + path; + } + // posix version + function isAbsolute(path) { + return path.charAt(0) === '/'; + } + + // posix version + function join() { + var paths = Array.prototype.slice.call(arguments, 0); + return normalize(filter(paths, function(p, index) { + if (typeof p !== 'string') { + throw new TypeError('Arguments to path.join must be strings'); + } + return p; + }).join('/')); + } + + + // path.relative(from, to) + // posix version + function relative(from, to) { + from = resolve(from).substr(1); + to = resolve(to).substr(1); + + function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') break; + } + + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') break; + } + + if (start > end) return []; + return arr.slice(start, end - start + 1); + } + + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } + } + + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + + return outputParts.join('/'); + } + + var sep = '/'; + var delimiter = ':'; + + function dirname(path) { + var result = splitPath(path), + root = result[0], + dir = result[1]; + + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + + return root + dir; + } + + function basename(path, ext) { + var f = splitPath(path)[2]; + // TODO: make this comparison case-insensitive on windows? + if (ext && f.substr(-1 * ext.length) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; + } + + + function extname(path) { + return splitPath(path)[3]; + } + var _polyfillNode_path = { + extname: extname, + basename: basename, + dirname: dirname, + sep: sep, + delimiter: delimiter, + relative: relative, + join: join, + isAbsolute: isAbsolute, + normalize: normalize, + resolve: resolve + }; + function filter (xs, f) { + if (xs.filter) return xs.filter(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + if (f(xs[i], i, xs)) res.push(xs[i]); + } + return res; + } + + // String.prototype.substr - negative index don't work in IE8 + var substr = 'ab'.substr(-1) === 'b' ? + function (str, start, len) { return str.substr(start, len) } : + function (str, start, len) { + if (start < 0) start = str.length + start; + return str.substr(start, len); + } + ; + + var _polyfillNode_path$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + resolve: resolve, + normalize: normalize, + isAbsolute: isAbsolute, + join: join, + relative: relative, + sep: sep, + delimiter: delimiter, + dirname: dirname, + basename: basename, + extname: extname, + 'default': _polyfillNode_path + }); + + var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_path$1); + + var reporters = {}; + + var base$1 = {exports: {}}; + + var lib = {}; + + var base = {}; + + /*istanbul ignore start*/ + + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = Diff; + + /*istanbul ignore end*/ + function Diff() {} + + Diff.prototype = { + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + diff: function diff(oldString, newString) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var callback = options.callback; + + if (typeof options === 'function') { + callback = options; + options = {}; + } + + this.options = options; + var self = this; + + function done(value) { + if (callback) { + setTimeout(function () { + callback(undefined, value); + }, 0); + return true; + } else { + return value; + } + } // Allow subclasses to massage the input prior to running + + + oldString = this.castInput(oldString); + newString = this.castInput(newString); + oldString = this.removeEmpty(this.tokenize(oldString)); + newString = this.removeEmpty(this.tokenize(newString)); + var newLen = newString.length, + oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ + newPos: -1, + components: [] + }]; // Seed editLength = 0, i.e. the content starts with the same values + + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{ + value: this.join(newString), + count: newString.length + }]); + } // Main worker method. checks all permutations of a given edit length for acceptance. + + + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath = + /*istanbul ignore start*/ + void 0 + /*istanbul ignore end*/ + ; + + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen; + + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + + + if (!canAdd || canRemove && addPath.newPos < removePath.newPos) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done + + if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) { + return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + + + if (callback) { + (function exec() { + setTimeout(function () { + // This should not happen, but we want to be safe. + + /* istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + })(); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + + if (ret) { + return ret; + } + } + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + pushComponent: function pushComponent(components, added, removed) { + var last = components[components.length - 1]; + + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = { + count: last.count + 1, + added: added, + removed: removed + }; + } else { + components.push({ + count: 1, + added: added, + removed: removed + }); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + commonCount = 0; + + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({ + count: commonCount + }); + } + + basePath.newPos = newPos; + return oldPos; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + equals: function equals(left, right) { + if (this.options.comparator) { + return this.options.comparator(left, right); + } else { + return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase(); + } + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + removeEmpty: function removeEmpty(array) { + var ret = []; + + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + + return ret; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + castInput: function castInput(value) { + return value; + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + tokenize: function tokenize(value) { + return value.split(''); + }, + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + join: function join(chars) { + return chars.join(''); + } + }; + + function buildValues(diff, components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = value.map(function (value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + component.value = diff.join(value); + } else { + component.value = diff.join(newString.slice(newPos, newPos + component.count)); + } + + newPos += component.count; // Common case + + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = diff.join(oldString.slice(oldPos, oldPos + component.count)); + oldPos += component.count; // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } // Special case handle for when one terminal is ignored (i.e. whitespace). + // For this case we merge the terminal into the prior string and drop the change. + // This is only available for string mode. + + + var lastComponent = components[componentLen - 1]; + + if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) { + components[componentLen - 2].value += lastComponent.value; + components.pop(); + } + + return components; + } + + function clonePath(path) { + return { + newPos: path.newPos, + components: path.components.slice(0) + }; + } + + }(base)); + + var character = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(character, "__esModule", { + value: true + }); + character.diffChars = diffChars; + character.characterDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$6 = _interopRequireDefault$7(base) + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$7(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + var characterDiff = new + /*istanbul ignore start*/ + _base$6 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + character.characterDiff = characterDiff; + + /*istanbul ignore end*/ + function diffChars(oldStr, newStr, options) { + return characterDiff.diff(oldStr, newStr, options); + } + + var word = {}; + + var params = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(params, "__esModule", { + value: true + }); + params.generateOptions = generateOptions; + + /*istanbul ignore end*/ + function generateOptions(options, defaults) { + if (typeof options === 'function') { + defaults.callback = options; + } else if (options) { + for (var name in options) { + /* istanbul ignore else */ + if (options.hasOwnProperty(name)) { + defaults[name] = options[name]; + } + } + } + + return defaults; + } + + /*istanbul ignore start*/ + + Object.defineProperty(word, "__esModule", { + value: true + }); + word.diffWords = diffWords; + word.diffWordsWithSpace = diffWordsWithSpace; + word.wordDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$5 = _interopRequireDefault$6(base) + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _params$1 = params + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$6(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + // Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode + // + // Ranges and exceptions: + // Latin-1 Supplement, 0080–00FF + // - U+00D7 × Multiplication sign + // - U+00F7 ÷ Division sign + // Latin Extended-A, 0100–017F + // Latin Extended-B, 0180–024F + // IPA Extensions, 0250–02AF + // Spacing Modifier Letters, 02B0–02FF + // - U+02C7 ˇ ˇ Caron + // - U+02D8 ˘ ˘ Breve + // - U+02D9 ˙ ˙ Dot Above + // - U+02DA ˚ ˚ Ring Above + // - U+02DB ˛ ˛ Ogonek + // - U+02DC ˜ ˜ Small Tilde + // - U+02DD ˝ ˝ Double Acute Accent + // Latin Extended Additional, 1E00–1EFF + var extendedWordChars = /^[A-Za-z\xC0-\u02C6\u02C8-\u02D7\u02DE-\u02FF\u1E00-\u1EFF]+$/; + var reWhitespace = /\S/; + var wordDiff = new + /*istanbul ignore start*/ + _base$5 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + word.wordDiff = wordDiff; + + /*istanbul ignore end*/ + wordDiff.equals = function (left, right) { + if (this.options.ignoreCase) { + left = left.toLowerCase(); + right = right.toLowerCase(); + } + + return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right); + }; + + wordDiff.tokenize = function (value) { + // All whitespace symbols except newline group into one token, each newline - in separate token + var tokens = value.split(/([^\S\r\n]+|[()[\]{}'"\r\n]|\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set. + + for (var i = 0; i < tokens.length - 1; i++) { + // If we have an empty string in the next field and we have only word chars before and after, merge + if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) { + tokens[i] += tokens[i + 2]; + tokens.splice(i + 1, 2); + i--; + } + } + + return tokens; + }; + + function diffWords(oldStr, newStr, options) { + options = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _params$1 + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (options, { + ignoreWhitespace: true + }); + return wordDiff.diff(oldStr, newStr, options); + } + + function diffWordsWithSpace(oldStr, newStr, options) { + return wordDiff.diff(oldStr, newStr, options); + } + + var line = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(line, "__esModule", { + value: true + }); + line.diffLines = diffLines; + line.diffTrimmedLines = diffTrimmedLines; + line.lineDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$4 = _interopRequireDefault$5(base) + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _params = params + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$5(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + var lineDiff = new + /*istanbul ignore start*/ + _base$4 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + line.lineDiff = lineDiff; + + /*istanbul ignore end*/ + lineDiff.tokenize = function (value) { + var retLines = [], + linesAndNewlines = value.split(/(\n|\r\n)/); // Ignore the final empty token that occurs if the string ends with a new line + + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } // Merge the content and line separators into single tokens + + + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2 && !this.options.newlineIsToken) { + retLines[retLines.length - 1] += line; + } else { + if (this.options.ignoreWhitespace) { + line = line.trim(); + } + + retLines.push(line); + } + } + + return retLines; + }; + + function diffLines(oldStr, newStr, callback) { + return lineDiff.diff(oldStr, newStr, callback); + } + + function diffTrimmedLines(oldStr, newStr, callback) { + var options = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _params + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + generateOptions) + /*istanbul ignore end*/ + (callback, { + ignoreWhitespace: true + }); + return lineDiff.diff(oldStr, newStr, options); + } + + var sentence = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(sentence, "__esModule", { + value: true + }); + sentence.diffSentences = diffSentences; + sentence.sentenceDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$3 = _interopRequireDefault$4(base) + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$4(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + var sentenceDiff = new + /*istanbul ignore start*/ + _base$3 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + sentence.sentenceDiff = sentenceDiff; + + /*istanbul ignore end*/ + sentenceDiff.tokenize = function (value) { + return value.split(/(\S.+?[.!?])(?=\s+|$)/); + }; + + function diffSentences(oldStr, newStr, callback) { + return sentenceDiff.diff(oldStr, newStr, callback); + } + + var css = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(css, "__esModule", { + value: true + }); + css.diffCss = diffCss; + css.cssDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$2 = _interopRequireDefault$3(base) + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$3(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + var cssDiff = new + /*istanbul ignore start*/ + _base$2 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + css.cssDiff = cssDiff; + + /*istanbul ignore end*/ + cssDiff.tokenize = function (value) { + return value.split(/([{}:;,]|\s+)/); + }; + + function diffCss(oldStr, newStr, callback) { + return cssDiff.diff(oldStr, newStr, callback); + } + + var json$1 = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(json$1, "__esModule", { + value: true + }); + json$1.diffJson = diffJson; + json$1.canonicalize = canonicalize; + json$1.jsonDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base$1 = _interopRequireDefault$2(base) + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _line$1 = line + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$2(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + + /*istanbul ignore end*/ + var objectPrototypeToString = Object.prototype.toString; + var jsonDiff = new + /*istanbul ignore start*/ + _base$1 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + + /*istanbul ignore start*/ + json$1.jsonDiff = jsonDiff; + + /*istanbul ignore end*/ + jsonDiff.useLongestToken = true; + jsonDiff.tokenize = + /*istanbul ignore start*/ + _line$1 + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + lineDiff + /*istanbul ignore end*/ + .tokenize; + + jsonDiff.castInput = function (value) { + /*istanbul ignore start*/ + var _this$options = + /*istanbul ignore end*/ + this.options, + undefinedReplacement = _this$options.undefinedReplacement, + _this$options$stringi = _this$options.stringifyReplacer, + stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + typeof v === 'undefined' ? undefinedReplacement : v + ); + } : _this$options$stringi; + return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' '); + }; + + jsonDiff.equals = function (left, right) { + return ( + /*istanbul ignore start*/ + _base$1 + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ].prototype.equals.call(jsonDiff, left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')) + ); + }; + + function diffJson(oldObj, newObj, options) { + return jsonDiff.diff(oldObj, newObj, options); + } // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. Accepts an optional replacer + + + function canonicalize(obj, stack, replacementStack, replacer, key) { + stack = stack || []; + replacementStack = replacementStack || []; + + if (replacer) { + obj = replacer(key, obj); + } + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key); + } + + stack.pop(); + replacementStack.pop(); + return canonicalizedObj; + } + + if (obj && obj.toJSON) { + obj = obj.toJSON(); + } + + if ( + /*istanbul ignore start*/ + _typeof( + /*istanbul ignore end*/ + obj) === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + + var sortedKeys = [], + _key; + + for (_key in obj) { + /* istanbul ignore else */ + if (obj.hasOwnProperty(_key)) { + sortedKeys.push(_key); + } + } + + sortedKeys.sort(); + + for (i = 0; i < sortedKeys.length; i += 1) { + _key = sortedKeys[i]; + canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key); + } + + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + } + + var array$1 = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(array$1, "__esModule", { + value: true + }); + array$1.diffArrays = diffArrays; + array$1.arrayDiff = void 0; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base = _interopRequireDefault$1(base) + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault$1(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + var arrayDiff = new + /*istanbul ignore start*/ + _base + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ](); + + /*istanbul ignore start*/ + array$1.arrayDiff = arrayDiff; + + /*istanbul ignore end*/ + arrayDiff.tokenize = function (value) { + return value.slice(); + }; + + arrayDiff.join = arrayDiff.removeEmpty = function (value) { + return value; + }; + + function diffArrays(oldArr, newArr, callback) { + return arrayDiff.diff(oldArr, newArr, callback); + } + + var apply = {}; + + var parse$2 = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(parse$2, "__esModule", { + value: true + }); + parse$2.parsePatch = parsePatch; + + /*istanbul ignore end*/ + function parsePatch(uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + var diffstr = uniDiff.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = uniDiff.match(/\r\n|[\n\v\f\r\x85]/g) || [], + list = [], + i = 0; + + function parseIndex() { + var index = {}; + list.push(index); // Parse diff metadata + + while (i < diffstr.length) { + var line = diffstr[i]; // File header found, end parsing diff metadata + + if (/^(\-\-\-|\+\+\+|@@)\s/.test(line)) { + break; + } // Diff index + + + var header = /^(?:Index:|diff(?: -r \w+)+)\s+(.+?)\s*$/.exec(line); + + if (header) { + index.index = header[1]; + } + + i++; + } // Parse file headers if they are defined. Unified diff requires them, but + // there's no technical issues to have an isolated hunk without file header + + + parseFileHeader(index); + parseFileHeader(index); // Parse hunks + + index.hunks = []; + + while (i < diffstr.length) { + var _line = diffstr[i]; + + if (/^(Index:|diff|\-\-\-|\+\+\+)\s/.test(_line)) { + break; + } else if (/^@@/.test(_line)) { + index.hunks.push(parseHunk()); + } else if (_line && options.strict) { + // Ignore unexpected content unless in strict mode + throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line)); + } else { + i++; + } + } + } // Parses the --- and +++ headers, if none are found, no lines + // are consumed. + + + function parseFileHeader(index) { + var fileHeader = /^(---|\+\+\+)\s+(.*)$/.exec(diffstr[i]); + + if (fileHeader) { + var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new'; + var data = fileHeader[2].split('\t', 2); + var fileName = data[0].replace(/\\\\/g, '\\'); + + if (/^".*"$/.test(fileName)) { + fileName = fileName.substr(1, fileName.length - 2); + } + + index[keyPrefix + 'FileName'] = fileName; + index[keyPrefix + 'Header'] = (data[1] || '').trim(); + i++; + } + } // Parses a hunk + // This assumes that we are at the start of a hunk. + + + function parseHunk() { + var chunkHeaderIndex = i, + chunkHeaderLine = diffstr[i++], + chunkHeader = chunkHeaderLine.split(/@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/); + var hunk = { + oldStart: +chunkHeader[1], + oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2], + newStart: +chunkHeader[3], + newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4], + lines: [], + linedelimiters: [] + }; // Unified Diff Format quirk: If the chunk size is 0, + // the first number is one lower than one would expect. + // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 + + if (hunk.oldLines === 0) { + hunk.oldStart += 1; + } + + if (hunk.newLines === 0) { + hunk.newStart += 1; + } + + var addCount = 0, + removeCount = 0; + + for (; i < diffstr.length; i++) { + // Lines starting with '---' could be mistaken for the "remove line" operation + // But they could be the header for the next file. Therefore prune such cases out. + if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) { + break; + } + + var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0]; + + if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\') { + hunk.lines.push(diffstr[i]); + hunk.linedelimiters.push(delimiters[i] || '\n'); + + if (operation === '+') { + addCount++; + } else if (operation === '-') { + removeCount++; + } else if (operation === ' ') { + addCount++; + removeCount++; + } + } else { + break; + } + } // Handle the empty block count case + + + if (!addCount && hunk.newLines === 1) { + hunk.newLines = 0; + } + + if (!removeCount && hunk.oldLines === 1) { + hunk.oldLines = 0; + } // Perform optional sanity checking + + + if (options.strict) { + if (addCount !== hunk.newLines) { + throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + + if (removeCount !== hunk.oldLines) { + throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1)); + } + } + + return hunk; + } + + while (i < diffstr.length) { + parseIndex(); + } + + return list; + } + + var distanceIterator = {}; + + /*istanbul ignore start*/ + + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + exports["default"] = _default; + + /*istanbul ignore end*/ + // Iterator that traverses in the range of [min, max], stepping + // by distance from a given start position. I.e. for [0, 4], with + // start of 2, this will iterate 2, 3, 1, 4, 0. + function + /*istanbul ignore start*/ + _default + /*istanbul ignore end*/ + (start, minLine, maxLine) { + var wantForward = true, + backwardExhausted = false, + forwardExhausted = false, + localOffset = 1; + return function iterator() { + if (wantForward && !forwardExhausted) { + if (backwardExhausted) { + localOffset++; + } else { + wantForward = false; + } // Check if trying to fit beyond text length, and if not, check it fits + // after offset location (or desired location on first iteration) + + + if (start + localOffset <= maxLine) { + return localOffset; + } + + forwardExhausted = true; + } + + if (!backwardExhausted) { + if (!forwardExhausted) { + wantForward = true; + } // Check if trying to fit before text beginning, and if not, check it fits + // before offset location + + + if (minLine <= start - localOffset) { + return -localOffset++; + } + + backwardExhausted = true; + return iterator(); + } // We tried to fit hunk before text beginning and beyond text length, then + // hunk can't fit on the text. Return undefined + + }; + } + + }(distanceIterator)); + + /*istanbul ignore start*/ + + Object.defineProperty(apply, "__esModule", { + value: true + }); + apply.applyPatch = applyPatch; + apply.applyPatches = applyPatches; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _parse$1 = parse$2 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _distanceIterator = _interopRequireDefault(distanceIterator) + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + function applyPatch(source, uniDiff) { + /*istanbul ignore start*/ + var + /*istanbul ignore end*/ + options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _parse$1 + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + if (Array.isArray(uniDiff)) { + if (uniDiff.length > 1) { + throw new Error('applyPatch only works with a single input.'); + } + + uniDiff = uniDiff[0]; + } // Apply the diff to the input + + + var lines = source.split(/\r\n|[\n\v\f\r\x85]/), + delimiters = source.match(/\r\n|[\n\v\f\r\x85]/g) || [], + hunks = uniDiff.hunks, + compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) + /*istanbul ignore start*/ + { + return ( + /*istanbul ignore end*/ + line === patchContent + ); + }, + errorCount = 0, + fuzzFactor = options.fuzzFactor || 0, + minLine = 0, + offset = 0, + removeEOFNL, + addEOFNL; + /** + * Checks if the hunk exactly fits on the provided location + */ + + + function hunkFits(hunk, toPos) { + for (var j = 0; j < hunk.lines.length; j++) { + var line = hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line; + + if (operation === ' ' || operation === '-') { + // Context sanity check + if (!compareLine(toPos + 1, lines[toPos], operation, content)) { + errorCount++; + + if (errorCount > fuzzFactor) { + return false; + } + } + + toPos++; + } + } + + return true; + } // Search best fit offsets for each hunk based on the previous ones + + + for (var i = 0; i < hunks.length; i++) { + var hunk = hunks[i], + maxLine = lines.length - hunk.oldLines, + localOffset = 0, + toPos = offset + hunk.oldStart - 1; + var iterator = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _distanceIterator + /*istanbul ignore end*/ + [ + /*istanbul ignore start*/ + "default" + /*istanbul ignore end*/ + ])(toPos, minLine, maxLine); + + for (; localOffset !== undefined; localOffset = iterator()) { + if (hunkFits(hunk, toPos + localOffset)) { + hunk.offset = offset += localOffset; + break; + } + } + + if (localOffset === undefined) { + return false; + } // Set lower text limit to end of the current hunk, so next ones don't try + // to fit over already patched text + + + minLine = hunk.offset + hunk.oldStart + hunk.oldLines; + } // Apply patch hunks + + + var diffOffset = 0; + + for (var _i = 0; _i < hunks.length; _i++) { + var _hunk = hunks[_i], + _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1; + + diffOffset += _hunk.newLines - _hunk.oldLines; + + for (var j = 0; j < _hunk.lines.length; j++) { + var line = _hunk.lines[j], + operation = line.length > 0 ? line[0] : ' ', + content = line.length > 0 ? line.substr(1) : line, + delimiter = _hunk.linedelimiters[j]; + + if (operation === ' ') { + _toPos++; + } else if (operation === '-') { + lines.splice(_toPos, 1); + delimiters.splice(_toPos, 1); + /* istanbul ignore else */ + } else if (operation === '+') { + lines.splice(_toPos, 0, content); + delimiters.splice(_toPos, 0, delimiter); + _toPos++; + } else if (operation === '\\') { + var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null; + + if (previousOperation === '+') { + removeEOFNL = true; + } else if (previousOperation === '-') { + addEOFNL = true; + } + } + } + } // Handle EOFNL insertion/removal + + + if (removeEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + delimiters.pop(); + } + } else if (addEOFNL) { + lines.push(''); + delimiters.push('\n'); + } + + for (var _k = 0; _k < lines.length - 1; _k++) { + lines[_k] = lines[_k] + delimiters[_k]; + } + + return lines.join(''); + } // Wrapper that supports multiple file patches via callbacks. + + + function applyPatches(uniDiff, options) { + if (typeof uniDiff === 'string') { + uniDiff = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _parse$1 + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (uniDiff); + } + + var currentIndex = 0; + + function processIndex() { + var index = uniDiff[currentIndex++]; + + if (!index) { + return options.complete(); + } + + options.loadFile(index, function (err, data) { + if (err) { + return options.complete(err); + } + + var updatedContent = applyPatch(data, index, options); + options.patched(index, updatedContent, function (err) { + if (err) { + return options.complete(err); + } + + processIndex(); + }); + }); + } + + processIndex(); + } + + var merge$1 = {}; + + var create = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(create, "__esModule", { + value: true + }); + create.structuredPatch = structuredPatch; + create.formatPatch = formatPatch; + create.createTwoFilesPatch = createTwoFilesPatch; + create.createPatch = createPatch; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _line = line + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _toConsumableArray$1(arr) { return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1(); } + + function _nonIterableSpread$1() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + + function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen); } + + function _iterableToArray$1(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + + function _arrayWithoutHoles$1(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } + + function _arrayLikeToArray$1(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + + /*istanbul ignore end*/ + function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + if (!options) { + options = {}; + } + + if (typeof options.context === 'undefined') { + options.context = 4; + } + + var diff = + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _line + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + diffLines) + /*istanbul ignore end*/ + (oldStr, newStr, options); + diff.push({ + value: '', + lines: [] + }); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function (entry) { + return ' ' + entry; + }); + } + + var hunks = []; + var oldRangeStart = 0, + newRangeStart = 0, + curRange = [], + oldLine = 1, + newLine = 1; + + /*istanbul ignore start*/ + var _loop = function _loop( + /*istanbul ignore end*/ + i) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + /*istanbul ignore start*/ + var _curRange; + + /*istanbul ignore end*/ + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : []; + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } // Output our changes + + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_curRange = + /*istanbul ignore end*/ + curRange).push.apply( + /*istanbul ignore start*/ + _curRange + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray$1( + /*istanbul ignore end*/ + lines.map(function (entry) { + return (current.added ? '+' : '-') + entry; + }))); // Track the updated file position + + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= options.context * 2 && i < diff.length - 2) { + /*istanbul ignore start*/ + var _curRange2; + + /*istanbul ignore end*/ + // Overlapping + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_curRange2 = + /*istanbul ignore end*/ + curRange).push.apply( + /*istanbul ignore start*/ + _curRange2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray$1( + /*istanbul ignore end*/ + contextLines(lines))); + } else { + /*istanbul ignore start*/ + var _curRange3; + + /*istanbul ignore end*/ + // end the range and output + var contextSize = Math.min(lines.length, options.context); + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_curRange3 = + /*istanbul ignore end*/ + curRange).push.apply( + /*istanbul ignore start*/ + _curRange3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray$1( + /*istanbul ignore end*/ + contextLines(lines.slice(0, contextSize)))); + + var hunk = { + oldStart: oldRangeStart, + oldLines: oldLine - oldRangeStart + contextSize, + newStart: newRangeStart, + newLines: newLine - newRangeStart + contextSize, + lines: curRange + }; + + if (i >= diff.length - 2 && lines.length <= options.context) { + // EOF is inside this hunk + var oldEOFNewline = /\n$/.test(oldStr); + var newEOFNewline = /\n$/.test(newStr); + var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines; + + if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) { + // special case: old has no eol and no trailing context; no-nl can end up before adds + // however, if the old file is empty, do not output the no-nl line + curRange.splice(hunk.oldLines, 0, '\\ No newline at end of file'); + } + + if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) { + curRange.push('\\ No newline at end of file'); + } + } + + hunks.push(hunk); + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + + oldLine += lines.length; + newLine += lines.length; + } + }; + + for (var i = 0; i < diff.length; i++) { + /*istanbul ignore start*/ + _loop( + /*istanbul ignore end*/ + i); + } + + return { + oldFileName: oldFileName, + newFileName: newFileName, + oldHeader: oldHeader, + newHeader: newHeader, + hunks: hunks + }; + } + + function formatPatch(diff) { + var ret = []; + + if (diff.oldFileName == diff.newFileName) { + ret.push('Index: ' + diff.oldFileName); + } + + ret.push('==================================================================='); + ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\t' + diff.oldHeader)); + ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\t' + diff.newHeader)); + + for (var i = 0; i < diff.hunks.length; i++) { + var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0, + // the first number is one lower than one would expect. + // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 + + if (hunk.oldLines === 0) { + hunk.oldStart -= 1; + } + + if (hunk.newLines === 0) { + hunk.newStart -= 1; + } + + ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@'); + ret.push.apply(ret, hunk.lines); + } + + return ret.join('\n') + '\n'; + } + + function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { + return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options)); + } + + function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { + return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); + } + + var array = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(array, "__esModule", { + value: true + }); + array.arrayEqual = arrayEqual; + array.arrayStartsWith = arrayStartsWith; + + /*istanbul ignore end*/ + function arrayEqual(a, b) { + if (a.length !== b.length) { + return false; + } + + return arrayStartsWith(a, b); + } + + function arrayStartsWith(array, start) { + if (start.length > array.length) { + return false; + } + + for (var i = 0; i < start.length; i++) { + if (start[i] !== array[i]) { + return false; + } + } + + return true; + } + + /*istanbul ignore start*/ + + Object.defineProperty(merge$1, "__esModule", { + value: true + }); + merge$1.calcLineCount = calcLineCount; + merge$1.merge = merge; + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _create = create + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _parse = parse$2 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _array = array + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } + + function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } + + function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } + + function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } + + function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } + + function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } + + /*istanbul ignore end*/ + function calcLineCount(hunk) { + /*istanbul ignore start*/ + var _calcOldNewLineCount = + /*istanbul ignore end*/ + calcOldNewLineCount(hunk.lines), + oldLines = _calcOldNewLineCount.oldLines, + newLines = _calcOldNewLineCount.newLines; + + if (oldLines !== undefined) { + hunk.oldLines = oldLines; + } else { + delete hunk.oldLines; + } + + if (newLines !== undefined) { + hunk.newLines = newLines; + } else { + delete hunk.newLines; + } + } + + function merge(mine, theirs, base) { + mine = loadPatch(mine, base); + theirs = loadPatch(theirs, base); + var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning. + // Leaving sanity checks on this to the API consumer that may know more about the + // meaning in their own context. + + if (mine.index || theirs.index) { + ret.index = mine.index || theirs.index; + } + + if (mine.newFileName || theirs.newFileName) { + if (!fileNameChanged(mine)) { + // No header or no change in ours, use theirs (and ours if theirs does not exist) + ret.oldFileName = theirs.oldFileName || mine.oldFileName; + ret.newFileName = theirs.newFileName || mine.newFileName; + ret.oldHeader = theirs.oldHeader || mine.oldHeader; + ret.newHeader = theirs.newHeader || mine.newHeader; + } else if (!fileNameChanged(theirs)) { + // No header or no change in theirs, use ours + ret.oldFileName = mine.oldFileName; + ret.newFileName = mine.newFileName; + ret.oldHeader = mine.oldHeader; + ret.newHeader = mine.newHeader; + } else { + // Both changed... figure it out + ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName); + ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName); + ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader); + ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader); + } + } + + ret.hunks = []; + var mineIndex = 0, + theirsIndex = 0, + mineOffset = 0, + theirsOffset = 0; + + while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) { + var mineCurrent = mine.hunks[mineIndex] || { + oldStart: Infinity + }, + theirsCurrent = theirs.hunks[theirsIndex] || { + oldStart: Infinity + }; + + if (hunkBefore(mineCurrent, theirsCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(mineCurrent, mineOffset)); + mineIndex++; + theirsOffset += mineCurrent.newLines - mineCurrent.oldLines; + } else if (hunkBefore(theirsCurrent, mineCurrent)) { + // This patch does not overlap with any of the others, yay. + ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset)); + theirsIndex++; + mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines; + } else { + // Overlap, merge as best we can + var mergedHunk = { + oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart), + oldLines: 0, + newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset), + newLines: 0, + lines: [] + }; + mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines); + theirsIndex++; + mineIndex++; + ret.hunks.push(mergedHunk); + } + } + + return ret; + } + + function loadPatch(param, base) { + if (typeof param === 'string') { + if (/^@@/m.test(param) || /^Index:/m.test(param)) { + return ( + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _parse + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + parsePatch) + /*istanbul ignore end*/ + (param)[0] + ); + } + + if (!base) { + throw new Error('Must provide a base reference or pass in a patch'); + } + + return ( + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _create + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + structuredPatch) + /*istanbul ignore end*/ + (undefined, undefined, base, param) + ); + } + + return param; + } + + function fileNameChanged(patch) { + return patch.newFileName && patch.newFileName !== patch.oldFileName; + } + + function selectField(index, mine, theirs) { + if (mine === theirs) { + return mine; + } else { + index.conflict = true; + return { + mine: mine, + theirs: theirs + }; + } + } + + function hunkBefore(test, check) { + return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart; + } + + function cloneHunk(hunk, offset) { + return { + oldStart: hunk.oldStart, + oldLines: hunk.oldLines, + newStart: hunk.newStart + offset, + newLines: hunk.newLines, + lines: hunk.lines + }; + } + + function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) { + // This will generally result in a conflicted hunk, but there are cases where the context + // is the only overlap where we can successfully merge the content here. + var mine = { + offset: mineOffset, + lines: mineLines, + index: 0 + }, + their = { + offset: theirOffset, + lines: theirLines, + index: 0 + }; // Handle any leading content + + insertLeading(hunk, mine, their); + insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each. + + while (mine.index < mine.lines.length && their.index < their.lines.length) { + var mineCurrent = mine.lines[mine.index], + theirCurrent = their.lines[their.index]; + + if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) { + // Both modified ... + mutualChange(hunk, mine, their); + } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines; + + /*istanbul ignore end*/ + // Mine inserted + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(mine))); + } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') { + /*istanbul ignore start*/ + var _hunk$lines2; + + /*istanbul ignore end*/ + // Theirs inserted + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines2 = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines2 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + collectChange(their))); + } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') { + // Mine removed or edited + removal(hunk, mine, their); + } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') { + // Their removed or edited + removal(hunk, their, mine, true); + } else if (mineCurrent === theirCurrent) { + // Context identity + hunk.lines.push(mineCurrent); + mine.index++; + their.index++; + } else { + // Context mismatch + conflict(hunk, collectChange(mine), collectChange(their)); + } + } // Now push anything that may be remaining + + + insertTrailing(hunk, mine); + insertTrailing(hunk, their); + calcLineCount(hunk); + } + + function mutualChange(hunk, mine, their) { + var myChanges = collectChange(mine), + theirChanges = collectChange(their); + + if (allRemoves(myChanges) && allRemoves(theirChanges)) { + // Special case for remove changes that are supersets of one another + if ( + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines3; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines3 = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines3 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } else if ( + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayStartsWith) + /*istanbul ignore end*/ + (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) { + /*istanbul ignore start*/ + var _hunk$lines4; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines4 = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines4 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges)); + + return; + } + } else if ( + /*istanbul ignore start*/ + (/*istanbul ignore end*/ + + /*istanbul ignore start*/ + 0, _array + /*istanbul ignore end*/ + . + /*istanbul ignore start*/ + arrayEqual) + /*istanbul ignore end*/ + (myChanges, theirChanges)) { + /*istanbul ignore start*/ + var _hunk$lines5; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines5 = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines5 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + myChanges)); + + return; + } + + conflict(hunk, myChanges, theirChanges); + } + + function removal(hunk, mine, their, swap) { + var myChanges = collectChange(mine), + theirChanges = collectContext(their, myChanges); + + if (theirChanges.merged) { + /*istanbul ignore start*/ + var _hunk$lines6; + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + + /*istanbul ignore end*/ + + /*istanbul ignore start*/ + (_hunk$lines6 = + /*istanbul ignore end*/ + hunk.lines).push.apply( + /*istanbul ignore start*/ + _hunk$lines6 + /*istanbul ignore end*/ + , + /*istanbul ignore start*/ + _toConsumableArray( + /*istanbul ignore end*/ + theirChanges.merged)); + } else { + conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges); + } + } + + function conflict(hunk, mine, their) { + hunk.conflict = true; + hunk.lines.push({ + conflict: true, + mine: mine, + theirs: their + }); + } + + function insertLeading(hunk, insert, their) { + while (insert.offset < their.offset && insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + insert.offset++; + } + } + + function insertTrailing(hunk, insert) { + while (insert.index < insert.lines.length) { + var line = insert.lines[insert.index++]; + hunk.lines.push(line); + } + } + + function collectChange(state) { + var ret = [], + operation = state.lines[state.index][0]; + + while (state.index < state.lines.length) { + var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one "atomic" modify change. + + if (operation === '-' && line[0] === '+') { + operation = '+'; + } + + if (operation === line[0]) { + ret.push(line); + state.index++; + } else { + break; + } + } + + return ret; + } + + function collectContext(state, matchChanges) { + var changes = [], + merged = [], + matchIndex = 0, + contextChanges = false, + conflicted = false; + + while (matchIndex < matchChanges.length && state.index < state.lines.length) { + var change = state.lines[state.index], + match = matchChanges[matchIndex]; // Once we've hit our add, then we are done + + if (match[0] === '+') { + break; + } + + contextChanges = contextChanges || change[0] !== ' '; + merged.push(match); + matchIndex++; // Consume any additions in the other block as a conflict to attempt + // to pull in the remaining context after this + + if (change[0] === '+') { + conflicted = true; + + while (change[0] === '+') { + changes.push(change); + change = state.lines[++state.index]; + } + } + + if (match.substr(1) === change.substr(1)) { + changes.push(change); + state.index++; + } else { + conflicted = true; + } + } + + if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) { + conflicted = true; + } + + if (conflicted) { + return changes; + } + + while (matchIndex < matchChanges.length) { + merged.push(matchChanges[matchIndex++]); + } + + return { + merged: merged, + changes: changes + }; + } + + function allRemoves(changes) { + return changes.reduce(function (prev, change) { + return prev && change[0] === '-'; + }, true); + } + + function skipRemoveSuperset(state, removeChanges, delta) { + for (var i = 0; i < delta; i++) { + var changeContent = removeChanges[removeChanges.length - delta + i].substr(1); + + if (state.lines[state.index + i] !== ' ' + changeContent) { + return false; + } + } + + state.index += delta; + return true; + } + + function calcOldNewLineCount(lines) { + var oldLines = 0; + var newLines = 0; + lines.forEach(function (line) { + if (typeof line !== 'string') { + var myCount = calcOldNewLineCount(line.mine); + var theirCount = calcOldNewLineCount(line.theirs); + + if (oldLines !== undefined) { + if (myCount.oldLines === theirCount.oldLines) { + oldLines += myCount.oldLines; + } else { + oldLines = undefined; + } + } + + if (newLines !== undefined) { + if (myCount.newLines === theirCount.newLines) { + newLines += myCount.newLines; + } else { + newLines = undefined; + } + } + } else { + if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) { + newLines++; + } + + if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) { + oldLines++; + } + } + }); + return { + oldLines: oldLines, + newLines: newLines + }; + } + + var dmp = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(dmp, "__esModule", { + value: true + }); + dmp.convertChangesToDMP = convertChangesToDMP; + + /*istanbul ignore end*/ + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + function convertChangesToDMP(changes) { + var ret = [], + change, + operation; + + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + + return ret; + } + + var xml = {}; + + /*istanbul ignore start*/ + + Object.defineProperty(xml, "__esModule", { + value: true + }); + xml.convertChangesToXML = convertChangesToXML; + + /*istanbul ignore end*/ + function convertChangesToXML(changes) { + var ret = []; + + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + + return ret.join(''); + } + + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + return n; + } + + /*istanbul ignore start*/ + + (function (exports) { + + Object.defineProperty(exports, "__esModule", { + value: true + }); + Object.defineProperty(exports, "Diff", { + enumerable: true, + get: function get() { + return _base["default"]; + } + }); + Object.defineProperty(exports, "diffChars", { + enumerable: true, + get: function get() { + return _character.diffChars; + } + }); + Object.defineProperty(exports, "diffWords", { + enumerable: true, + get: function get() { + return _word.diffWords; + } + }); + Object.defineProperty(exports, "diffWordsWithSpace", { + enumerable: true, + get: function get() { + return _word.diffWordsWithSpace; + } + }); + Object.defineProperty(exports, "diffLines", { + enumerable: true, + get: function get() { + return _line.diffLines; + } + }); + Object.defineProperty(exports, "diffTrimmedLines", { + enumerable: true, + get: function get() { + return _line.diffTrimmedLines; + } + }); + Object.defineProperty(exports, "diffSentences", { + enumerable: true, + get: function get() { + return _sentence.diffSentences; + } + }); + Object.defineProperty(exports, "diffCss", { + enumerable: true, + get: function get() { + return _css.diffCss; + } + }); + Object.defineProperty(exports, "diffJson", { + enumerable: true, + get: function get() { + return _json.diffJson; + } + }); + Object.defineProperty(exports, "canonicalize", { + enumerable: true, + get: function get() { + return _json.canonicalize; + } + }); + Object.defineProperty(exports, "diffArrays", { + enumerable: true, + get: function get() { + return _array.diffArrays; + } + }); + Object.defineProperty(exports, "applyPatch", { + enumerable: true, + get: function get() { + return _apply.applyPatch; + } + }); + Object.defineProperty(exports, "applyPatches", { + enumerable: true, + get: function get() { + return _apply.applyPatches; + } + }); + Object.defineProperty(exports, "parsePatch", { + enumerable: true, + get: function get() { + return _parse.parsePatch; + } + }); + Object.defineProperty(exports, "merge", { + enumerable: true, + get: function get() { + return _merge.merge; + } + }); + Object.defineProperty(exports, "structuredPatch", { + enumerable: true, + get: function get() { + return _create.structuredPatch; + } + }); + Object.defineProperty(exports, "createTwoFilesPatch", { + enumerable: true, + get: function get() { + return _create.createTwoFilesPatch; + } + }); + Object.defineProperty(exports, "createPatch", { + enumerable: true, + get: function get() { + return _create.createPatch; + } + }); + Object.defineProperty(exports, "convertChangesToDMP", { + enumerable: true, + get: function get() { + return _dmp.convertChangesToDMP; + } + }); + Object.defineProperty(exports, "convertChangesToXML", { + enumerable: true, + get: function get() { + return _xml.convertChangesToXML; + } + }); + + /*istanbul ignore end*/ + var + /*istanbul ignore start*/ + _base = _interopRequireDefault(base) + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _character = character + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _word = word + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _line = line + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _sentence = sentence + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _css = css + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _json = json$1 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _array = array$1 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _apply = apply + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _parse = parse$2 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _merge = merge$1 + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _create = create + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _dmp = dmp + /*istanbul ignore end*/ + ; + + var + /*istanbul ignore start*/ + _xml = xml + /*istanbul ignore end*/ + ; + + /*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } + + /*istanbul ignore end*/ + + }(lib)); + + /** + * Helpers. + */ + + var s$1 = 1000; + var m$1 = s$1 * 60; + var h$1 = m$1 * 60; + var d$1 = h$1 * 24; + var w$1 = d$1 * 7; + var y$1 = d$1 * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + var ms$1 = function (val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse$1(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong$1(val) : fmtShort$1(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse$1(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y$1; + case 'weeks': + case 'week': + case 'w': + return n * w$1; + case 'days': + case 'day': + case 'd': + return n * d$1; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h$1; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m$1; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s$1; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort$1(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d$1) { + return Math.round(ms / d$1) + 'd'; + } + if (msAbs >= h$1) { + return Math.round(ms / h$1) + 'h'; + } + if (msAbs >= m$1) { + return Math.round(ms / m$1) + 'm'; + } + if (msAbs >= s$1) { + return Math.round(ms / s$1) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong$1(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d$1) { + return plural$1(ms, msAbs, d$1, 'day'); + } + if (msAbs >= h$1) { + return plural$1(ms, msAbs, h$1, 'hour'); + } + if (msAbs >= m$1) { + return plural$1(ms, msAbs, m$1, 'minute'); + } + if (msAbs >= s$1) { + return plural$1(ms, msAbs, s$1, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural$1(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString$1 = {}.toString; + + var isArray = Array.isArray || function (arr) { + return toString$1.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + var browser$2 = true; + + var utils$3 = {}; + + var he = {exports: {}}; + + /*! https://mths.be/he v1.2.0 by @mathias | MIT license */ + + (function (module, exports) { + (function(root) { + + // Detect free variables `exports`. + var freeExports = exports; + + // Detect free variable `module`. + var freeModule = module && + module.exports == freeExports && module; + + // Detect free variable `global`, from Node.js or Browserified code, + // and use it as `root`. + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { + root = freeGlobal; + } + + /*--------------------------------------------------------------------------*/ + + // All astral symbols. + var regexAstralSymbols = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g; + // All ASCII symbols (not just printable ASCII) except those listed in the + // first column of the overrides table. + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides + var regexAsciiWhitelist = /[\x01-\x7F]/g; + // All BMP symbols that are not ASCII newlines, printable ASCII symbols, or + // code points listed in the first column of the overrides table on + // https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides. + var regexBmpWhitelist = /[\x01-\t\x0B\f\x0E-\x1F\x7F\x81\x8D\x8F\x90\x9D\xA0-\uFFFF]/g; + + var regexEncodeNonAscii = /<\u20D2|=\u20E5|>\u20D2|\u205F\u200A|\u219D\u0338|\u2202\u0338|\u2220\u20D2|\u2229\uFE00|\u222A\uFE00|\u223C\u20D2|\u223D\u0331|\u223E\u0333|\u2242\u0338|\u224B\u0338|\u224D\u20D2|\u224E\u0338|\u224F\u0338|\u2250\u0338|\u2261\u20E5|\u2264\u20D2|\u2265\u20D2|\u2266\u0338|\u2267\u0338|\u2268\uFE00|\u2269\uFE00|\u226A\u0338|\u226A\u20D2|\u226B\u0338|\u226B\u20D2|\u227F\u0338|\u2282\u20D2|\u2283\u20D2|\u228A\uFE00|\u228B\uFE00|\u228F\u0338|\u2290\u0338|\u2293\uFE00|\u2294\uFE00|\u22B4\u20D2|\u22B5\u20D2|\u22D8\u0338|\u22D9\u0338|\u22DA\uFE00|\u22DB\uFE00|\u22F5\u0338|\u22F9\u0338|\u2933\u0338|\u29CF\u0338|\u29D0\u0338|\u2A6D\u0338|\u2A70\u0338|\u2A7D\u0338|\u2A7E\u0338|\u2AA1\u0338|\u2AA2\u0338|\u2AAC\uFE00|\u2AAD\uFE00|\u2AAF\u0338|\u2AB0\u0338|\u2AC5\u0338|\u2AC6\u0338|\u2ACB\uFE00|\u2ACC\uFE00|\u2AFD\u20E5|[\xA0-\u0113\u0116-\u0122\u0124-\u012B\u012E-\u014D\u0150-\u017E\u0192\u01B5\u01F5\u0237\u02C6\u02C7\u02D8-\u02DD\u0311\u0391-\u03A1\u03A3-\u03A9\u03B1-\u03C9\u03D1\u03D2\u03D5\u03D6\u03DC\u03DD\u03F0\u03F1\u03F5\u03F6\u0401-\u040C\u040E-\u044F\u0451-\u045C\u045E\u045F\u2002-\u2005\u2007-\u2010\u2013-\u2016\u2018-\u201A\u201C-\u201E\u2020-\u2022\u2025\u2026\u2030-\u2035\u2039\u203A\u203E\u2041\u2043\u2044\u204F\u2057\u205F-\u2063\u20AC\u20DB\u20DC\u2102\u2105\u210A-\u2113\u2115-\u211E\u2122\u2124\u2127-\u2129\u212C\u212D\u212F-\u2131\u2133-\u2138\u2145-\u2148\u2153-\u215E\u2190-\u219B\u219D-\u21A7\u21A9-\u21AE\u21B0-\u21B3\u21B5-\u21B7\u21BA-\u21DB\u21DD\u21E4\u21E5\u21F5\u21FD-\u2205\u2207-\u2209\u220B\u220C\u220F-\u2214\u2216-\u2218\u221A\u221D-\u2238\u223A-\u2257\u2259\u225A\u225C\u225F-\u2262\u2264-\u228B\u228D-\u229B\u229D-\u22A5\u22A7-\u22B0\u22B2-\u22BB\u22BD-\u22DB\u22DE-\u22E3\u22E6-\u22F7\u22F9-\u22FE\u2305\u2306\u2308-\u2310\u2312\u2313\u2315\u2316\u231C-\u231F\u2322\u2323\u232D\u232E\u2336\u233D\u233F\u237C\u23B0\u23B1\u23B4-\u23B6\u23DC-\u23DF\u23E2\u23E7\u2423\u24C8\u2500\u2502\u250C\u2510\u2514\u2518\u251C\u2524\u252C\u2534\u253C\u2550-\u256C\u2580\u2584\u2588\u2591-\u2593\u25A1\u25AA\u25AB\u25AD\u25AE\u25B1\u25B3-\u25B5\u25B8\u25B9\u25BD-\u25BF\u25C2\u25C3\u25CA\u25CB\u25EC\u25EF\u25F8-\u25FC\u2605\u2606\u260E\u2640\u2642\u2660\u2663\u2665\u2666\u266A\u266D-\u266F\u2713\u2717\u2720\u2736\u2758\u2772\u2773\u27C8\u27C9\u27E6-\u27ED\u27F5-\u27FA\u27FC\u27FF\u2902-\u2905\u290C-\u2913\u2916\u2919-\u2920\u2923-\u292A\u2933\u2935-\u2939\u293C\u293D\u2945\u2948-\u294B\u294E-\u2976\u2978\u2979\u297B-\u297F\u2985\u2986\u298B-\u2996\u299A\u299C\u299D\u29A4-\u29B7\u29B9\u29BB\u29BC\u29BE-\u29C5\u29C9\u29CD-\u29D0\u29DC-\u29DE\u29E3-\u29E5\u29EB\u29F4\u29F6\u2A00-\u2A02\u2A04\u2A06\u2A0C\u2A0D\u2A10-\u2A17\u2A22-\u2A27\u2A29\u2A2A\u2A2D-\u2A31\u2A33-\u2A3C\u2A3F\u2A40\u2A42-\u2A4D\u2A50\u2A53-\u2A58\u2A5A-\u2A5D\u2A5F\u2A66\u2A6A\u2A6D-\u2A75\u2A77-\u2A9A\u2A9D-\u2AA2\u2AA4-\u2AB0\u2AB3-\u2AC8\u2ACB\u2ACC\u2ACF-\u2ADB\u2AE4\u2AE6-\u2AE9\u2AEB-\u2AF3\u2AFD\uFB00-\uFB04]|\uD835[\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDCCF\uDD04\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDD6B]/g; + var encodeMap = {'\xAD':'shy','\u200C':'zwnj','\u200D':'zwj','\u200E':'lrm','\u2063':'ic','\u2062':'it','\u2061':'af','\u200F':'rlm','\u200B':'ZeroWidthSpace','\u2060':'NoBreak','\u0311':'DownBreve','\u20DB':'tdot','\u20DC':'DotDot','\t':'Tab','\n':'NewLine','\u2008':'puncsp','\u205F':'MediumSpace','\u2009':'thinsp','\u200A':'hairsp','\u2004':'emsp13','\u2002':'ensp','\u2005':'emsp14','\u2003':'emsp','\u2007':'numsp','\xA0':'nbsp','\u205F\u200A':'ThickSpace','\u203E':'oline','_':'lowbar','\u2010':'dash','\u2013':'ndash','\u2014':'mdash','\u2015':'horbar',',':'comma',';':'semi','\u204F':'bsemi',':':'colon','\u2A74':'Colone','!':'excl','\xA1':'iexcl','?':'quest','\xBF':'iquest','.':'period','\u2025':'nldr','\u2026':'mldr','\xB7':'middot','\'':'apos','\u2018':'lsquo','\u2019':'rsquo','\u201A':'sbquo','\u2039':'lsaquo','\u203A':'rsaquo','"':'quot','\u201C':'ldquo','\u201D':'rdquo','\u201E':'bdquo','\xAB':'laquo','\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\u2308':'lceil','\u2309':'rceil','\u230A':'lfloor','\u230B':'rfloor','\u2985':'lopar','\u2986':'ropar','\u298B':'lbrke','\u298C':'rbrke','\u298D':'lbrkslu','\u298E':'rbrksld','\u298F':'lbrksld','\u2990':'rbrkslu','\u2991':'langd','\u2992':'rangd','\u2993':'lparlt','\u2994':'rpargt','\u2995':'gtlPar','\u2996':'ltrPar','\u27E6':'lobrk','\u27E7':'robrk','\u27E8':'lang','\u27E9':'rang','\u27EA':'Lang','\u27EB':'Rang','\u27EC':'loang','\u27ED':'roang','\u2772':'lbbrk','\u2773':'rbbrk','\u2016':'Vert','\xA7':'sect','\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\u2030':'permil','\u2031':'pertenk','\u2020':'dagger','\u2021':'Dagger','\u2022':'bull','\u2043':'hybull','\u2032':'prime','\u2033':'Prime','\u2034':'tprime','\u2057':'qprime','\u2035':'bprime','\u2041':'caret','`':'grave','\xB4':'acute','\u02DC':'tilde','^':'Hat','\xAF':'macr','\u02D8':'breve','\u02D9':'dot','\xA8':'die','\u02DA':'ring','\u02DD':'dblac','\xB8':'cedil','\u02DB':'ogon','\u02C6':'circ','\u02C7':'caron','\xB0':'deg','\xA9':'copy','\xAE':'reg','\u2117':'copysr','\u2118':'wp','\u211E':'rx','\u2127':'mho','\u2129':'iiota','\u2190':'larr','\u219A':'nlarr','\u2192':'rarr','\u219B':'nrarr','\u2191':'uarr','\u2193':'darr','\u2194':'harr','\u21AE':'nharr','\u2195':'varr','\u2196':'nwarr','\u2197':'nearr','\u2198':'searr','\u2199':'swarr','\u219D':'rarrw','\u219D\u0338':'nrarrw','\u219E':'Larr','\u219F':'Uarr','\u21A0':'Rarr','\u21A1':'Darr','\u21A2':'larrtl','\u21A3':'rarrtl','\u21A4':'mapstoleft','\u21A5':'mapstoup','\u21A6':'map','\u21A7':'mapstodown','\u21A9':'larrhk','\u21AA':'rarrhk','\u21AB':'larrlp','\u21AC':'rarrlp','\u21AD':'harrw','\u21B0':'lsh','\u21B1':'rsh','\u21B2':'ldsh','\u21B3':'rdsh','\u21B5':'crarr','\u21B6':'cularr','\u21B7':'curarr','\u21BA':'olarr','\u21BB':'orarr','\u21BC':'lharu','\u21BD':'lhard','\u21BE':'uharr','\u21BF':'uharl','\u21C0':'rharu','\u21C1':'rhard','\u21C2':'dharr','\u21C3':'dharl','\u21C4':'rlarr','\u21C5':'udarr','\u21C6':'lrarr','\u21C7':'llarr','\u21C8':'uuarr','\u21C9':'rrarr','\u21CA':'ddarr','\u21CB':'lrhar','\u21CC':'rlhar','\u21D0':'lArr','\u21CD':'nlArr','\u21D1':'uArr','\u21D2':'rArr','\u21CF':'nrArr','\u21D3':'dArr','\u21D4':'iff','\u21CE':'nhArr','\u21D5':'vArr','\u21D6':'nwArr','\u21D7':'neArr','\u21D8':'seArr','\u21D9':'swArr','\u21DA':'lAarr','\u21DB':'rAarr','\u21DD':'zigrarr','\u21E4':'larrb','\u21E5':'rarrb','\u21F5':'duarr','\u21FD':'loarr','\u21FE':'roarr','\u21FF':'hoarr','\u2200':'forall','\u2201':'comp','\u2202':'part','\u2202\u0338':'npart','\u2203':'exist','\u2204':'nexist','\u2205':'empty','\u2207':'Del','\u2208':'in','\u2209':'notin','\u220B':'ni','\u220C':'notni','\u03F6':'bepsi','\u220F':'prod','\u2210':'coprod','\u2211':'sum','+':'plus','\xB1':'pm','\xF7':'div','\xD7':'times','<':'lt','\u226E':'nlt','<\u20D2':'nvlt','=':'equals','\u2260':'ne','=\u20E5':'bne','\u2A75':'Equal','>':'gt','\u226F':'ngt','>\u20D2':'nvgt','\xAC':'not','|':'vert','\xA6':'brvbar','\u2212':'minus','\u2213':'mp','\u2214':'plusdo','\u2044':'frasl','\u2216':'setmn','\u2217':'lowast','\u2218':'compfn','\u221A':'Sqrt','\u221D':'prop','\u221E':'infin','\u221F':'angrt','\u2220':'ang','\u2220\u20D2':'nang','\u2221':'angmsd','\u2222':'angsph','\u2223':'mid','\u2224':'nmid','\u2225':'par','\u2226':'npar','\u2227':'and','\u2228':'or','\u2229':'cap','\u2229\uFE00':'caps','\u222A':'cup','\u222A\uFE00':'cups','\u222B':'int','\u222C':'Int','\u222D':'tint','\u2A0C':'qint','\u222E':'oint','\u222F':'Conint','\u2230':'Cconint','\u2231':'cwint','\u2232':'cwconint','\u2233':'awconint','\u2234':'there4','\u2235':'becaus','\u2236':'ratio','\u2237':'Colon','\u2238':'minusd','\u223A':'mDDot','\u223B':'homtht','\u223C':'sim','\u2241':'nsim','\u223C\u20D2':'nvsim','\u223D':'bsim','\u223D\u0331':'race','\u223E':'ac','\u223E\u0333':'acE','\u223F':'acd','\u2240':'wr','\u2242':'esim','\u2242\u0338':'nesim','\u2243':'sime','\u2244':'nsime','\u2245':'cong','\u2247':'ncong','\u2246':'simne','\u2248':'ap','\u2249':'nap','\u224A':'ape','\u224B':'apid','\u224B\u0338':'napid','\u224C':'bcong','\u224D':'CupCap','\u226D':'NotCupCap','\u224D\u20D2':'nvap','\u224E':'bump','\u224E\u0338':'nbump','\u224F':'bumpe','\u224F\u0338':'nbumpe','\u2250':'doteq','\u2250\u0338':'nedot','\u2251':'eDot','\u2252':'efDot','\u2253':'erDot','\u2254':'colone','\u2255':'ecolon','\u2256':'ecir','\u2257':'cire','\u2259':'wedgeq','\u225A':'veeeq','\u225C':'trie','\u225F':'equest','\u2261':'equiv','\u2262':'nequiv','\u2261\u20E5':'bnequiv','\u2264':'le','\u2270':'nle','\u2264\u20D2':'nvle','\u2265':'ge','\u2271':'nge','\u2265\u20D2':'nvge','\u2266':'lE','\u2266\u0338':'nlE','\u2267':'gE','\u2267\u0338':'ngE','\u2268\uFE00':'lvnE','\u2268':'lnE','\u2269':'gnE','\u2269\uFE00':'gvnE','\u226A':'ll','\u226A\u0338':'nLtv','\u226A\u20D2':'nLt','\u226B':'gg','\u226B\u0338':'nGtv','\u226B\u20D2':'nGt','\u226C':'twixt','\u2272':'lsim','\u2274':'nlsim','\u2273':'gsim','\u2275':'ngsim','\u2276':'lg','\u2278':'ntlg','\u2277':'gl','\u2279':'ntgl','\u227A':'pr','\u2280':'npr','\u227B':'sc','\u2281':'nsc','\u227C':'prcue','\u22E0':'nprcue','\u227D':'sccue','\u22E1':'nsccue','\u227E':'prsim','\u227F':'scsim','\u227F\u0338':'NotSucceedsTilde','\u2282':'sub','\u2284':'nsub','\u2282\u20D2':'vnsub','\u2283':'sup','\u2285':'nsup','\u2283\u20D2':'vnsup','\u2286':'sube','\u2288':'nsube','\u2287':'supe','\u2289':'nsupe','\u228A\uFE00':'vsubne','\u228A':'subne','\u228B\uFE00':'vsupne','\u228B':'supne','\u228D':'cupdot','\u228E':'uplus','\u228F':'sqsub','\u228F\u0338':'NotSquareSubset','\u2290':'sqsup','\u2290\u0338':'NotSquareSuperset','\u2291':'sqsube','\u22E2':'nsqsube','\u2292':'sqsupe','\u22E3':'nsqsupe','\u2293':'sqcap','\u2293\uFE00':'sqcaps','\u2294':'sqcup','\u2294\uFE00':'sqcups','\u2295':'oplus','\u2296':'ominus','\u2297':'otimes','\u2298':'osol','\u2299':'odot','\u229A':'ocir','\u229B':'oast','\u229D':'odash','\u229E':'plusb','\u229F':'minusb','\u22A0':'timesb','\u22A1':'sdotb','\u22A2':'vdash','\u22AC':'nvdash','\u22A3':'dashv','\u22A4':'top','\u22A5':'bot','\u22A7':'models','\u22A8':'vDash','\u22AD':'nvDash','\u22A9':'Vdash','\u22AE':'nVdash','\u22AA':'Vvdash','\u22AB':'VDash','\u22AF':'nVDash','\u22B0':'prurel','\u22B2':'vltri','\u22EA':'nltri','\u22B3':'vrtri','\u22EB':'nrtri','\u22B4':'ltrie','\u22EC':'nltrie','\u22B4\u20D2':'nvltrie','\u22B5':'rtrie','\u22ED':'nrtrie','\u22B5\u20D2':'nvrtrie','\u22B6':'origof','\u22B7':'imof','\u22B8':'mumap','\u22B9':'hercon','\u22BA':'intcal','\u22BB':'veebar','\u22BD':'barvee','\u22BE':'angrtvb','\u22BF':'lrtri','\u22C0':'Wedge','\u22C1':'Vee','\u22C2':'xcap','\u22C3':'xcup','\u22C4':'diam','\u22C5':'sdot','\u22C6':'Star','\u22C7':'divonx','\u22C8':'bowtie','\u22C9':'ltimes','\u22CA':'rtimes','\u22CB':'lthree','\u22CC':'rthree','\u22CD':'bsime','\u22CE':'cuvee','\u22CF':'cuwed','\u22D0':'Sub','\u22D1':'Sup','\u22D2':'Cap','\u22D3':'Cup','\u22D4':'fork','\u22D5':'epar','\u22D6':'ltdot','\u22D7':'gtdot','\u22D8':'Ll','\u22D8\u0338':'nLl','\u22D9':'Gg','\u22D9\u0338':'nGg','\u22DA\uFE00':'lesg','\u22DA':'leg','\u22DB':'gel','\u22DB\uFE00':'gesl','\u22DE':'cuepr','\u22DF':'cuesc','\u22E6':'lnsim','\u22E7':'gnsim','\u22E8':'prnsim','\u22E9':'scnsim','\u22EE':'vellip','\u22EF':'ctdot','\u22F0':'utdot','\u22F1':'dtdot','\u22F2':'disin','\u22F3':'isinsv','\u22F4':'isins','\u22F5':'isindot','\u22F5\u0338':'notindot','\u22F6':'notinvc','\u22F7':'notinvb','\u22F9':'isinE','\u22F9\u0338':'notinE','\u22FA':'nisd','\u22FB':'xnis','\u22FC':'nis','\u22FD':'notnivc','\u22FE':'notnivb','\u2305':'barwed','\u2306':'Barwed','\u230C':'drcrop','\u230D':'dlcrop','\u230E':'urcrop','\u230F':'ulcrop','\u2310':'bnot','\u2312':'profline','\u2313':'profsurf','\u2315':'telrec','\u2316':'target','\u231C':'ulcorn','\u231D':'urcorn','\u231E':'dlcorn','\u231F':'drcorn','\u2322':'frown','\u2323':'smile','\u232D':'cylcty','\u232E':'profalar','\u2336':'topbot','\u233D':'ovbar','\u233F':'solbar','\u237C':'angzarr','\u23B0':'lmoust','\u23B1':'rmoust','\u23B4':'tbrk','\u23B5':'bbrk','\u23B6':'bbrktbrk','\u23DC':'OverParenthesis','\u23DD':'UnderParenthesis','\u23DE':'OverBrace','\u23DF':'UnderBrace','\u23E2':'trpezium','\u23E7':'elinters','\u2423':'blank','\u2500':'boxh','\u2502':'boxv','\u250C':'boxdr','\u2510':'boxdl','\u2514':'boxur','\u2518':'boxul','\u251C':'boxvr','\u2524':'boxvl','\u252C':'boxhd','\u2534':'boxhu','\u253C':'boxvh','\u2550':'boxH','\u2551':'boxV','\u2552':'boxdR','\u2553':'boxDr','\u2554':'boxDR','\u2555':'boxdL','\u2556':'boxDl','\u2557':'boxDL','\u2558':'boxuR','\u2559':'boxUr','\u255A':'boxUR','\u255B':'boxuL','\u255C':'boxUl','\u255D':'boxUL','\u255E':'boxvR','\u255F':'boxVr','\u2560':'boxVR','\u2561':'boxvL','\u2562':'boxVl','\u2563':'boxVL','\u2564':'boxHd','\u2565':'boxhD','\u2566':'boxHD','\u2567':'boxHu','\u2568':'boxhU','\u2569':'boxHU','\u256A':'boxvH','\u256B':'boxVh','\u256C':'boxVH','\u2580':'uhblk','\u2584':'lhblk','\u2588':'block','\u2591':'blk14','\u2592':'blk12','\u2593':'blk34','\u25A1':'squ','\u25AA':'squf','\u25AB':'EmptyVerySmallSquare','\u25AD':'rect','\u25AE':'marker','\u25B1':'fltns','\u25B3':'xutri','\u25B4':'utrif','\u25B5':'utri','\u25B8':'rtrif','\u25B9':'rtri','\u25BD':'xdtri','\u25BE':'dtrif','\u25BF':'dtri','\u25C2':'ltrif','\u25C3':'ltri','\u25CA':'loz','\u25CB':'cir','\u25EC':'tridot','\u25EF':'xcirc','\u25F8':'ultri','\u25F9':'urtri','\u25FA':'lltri','\u25FB':'EmptySmallSquare','\u25FC':'FilledSmallSquare','\u2605':'starf','\u2606':'star','\u260E':'phone','\u2640':'female','\u2642':'male','\u2660':'spades','\u2663':'clubs','\u2665':'hearts','\u2666':'diams','\u266A':'sung','\u2713':'check','\u2717':'cross','\u2720':'malt','\u2736':'sext','\u2758':'VerticalSeparator','\u27C8':'bsolhsub','\u27C9':'suphsol','\u27F5':'xlarr','\u27F6':'xrarr','\u27F7':'xharr','\u27F8':'xlArr','\u27F9':'xrArr','\u27FA':'xhArr','\u27FC':'xmap','\u27FF':'dzigrarr','\u2902':'nvlArr','\u2903':'nvrArr','\u2904':'nvHarr','\u2905':'Map','\u290C':'lbarr','\u290D':'rbarr','\u290E':'lBarr','\u290F':'rBarr','\u2910':'RBarr','\u2911':'DDotrahd','\u2912':'UpArrowBar','\u2913':'DownArrowBar','\u2916':'Rarrtl','\u2919':'latail','\u291A':'ratail','\u291B':'lAtail','\u291C':'rAtail','\u291D':'larrfs','\u291E':'rarrfs','\u291F':'larrbfs','\u2920':'rarrbfs','\u2923':'nwarhk','\u2924':'nearhk','\u2925':'searhk','\u2926':'swarhk','\u2927':'nwnear','\u2928':'toea','\u2929':'tosa','\u292A':'swnwar','\u2933':'rarrc','\u2933\u0338':'nrarrc','\u2935':'cudarrr','\u2936':'ldca','\u2937':'rdca','\u2938':'cudarrl','\u2939':'larrpl','\u293C':'curarrm','\u293D':'cularrp','\u2945':'rarrpl','\u2948':'harrcir','\u2949':'Uarrocir','\u294A':'lurdshar','\u294B':'ldrushar','\u294E':'LeftRightVector','\u294F':'RightUpDownVector','\u2950':'DownLeftRightVector','\u2951':'LeftUpDownVector','\u2952':'LeftVectorBar','\u2953':'RightVectorBar','\u2954':'RightUpVectorBar','\u2955':'RightDownVectorBar','\u2956':'DownLeftVectorBar','\u2957':'DownRightVectorBar','\u2958':'LeftUpVectorBar','\u2959':'LeftDownVectorBar','\u295A':'LeftTeeVector','\u295B':'RightTeeVector','\u295C':'RightUpTeeVector','\u295D':'RightDownTeeVector','\u295E':'DownLeftTeeVector','\u295F':'DownRightTeeVector','\u2960':'LeftUpTeeVector','\u2961':'LeftDownTeeVector','\u2962':'lHar','\u2963':'uHar','\u2964':'rHar','\u2965':'dHar','\u2966':'luruhar','\u2967':'ldrdhar','\u2968':'ruluhar','\u2969':'rdldhar','\u296A':'lharul','\u296B':'llhard','\u296C':'rharul','\u296D':'lrhard','\u296E':'udhar','\u296F':'duhar','\u2970':'RoundImplies','\u2971':'erarr','\u2972':'simrarr','\u2973':'larrsim','\u2974':'rarrsim','\u2975':'rarrap','\u2976':'ltlarr','\u2978':'gtrarr','\u2979':'subrarr','\u297B':'suplarr','\u297C':'lfisht','\u297D':'rfisht','\u297E':'ufisht','\u297F':'dfisht','\u299A':'vzigzag','\u299C':'vangrt','\u299D':'angrtvbd','\u29A4':'ange','\u29A5':'range','\u29A6':'dwangle','\u29A7':'uwangle','\u29A8':'angmsdaa','\u29A9':'angmsdab','\u29AA':'angmsdac','\u29AB':'angmsdad','\u29AC':'angmsdae','\u29AD':'angmsdaf','\u29AE':'angmsdag','\u29AF':'angmsdah','\u29B0':'bemptyv','\u29B1':'demptyv','\u29B2':'cemptyv','\u29B3':'raemptyv','\u29B4':'laemptyv','\u29B5':'ohbar','\u29B6':'omid','\u29B7':'opar','\u29B9':'operp','\u29BB':'olcross','\u29BC':'odsold','\u29BE':'olcir','\u29BF':'ofcir','\u29C0':'olt','\u29C1':'ogt','\u29C2':'cirscir','\u29C3':'cirE','\u29C4':'solb','\u29C5':'bsolb','\u29C9':'boxbox','\u29CD':'trisb','\u29CE':'rtriltri','\u29CF':'LeftTriangleBar','\u29CF\u0338':'NotLeftTriangleBar','\u29D0':'RightTriangleBar','\u29D0\u0338':'NotRightTriangleBar','\u29DC':'iinfin','\u29DD':'infintie','\u29DE':'nvinfin','\u29E3':'eparsl','\u29E4':'smeparsl','\u29E5':'eqvparsl','\u29EB':'lozf','\u29F4':'RuleDelayed','\u29F6':'dsol','\u2A00':'xodot','\u2A01':'xoplus','\u2A02':'xotime','\u2A04':'xuplus','\u2A06':'xsqcup','\u2A0D':'fpartint','\u2A10':'cirfnint','\u2A11':'awint','\u2A12':'rppolint','\u2A13':'scpolint','\u2A14':'npolint','\u2A15':'pointint','\u2A16':'quatint','\u2A17':'intlarhk','\u2A22':'pluscir','\u2A23':'plusacir','\u2A24':'simplus','\u2A25':'plusdu','\u2A26':'plussim','\u2A27':'plustwo','\u2A29':'mcomma','\u2A2A':'minusdu','\u2A2D':'loplus','\u2A2E':'roplus','\u2A2F':'Cross','\u2A30':'timesd','\u2A31':'timesbar','\u2A33':'smashp','\u2A34':'lotimes','\u2A35':'rotimes','\u2A36':'otimesas','\u2A37':'Otimes','\u2A38':'odiv','\u2A39':'triplus','\u2A3A':'triminus','\u2A3B':'tritime','\u2A3C':'iprod','\u2A3F':'amalg','\u2A40':'capdot','\u2A42':'ncup','\u2A43':'ncap','\u2A44':'capand','\u2A45':'cupor','\u2A46':'cupcap','\u2A47':'capcup','\u2A48':'cupbrcap','\u2A49':'capbrcup','\u2A4A':'cupcup','\u2A4B':'capcap','\u2A4C':'ccups','\u2A4D':'ccaps','\u2A50':'ccupssm','\u2A53':'And','\u2A54':'Or','\u2A55':'andand','\u2A56':'oror','\u2A57':'orslope','\u2A58':'andslope','\u2A5A':'andv','\u2A5B':'orv','\u2A5C':'andd','\u2A5D':'ord','\u2A5F':'wedbar','\u2A66':'sdote','\u2A6A':'simdot','\u2A6D':'congdot','\u2A6D\u0338':'ncongdot','\u2A6E':'easter','\u2A6F':'apacir','\u2A70':'apE','\u2A70\u0338':'napE','\u2A71':'eplus','\u2A72':'pluse','\u2A73':'Esim','\u2A77':'eDDot','\u2A78':'equivDD','\u2A79':'ltcir','\u2A7A':'gtcir','\u2A7B':'ltquest','\u2A7C':'gtquest','\u2A7D':'les','\u2A7D\u0338':'nles','\u2A7E':'ges','\u2A7E\u0338':'nges','\u2A7F':'lesdot','\u2A80':'gesdot','\u2A81':'lesdoto','\u2A82':'gesdoto','\u2A83':'lesdotor','\u2A84':'gesdotol','\u2A85':'lap','\u2A86':'gap','\u2A87':'lne','\u2A88':'gne','\u2A89':'lnap','\u2A8A':'gnap','\u2A8B':'lEg','\u2A8C':'gEl','\u2A8D':'lsime','\u2A8E':'gsime','\u2A8F':'lsimg','\u2A90':'gsiml','\u2A91':'lgE','\u2A92':'glE','\u2A93':'lesges','\u2A94':'gesles','\u2A95':'els','\u2A96':'egs','\u2A97':'elsdot','\u2A98':'egsdot','\u2A99':'el','\u2A9A':'eg','\u2A9D':'siml','\u2A9E':'simg','\u2A9F':'simlE','\u2AA0':'simgE','\u2AA1':'LessLess','\u2AA1\u0338':'NotNestedLessLess','\u2AA2':'GreaterGreater','\u2AA2\u0338':'NotNestedGreaterGreater','\u2AA4':'glj','\u2AA5':'gla','\u2AA6':'ltcc','\u2AA7':'gtcc','\u2AA8':'lescc','\u2AA9':'gescc','\u2AAA':'smt','\u2AAB':'lat','\u2AAC':'smte','\u2AAC\uFE00':'smtes','\u2AAD':'late','\u2AAD\uFE00':'lates','\u2AAE':'bumpE','\u2AAF':'pre','\u2AAF\u0338':'npre','\u2AB0':'sce','\u2AB0\u0338':'nsce','\u2AB3':'prE','\u2AB4':'scE','\u2AB5':'prnE','\u2AB6':'scnE','\u2AB7':'prap','\u2AB8':'scap','\u2AB9':'prnap','\u2ABA':'scnap','\u2ABB':'Pr','\u2ABC':'Sc','\u2ABD':'subdot','\u2ABE':'supdot','\u2ABF':'subplus','\u2AC0':'supplus','\u2AC1':'submult','\u2AC2':'supmult','\u2AC3':'subedot','\u2AC4':'supedot','\u2AC5':'subE','\u2AC5\u0338':'nsubE','\u2AC6':'supE','\u2AC6\u0338':'nsupE','\u2AC7':'subsim','\u2AC8':'supsim','\u2ACB\uFE00':'vsubnE','\u2ACB':'subnE','\u2ACC\uFE00':'vsupnE','\u2ACC':'supnE','\u2ACF':'csub','\u2AD0':'csup','\u2AD1':'csube','\u2AD2':'csupe','\u2AD3':'subsup','\u2AD4':'supsub','\u2AD5':'subsub','\u2AD6':'supsup','\u2AD7':'suphsub','\u2AD8':'supdsub','\u2AD9':'forkv','\u2ADA':'topfork','\u2ADB':'mlcp','\u2AE4':'Dashv','\u2AE6':'Vdashl','\u2AE7':'Barv','\u2AE8':'vBar','\u2AE9':'vBarv','\u2AEB':'Vbar','\u2AEC':'Not','\u2AED':'bNot','\u2AEE':'rnmid','\u2AEF':'cirmid','\u2AF0':'midcir','\u2AF1':'topcir','\u2AF2':'nhpar','\u2AF3':'parsim','\u2AFD':'parsl','\u2AFD\u20E5':'nparsl','\u266D':'flat','\u266E':'natur','\u266F':'sharp','\xA4':'curren','\xA2':'cent','$':'dollar','\xA3':'pound','\xA5':'yen','\u20AC':'euro','\xB9':'sup1','\xBD':'half','\u2153':'frac13','\xBC':'frac14','\u2155':'frac15','\u2159':'frac16','\u215B':'frac18','\xB2':'sup2','\u2154':'frac23','\u2156':'frac25','\xB3':'sup3','\xBE':'frac34','\u2157':'frac35','\u215C':'frac38','\u2158':'frac45','\u215A':'frac56','\u215D':'frac58','\u215E':'frac78','\uD835\uDCB6':'ascr','\uD835\uDD52':'aopf','\uD835\uDD1E':'afr','\uD835\uDD38':'Aopf','\uD835\uDD04':'Afr','\uD835\uDC9C':'Ascr','\xAA':'ordf','\xE1':'aacute','\xC1':'Aacute','\xE0':'agrave','\xC0':'Agrave','\u0103':'abreve','\u0102':'Abreve','\xE2':'acirc','\xC2':'Acirc','\xE5':'aring','\xC5':'angst','\xE4':'auml','\xC4':'Auml','\xE3':'atilde','\xC3':'Atilde','\u0105':'aogon','\u0104':'Aogon','\u0101':'amacr','\u0100':'Amacr','\xE6':'aelig','\xC6':'AElig','\uD835\uDCB7':'bscr','\uD835\uDD53':'bopf','\uD835\uDD1F':'bfr','\uD835\uDD39':'Bopf','\u212C':'Bscr','\uD835\uDD05':'Bfr','\uD835\uDD20':'cfr','\uD835\uDCB8':'cscr','\uD835\uDD54':'copf','\u212D':'Cfr','\uD835\uDC9E':'Cscr','\u2102':'Copf','\u0107':'cacute','\u0106':'Cacute','\u0109':'ccirc','\u0108':'Ccirc','\u010D':'ccaron','\u010C':'Ccaron','\u010B':'cdot','\u010A':'Cdot','\xE7':'ccedil','\xC7':'Ccedil','\u2105':'incare','\uD835\uDD21':'dfr','\u2146':'dd','\uD835\uDD55':'dopf','\uD835\uDCB9':'dscr','\uD835\uDC9F':'Dscr','\uD835\uDD07':'Dfr','\u2145':'DD','\uD835\uDD3B':'Dopf','\u010F':'dcaron','\u010E':'Dcaron','\u0111':'dstrok','\u0110':'Dstrok','\xF0':'eth','\xD0':'ETH','\u2147':'ee','\u212F':'escr','\uD835\uDD22':'efr','\uD835\uDD56':'eopf','\u2130':'Escr','\uD835\uDD08':'Efr','\uD835\uDD3C':'Eopf','\xE9':'eacute','\xC9':'Eacute','\xE8':'egrave','\xC8':'Egrave','\xEA':'ecirc','\xCA':'Ecirc','\u011B':'ecaron','\u011A':'Ecaron','\xEB':'euml','\xCB':'Euml','\u0117':'edot','\u0116':'Edot','\u0119':'eogon','\u0118':'Eogon','\u0113':'emacr','\u0112':'Emacr','\uD835\uDD23':'ffr','\uD835\uDD57':'fopf','\uD835\uDCBB':'fscr','\uD835\uDD09':'Ffr','\uD835\uDD3D':'Fopf','\u2131':'Fscr','\uFB00':'fflig','\uFB03':'ffilig','\uFB04':'ffllig','\uFB01':'filig','fj':'fjlig','\uFB02':'fllig','\u0192':'fnof','\u210A':'gscr','\uD835\uDD58':'gopf','\uD835\uDD24':'gfr','\uD835\uDCA2':'Gscr','\uD835\uDD3E':'Gopf','\uD835\uDD0A':'Gfr','\u01F5':'gacute','\u011F':'gbreve','\u011E':'Gbreve','\u011D':'gcirc','\u011C':'Gcirc','\u0121':'gdot','\u0120':'Gdot','\u0122':'Gcedil','\uD835\uDD25':'hfr','\u210E':'planckh','\uD835\uDCBD':'hscr','\uD835\uDD59':'hopf','\u210B':'Hscr','\u210C':'Hfr','\u210D':'Hopf','\u0125':'hcirc','\u0124':'Hcirc','\u210F':'hbar','\u0127':'hstrok','\u0126':'Hstrok','\uD835\uDD5A':'iopf','\uD835\uDD26':'ifr','\uD835\uDCBE':'iscr','\u2148':'ii','\uD835\uDD40':'Iopf','\u2110':'Iscr','\u2111':'Im','\xED':'iacute','\xCD':'Iacute','\xEC':'igrave','\xCC':'Igrave','\xEE':'icirc','\xCE':'Icirc','\xEF':'iuml','\xCF':'Iuml','\u0129':'itilde','\u0128':'Itilde','\u0130':'Idot','\u012F':'iogon','\u012E':'Iogon','\u012B':'imacr','\u012A':'Imacr','\u0133':'ijlig','\u0132':'IJlig','\u0131':'imath','\uD835\uDCBF':'jscr','\uD835\uDD5B':'jopf','\uD835\uDD27':'jfr','\uD835\uDCA5':'Jscr','\uD835\uDD0D':'Jfr','\uD835\uDD41':'Jopf','\u0135':'jcirc','\u0134':'Jcirc','\u0237':'jmath','\uD835\uDD5C':'kopf','\uD835\uDCC0':'kscr','\uD835\uDD28':'kfr','\uD835\uDCA6':'Kscr','\uD835\uDD42':'Kopf','\uD835\uDD0E':'Kfr','\u0137':'kcedil','\u0136':'Kcedil','\uD835\uDD29':'lfr','\uD835\uDCC1':'lscr','\u2113':'ell','\uD835\uDD5D':'lopf','\u2112':'Lscr','\uD835\uDD0F':'Lfr','\uD835\uDD43':'Lopf','\u013A':'lacute','\u0139':'Lacute','\u013E':'lcaron','\u013D':'Lcaron','\u013C':'lcedil','\u013B':'Lcedil','\u0142':'lstrok','\u0141':'Lstrok','\u0140':'lmidot','\u013F':'Lmidot','\uD835\uDD2A':'mfr','\uD835\uDD5E':'mopf','\uD835\uDCC2':'mscr','\uD835\uDD10':'Mfr','\uD835\uDD44':'Mopf','\u2133':'Mscr','\uD835\uDD2B':'nfr','\uD835\uDD5F':'nopf','\uD835\uDCC3':'nscr','\u2115':'Nopf','\uD835\uDCA9':'Nscr','\uD835\uDD11':'Nfr','\u0144':'nacute','\u0143':'Nacute','\u0148':'ncaron','\u0147':'Ncaron','\xF1':'ntilde','\xD1':'Ntilde','\u0146':'ncedil','\u0145':'Ncedil','\u2116':'numero','\u014B':'eng','\u014A':'ENG','\uD835\uDD60':'oopf','\uD835\uDD2C':'ofr','\u2134':'oscr','\uD835\uDCAA':'Oscr','\uD835\uDD12':'Ofr','\uD835\uDD46':'Oopf','\xBA':'ordm','\xF3':'oacute','\xD3':'Oacute','\xF2':'ograve','\xD2':'Ograve','\xF4':'ocirc','\xD4':'Ocirc','\xF6':'ouml','\xD6':'Ouml','\u0151':'odblac','\u0150':'Odblac','\xF5':'otilde','\xD5':'Otilde','\xF8':'oslash','\xD8':'Oslash','\u014D':'omacr','\u014C':'Omacr','\u0153':'oelig','\u0152':'OElig','\uD835\uDD2D':'pfr','\uD835\uDCC5':'pscr','\uD835\uDD61':'popf','\u2119':'Popf','\uD835\uDD13':'Pfr','\uD835\uDCAB':'Pscr','\uD835\uDD62':'qopf','\uD835\uDD2E':'qfr','\uD835\uDCC6':'qscr','\uD835\uDCAC':'Qscr','\uD835\uDD14':'Qfr','\u211A':'Qopf','\u0138':'kgreen','\uD835\uDD2F':'rfr','\uD835\uDD63':'ropf','\uD835\uDCC7':'rscr','\u211B':'Rscr','\u211C':'Re','\u211D':'Ropf','\u0155':'racute','\u0154':'Racute','\u0159':'rcaron','\u0158':'Rcaron','\u0157':'rcedil','\u0156':'Rcedil','\uD835\uDD64':'sopf','\uD835\uDCC8':'sscr','\uD835\uDD30':'sfr','\uD835\uDD4A':'Sopf','\uD835\uDD16':'Sfr','\uD835\uDCAE':'Sscr','\u24C8':'oS','\u015B':'sacute','\u015A':'Sacute','\u015D':'scirc','\u015C':'Scirc','\u0161':'scaron','\u0160':'Scaron','\u015F':'scedil','\u015E':'Scedil','\xDF':'szlig','\uD835\uDD31':'tfr','\uD835\uDCC9':'tscr','\uD835\uDD65':'topf','\uD835\uDCAF':'Tscr','\uD835\uDD17':'Tfr','\uD835\uDD4B':'Topf','\u0165':'tcaron','\u0164':'Tcaron','\u0163':'tcedil','\u0162':'Tcedil','\u2122':'trade','\u0167':'tstrok','\u0166':'Tstrok','\uD835\uDCCA':'uscr','\uD835\uDD66':'uopf','\uD835\uDD32':'ufr','\uD835\uDD4C':'Uopf','\uD835\uDD18':'Ufr','\uD835\uDCB0':'Uscr','\xFA':'uacute','\xDA':'Uacute','\xF9':'ugrave','\xD9':'Ugrave','\u016D':'ubreve','\u016C':'Ubreve','\xFB':'ucirc','\xDB':'Ucirc','\u016F':'uring','\u016E':'Uring','\xFC':'uuml','\xDC':'Uuml','\u0171':'udblac','\u0170':'Udblac','\u0169':'utilde','\u0168':'Utilde','\u0173':'uogon','\u0172':'Uogon','\u016B':'umacr','\u016A':'Umacr','\uD835\uDD33':'vfr','\uD835\uDD67':'vopf','\uD835\uDCCB':'vscr','\uD835\uDD19':'Vfr','\uD835\uDD4D':'Vopf','\uD835\uDCB1':'Vscr','\uD835\uDD68':'wopf','\uD835\uDCCC':'wscr','\uD835\uDD34':'wfr','\uD835\uDCB2':'Wscr','\uD835\uDD4E':'Wopf','\uD835\uDD1A':'Wfr','\u0175':'wcirc','\u0174':'Wcirc','\uD835\uDD35':'xfr','\uD835\uDCCD':'xscr','\uD835\uDD69':'xopf','\uD835\uDD4F':'Xopf','\uD835\uDD1B':'Xfr','\uD835\uDCB3':'Xscr','\uD835\uDD36':'yfr','\uD835\uDCCE':'yscr','\uD835\uDD6A':'yopf','\uD835\uDCB4':'Yscr','\uD835\uDD1C':'Yfr','\uD835\uDD50':'Yopf','\xFD':'yacute','\xDD':'Yacute','\u0177':'ycirc','\u0176':'Ycirc','\xFF':'yuml','\u0178':'Yuml','\uD835\uDCCF':'zscr','\uD835\uDD37':'zfr','\uD835\uDD6B':'zopf','\u2128':'Zfr','\u2124':'Zopf','\uD835\uDCB5':'Zscr','\u017A':'zacute','\u0179':'Zacute','\u017E':'zcaron','\u017D':'Zcaron','\u017C':'zdot','\u017B':'Zdot','\u01B5':'imped','\xFE':'thorn','\xDE':'THORN','\u0149':'napos','\u03B1':'alpha','\u0391':'Alpha','\u03B2':'beta','\u0392':'Beta','\u03B3':'gamma','\u0393':'Gamma','\u03B4':'delta','\u0394':'Delta','\u03B5':'epsi','\u03F5':'epsiv','\u0395':'Epsilon','\u03DD':'gammad','\u03DC':'Gammad','\u03B6':'zeta','\u0396':'Zeta','\u03B7':'eta','\u0397':'Eta','\u03B8':'theta','\u03D1':'thetav','\u0398':'Theta','\u03B9':'iota','\u0399':'Iota','\u03BA':'kappa','\u03F0':'kappav','\u039A':'Kappa','\u03BB':'lambda','\u039B':'Lambda','\u03BC':'mu','\xB5':'micro','\u039C':'Mu','\u03BD':'nu','\u039D':'Nu','\u03BE':'xi','\u039E':'Xi','\u03BF':'omicron','\u039F':'Omicron','\u03C0':'pi','\u03D6':'piv','\u03A0':'Pi','\u03C1':'rho','\u03F1':'rhov','\u03A1':'Rho','\u03C3':'sigma','\u03A3':'Sigma','\u03C2':'sigmaf','\u03C4':'tau','\u03A4':'Tau','\u03C5':'upsi','\u03A5':'Upsilon','\u03D2':'Upsi','\u03C6':'phi','\u03D5':'phiv','\u03A6':'Phi','\u03C7':'chi','\u03A7':'Chi','\u03C8':'psi','\u03A8':'Psi','\u03C9':'omega','\u03A9':'ohm','\u0430':'acy','\u0410':'Acy','\u0431':'bcy','\u0411':'Bcy','\u0432':'vcy','\u0412':'Vcy','\u0433':'gcy','\u0413':'Gcy','\u0453':'gjcy','\u0403':'GJcy','\u0434':'dcy','\u0414':'Dcy','\u0452':'djcy','\u0402':'DJcy','\u0435':'iecy','\u0415':'IEcy','\u0451':'iocy','\u0401':'IOcy','\u0454':'jukcy','\u0404':'Jukcy','\u0436':'zhcy','\u0416':'ZHcy','\u0437':'zcy','\u0417':'Zcy','\u0455':'dscy','\u0405':'DScy','\u0438':'icy','\u0418':'Icy','\u0456':'iukcy','\u0406':'Iukcy','\u0457':'yicy','\u0407':'YIcy','\u0439':'jcy','\u0419':'Jcy','\u0458':'jsercy','\u0408':'Jsercy','\u043A':'kcy','\u041A':'Kcy','\u045C':'kjcy','\u040C':'KJcy','\u043B':'lcy','\u041B':'Lcy','\u0459':'ljcy','\u0409':'LJcy','\u043C':'mcy','\u041C':'Mcy','\u043D':'ncy','\u041D':'Ncy','\u045A':'njcy','\u040A':'NJcy','\u043E':'ocy','\u041E':'Ocy','\u043F':'pcy','\u041F':'Pcy','\u0440':'rcy','\u0420':'Rcy','\u0441':'scy','\u0421':'Scy','\u0442':'tcy','\u0422':'Tcy','\u045B':'tshcy','\u040B':'TSHcy','\u0443':'ucy','\u0423':'Ucy','\u045E':'ubrcy','\u040E':'Ubrcy','\u0444':'fcy','\u0424':'Fcy','\u0445':'khcy','\u0425':'KHcy','\u0446':'tscy','\u0426':'TScy','\u0447':'chcy','\u0427':'CHcy','\u045F':'dzcy','\u040F':'DZcy','\u0448':'shcy','\u0428':'SHcy','\u0449':'shchcy','\u0429':'SHCHcy','\u044A':'hardcy','\u042A':'HARDcy','\u044B':'ycy','\u042B':'Ycy','\u044C':'softcy','\u042C':'SOFTcy','\u044D':'ecy','\u042D':'Ecy','\u044E':'yucy','\u042E':'YUcy','\u044F':'yacy','\u042F':'YAcy','\u2135':'aleph','\u2136':'beth','\u2137':'gimel','\u2138':'daleth'}; + + var regexEscape = /["&'<>`]/g; + var escapeMap = { + '"': '"', + '&': '&', + '\'': ''', + '<': '<', + // See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the + // following is not strictly necessary unless it’s part of a tag or an + // unquoted attribute value. We’re only escaping it to support those + // situations, and for XML support. + '>': '>', + // In Internet Explorer ≤ 8, the backtick character can be used + // to break out of (un)quoted attribute values or HTML comments. + // See http://html5sec.org/#102, http://html5sec.org/#108, and + // http://html5sec.org/#133. + '`': '`' + }; + + var regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/; + var regexInvalidRawCodePoint = /[\0-\x08\x0B\x0E-\x1F\x7F-\x9F\uFDD0-\uFDEF\uFFFE\uFFFF]|[\uD83F\uD87F\uD8BF\uD8FF\uD93F\uD97F\uD9BF\uD9FF\uDA3F\uDA7F\uDABF\uDAFF\uDB3F\uDB7F\uDBBF\uDBFF][\uDFFE\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; + var regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g; + var decodeMap = {'aacute':'\xE1','Aacute':'\xC1','abreve':'\u0103','Abreve':'\u0102','ac':'\u223E','acd':'\u223F','acE':'\u223E\u0333','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','acy':'\u0430','Acy':'\u0410','aelig':'\xE6','AElig':'\xC6','af':'\u2061','afr':'\uD835\uDD1E','Afr':'\uD835\uDD04','agrave':'\xE0','Agrave':'\xC0','alefsym':'\u2135','aleph':'\u2135','alpha':'\u03B1','Alpha':'\u0391','amacr':'\u0101','Amacr':'\u0100','amalg':'\u2A3F','amp':'&','AMP':'&','and':'\u2227','And':'\u2A53','andand':'\u2A55','andd':'\u2A5C','andslope':'\u2A58','andv':'\u2A5A','ang':'\u2220','ange':'\u29A4','angle':'\u2220','angmsd':'\u2221','angmsdaa':'\u29A8','angmsdab':'\u29A9','angmsdac':'\u29AA','angmsdad':'\u29AB','angmsdae':'\u29AC','angmsdaf':'\u29AD','angmsdag':'\u29AE','angmsdah':'\u29AF','angrt':'\u221F','angrtvb':'\u22BE','angrtvbd':'\u299D','angsph':'\u2222','angst':'\xC5','angzarr':'\u237C','aogon':'\u0105','Aogon':'\u0104','aopf':'\uD835\uDD52','Aopf':'\uD835\uDD38','ap':'\u2248','apacir':'\u2A6F','ape':'\u224A','apE':'\u2A70','apid':'\u224B','apos':'\'','ApplyFunction':'\u2061','approx':'\u2248','approxeq':'\u224A','aring':'\xE5','Aring':'\xC5','ascr':'\uD835\uDCB6','Ascr':'\uD835\uDC9C','Assign':'\u2254','ast':'*','asymp':'\u2248','asympeq':'\u224D','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','awconint':'\u2233','awint':'\u2A11','backcong':'\u224C','backepsilon':'\u03F6','backprime':'\u2035','backsim':'\u223D','backsimeq':'\u22CD','Backslash':'\u2216','Barv':'\u2AE7','barvee':'\u22BD','barwed':'\u2305','Barwed':'\u2306','barwedge':'\u2305','bbrk':'\u23B5','bbrktbrk':'\u23B6','bcong':'\u224C','bcy':'\u0431','Bcy':'\u0411','bdquo':'\u201E','becaus':'\u2235','because':'\u2235','Because':'\u2235','bemptyv':'\u29B0','bepsi':'\u03F6','bernou':'\u212C','Bernoullis':'\u212C','beta':'\u03B2','Beta':'\u0392','beth':'\u2136','between':'\u226C','bfr':'\uD835\uDD1F','Bfr':'\uD835\uDD05','bigcap':'\u22C2','bigcirc':'\u25EF','bigcup':'\u22C3','bigodot':'\u2A00','bigoplus':'\u2A01','bigotimes':'\u2A02','bigsqcup':'\u2A06','bigstar':'\u2605','bigtriangledown':'\u25BD','bigtriangleup':'\u25B3','biguplus':'\u2A04','bigvee':'\u22C1','bigwedge':'\u22C0','bkarow':'\u290D','blacklozenge':'\u29EB','blacksquare':'\u25AA','blacktriangle':'\u25B4','blacktriangledown':'\u25BE','blacktriangleleft':'\u25C2','blacktriangleright':'\u25B8','blank':'\u2423','blk12':'\u2592','blk14':'\u2591','blk34':'\u2593','block':'\u2588','bne':'=\u20E5','bnequiv':'\u2261\u20E5','bnot':'\u2310','bNot':'\u2AED','bopf':'\uD835\uDD53','Bopf':'\uD835\uDD39','bot':'\u22A5','bottom':'\u22A5','bowtie':'\u22C8','boxbox':'\u29C9','boxdl':'\u2510','boxdL':'\u2555','boxDl':'\u2556','boxDL':'\u2557','boxdr':'\u250C','boxdR':'\u2552','boxDr':'\u2553','boxDR':'\u2554','boxh':'\u2500','boxH':'\u2550','boxhd':'\u252C','boxhD':'\u2565','boxHd':'\u2564','boxHD':'\u2566','boxhu':'\u2534','boxhU':'\u2568','boxHu':'\u2567','boxHU':'\u2569','boxminus':'\u229F','boxplus':'\u229E','boxtimes':'\u22A0','boxul':'\u2518','boxuL':'\u255B','boxUl':'\u255C','boxUL':'\u255D','boxur':'\u2514','boxuR':'\u2558','boxUr':'\u2559','boxUR':'\u255A','boxv':'\u2502','boxV':'\u2551','boxvh':'\u253C','boxvH':'\u256A','boxVh':'\u256B','boxVH':'\u256C','boxvl':'\u2524','boxvL':'\u2561','boxVl':'\u2562','boxVL':'\u2563','boxvr':'\u251C','boxvR':'\u255E','boxVr':'\u255F','boxVR':'\u2560','bprime':'\u2035','breve':'\u02D8','Breve':'\u02D8','brvbar':'\xA6','bscr':'\uD835\uDCB7','Bscr':'\u212C','bsemi':'\u204F','bsim':'\u223D','bsime':'\u22CD','bsol':'\\','bsolb':'\u29C5','bsolhsub':'\u27C8','bull':'\u2022','bullet':'\u2022','bump':'\u224E','bumpe':'\u224F','bumpE':'\u2AAE','bumpeq':'\u224F','Bumpeq':'\u224E','cacute':'\u0107','Cacute':'\u0106','cap':'\u2229','Cap':'\u22D2','capand':'\u2A44','capbrcup':'\u2A49','capcap':'\u2A4B','capcup':'\u2A47','capdot':'\u2A40','CapitalDifferentialD':'\u2145','caps':'\u2229\uFE00','caret':'\u2041','caron':'\u02C7','Cayleys':'\u212D','ccaps':'\u2A4D','ccaron':'\u010D','Ccaron':'\u010C','ccedil':'\xE7','Ccedil':'\xC7','ccirc':'\u0109','Ccirc':'\u0108','Cconint':'\u2230','ccups':'\u2A4C','ccupssm':'\u2A50','cdot':'\u010B','Cdot':'\u010A','cedil':'\xB8','Cedilla':'\xB8','cemptyv':'\u29B2','cent':'\xA2','centerdot':'\xB7','CenterDot':'\xB7','cfr':'\uD835\uDD20','Cfr':'\u212D','chcy':'\u0447','CHcy':'\u0427','check':'\u2713','checkmark':'\u2713','chi':'\u03C7','Chi':'\u03A7','cir':'\u25CB','circ':'\u02C6','circeq':'\u2257','circlearrowleft':'\u21BA','circlearrowright':'\u21BB','circledast':'\u229B','circledcirc':'\u229A','circleddash':'\u229D','CircleDot':'\u2299','circledR':'\xAE','circledS':'\u24C8','CircleMinus':'\u2296','CirclePlus':'\u2295','CircleTimes':'\u2297','cire':'\u2257','cirE':'\u29C3','cirfnint':'\u2A10','cirmid':'\u2AEF','cirscir':'\u29C2','ClockwiseContourIntegral':'\u2232','CloseCurlyDoubleQuote':'\u201D','CloseCurlyQuote':'\u2019','clubs':'\u2663','clubsuit':'\u2663','colon':':','Colon':'\u2237','colone':'\u2254','Colone':'\u2A74','coloneq':'\u2254','comma':',','commat':'@','comp':'\u2201','compfn':'\u2218','complement':'\u2201','complexes':'\u2102','cong':'\u2245','congdot':'\u2A6D','Congruent':'\u2261','conint':'\u222E','Conint':'\u222F','ContourIntegral':'\u222E','copf':'\uD835\uDD54','Copf':'\u2102','coprod':'\u2210','Coproduct':'\u2210','copy':'\xA9','COPY':'\xA9','copysr':'\u2117','CounterClockwiseContourIntegral':'\u2233','crarr':'\u21B5','cross':'\u2717','Cross':'\u2A2F','cscr':'\uD835\uDCB8','Cscr':'\uD835\uDC9E','csub':'\u2ACF','csube':'\u2AD1','csup':'\u2AD0','csupe':'\u2AD2','ctdot':'\u22EF','cudarrl':'\u2938','cudarrr':'\u2935','cuepr':'\u22DE','cuesc':'\u22DF','cularr':'\u21B6','cularrp':'\u293D','cup':'\u222A','Cup':'\u22D3','cupbrcap':'\u2A48','cupcap':'\u2A46','CupCap':'\u224D','cupcup':'\u2A4A','cupdot':'\u228D','cupor':'\u2A45','cups':'\u222A\uFE00','curarr':'\u21B7','curarrm':'\u293C','curlyeqprec':'\u22DE','curlyeqsucc':'\u22DF','curlyvee':'\u22CE','curlywedge':'\u22CF','curren':'\xA4','curvearrowleft':'\u21B6','curvearrowright':'\u21B7','cuvee':'\u22CE','cuwed':'\u22CF','cwconint':'\u2232','cwint':'\u2231','cylcty':'\u232D','dagger':'\u2020','Dagger':'\u2021','daleth':'\u2138','darr':'\u2193','dArr':'\u21D3','Darr':'\u21A1','dash':'\u2010','dashv':'\u22A3','Dashv':'\u2AE4','dbkarow':'\u290F','dblac':'\u02DD','dcaron':'\u010F','Dcaron':'\u010E','dcy':'\u0434','Dcy':'\u0414','dd':'\u2146','DD':'\u2145','ddagger':'\u2021','ddarr':'\u21CA','DDotrahd':'\u2911','ddotseq':'\u2A77','deg':'\xB0','Del':'\u2207','delta':'\u03B4','Delta':'\u0394','demptyv':'\u29B1','dfisht':'\u297F','dfr':'\uD835\uDD21','Dfr':'\uD835\uDD07','dHar':'\u2965','dharl':'\u21C3','dharr':'\u21C2','DiacriticalAcute':'\xB4','DiacriticalDot':'\u02D9','DiacriticalDoubleAcute':'\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\u02DC','diam':'\u22C4','diamond':'\u22C4','Diamond':'\u22C4','diamondsuit':'\u2666','diams':'\u2666','die':'\xA8','DifferentialD':'\u2146','digamma':'\u03DD','disin':'\u22F2','div':'\xF7','divide':'\xF7','divideontimes':'\u22C7','divonx':'\u22C7','djcy':'\u0452','DJcy':'\u0402','dlcorn':'\u231E','dlcrop':'\u230D','dollar':'$','dopf':'\uD835\uDD55','Dopf':'\uD835\uDD3B','dot':'\u02D9','Dot':'\xA8','DotDot':'\u20DC','doteq':'\u2250','doteqdot':'\u2251','DotEqual':'\u2250','dotminus':'\u2238','dotplus':'\u2214','dotsquare':'\u22A1','doublebarwedge':'\u2306','DoubleContourIntegral':'\u222F','DoubleDot':'\xA8','DoubleDownArrow':'\u21D3','DoubleLeftArrow':'\u21D0','DoubleLeftRightArrow':'\u21D4','DoubleLeftTee':'\u2AE4','DoubleLongLeftArrow':'\u27F8','DoubleLongLeftRightArrow':'\u27FA','DoubleLongRightArrow':'\u27F9','DoubleRightArrow':'\u21D2','DoubleRightTee':'\u22A8','DoubleUpArrow':'\u21D1','DoubleUpDownArrow':'\u21D5','DoubleVerticalBar':'\u2225','downarrow':'\u2193','Downarrow':'\u21D3','DownArrow':'\u2193','DownArrowBar':'\u2913','DownArrowUpArrow':'\u21F5','DownBreve':'\u0311','downdownarrows':'\u21CA','downharpoonleft':'\u21C3','downharpoonright':'\u21C2','DownLeftRightVector':'\u2950','DownLeftTeeVector':'\u295E','DownLeftVector':'\u21BD','DownLeftVectorBar':'\u2956','DownRightTeeVector':'\u295F','DownRightVector':'\u21C1','DownRightVectorBar':'\u2957','DownTee':'\u22A4','DownTeeArrow':'\u21A7','drbkarow':'\u2910','drcorn':'\u231F','drcrop':'\u230C','dscr':'\uD835\uDCB9','Dscr':'\uD835\uDC9F','dscy':'\u0455','DScy':'\u0405','dsol':'\u29F6','dstrok':'\u0111','Dstrok':'\u0110','dtdot':'\u22F1','dtri':'\u25BF','dtrif':'\u25BE','duarr':'\u21F5','duhar':'\u296F','dwangle':'\u29A6','dzcy':'\u045F','DZcy':'\u040F','dzigrarr':'\u27FF','eacute':'\xE9','Eacute':'\xC9','easter':'\u2A6E','ecaron':'\u011B','Ecaron':'\u011A','ecir':'\u2256','ecirc':'\xEA','Ecirc':'\xCA','ecolon':'\u2255','ecy':'\u044D','Ecy':'\u042D','eDDot':'\u2A77','edot':'\u0117','eDot':'\u2251','Edot':'\u0116','ee':'\u2147','efDot':'\u2252','efr':'\uD835\uDD22','Efr':'\uD835\uDD08','eg':'\u2A9A','egrave':'\xE8','Egrave':'\xC8','egs':'\u2A96','egsdot':'\u2A98','el':'\u2A99','Element':'\u2208','elinters':'\u23E7','ell':'\u2113','els':'\u2A95','elsdot':'\u2A97','emacr':'\u0113','Emacr':'\u0112','empty':'\u2205','emptyset':'\u2205','EmptySmallSquare':'\u25FB','emptyv':'\u2205','EmptyVerySmallSquare':'\u25AB','emsp':'\u2003','emsp13':'\u2004','emsp14':'\u2005','eng':'\u014B','ENG':'\u014A','ensp':'\u2002','eogon':'\u0119','Eogon':'\u0118','eopf':'\uD835\uDD56','Eopf':'\uD835\uDD3C','epar':'\u22D5','eparsl':'\u29E3','eplus':'\u2A71','epsi':'\u03B5','epsilon':'\u03B5','Epsilon':'\u0395','epsiv':'\u03F5','eqcirc':'\u2256','eqcolon':'\u2255','eqsim':'\u2242','eqslantgtr':'\u2A96','eqslantless':'\u2A95','Equal':'\u2A75','equals':'=','EqualTilde':'\u2242','equest':'\u225F','Equilibrium':'\u21CC','equiv':'\u2261','equivDD':'\u2A78','eqvparsl':'\u29E5','erarr':'\u2971','erDot':'\u2253','escr':'\u212F','Escr':'\u2130','esdot':'\u2250','esim':'\u2242','Esim':'\u2A73','eta':'\u03B7','Eta':'\u0397','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','euro':'\u20AC','excl':'!','exist':'\u2203','Exists':'\u2203','expectation':'\u2130','exponentiale':'\u2147','ExponentialE':'\u2147','fallingdotseq':'\u2252','fcy':'\u0444','Fcy':'\u0424','female':'\u2640','ffilig':'\uFB03','fflig':'\uFB00','ffllig':'\uFB04','ffr':'\uD835\uDD23','Ffr':'\uD835\uDD09','filig':'\uFB01','FilledSmallSquare':'\u25FC','FilledVerySmallSquare':'\u25AA','fjlig':'fj','flat':'\u266D','fllig':'\uFB02','fltns':'\u25B1','fnof':'\u0192','fopf':'\uD835\uDD57','Fopf':'\uD835\uDD3D','forall':'\u2200','ForAll':'\u2200','fork':'\u22D4','forkv':'\u2AD9','Fouriertrf':'\u2131','fpartint':'\u2A0D','frac12':'\xBD','frac13':'\u2153','frac14':'\xBC','frac15':'\u2155','frac16':'\u2159','frac18':'\u215B','frac23':'\u2154','frac25':'\u2156','frac34':'\xBE','frac35':'\u2157','frac38':'\u215C','frac45':'\u2158','frac56':'\u215A','frac58':'\u215D','frac78':'\u215E','frasl':'\u2044','frown':'\u2322','fscr':'\uD835\uDCBB','Fscr':'\u2131','gacute':'\u01F5','gamma':'\u03B3','Gamma':'\u0393','gammad':'\u03DD','Gammad':'\u03DC','gap':'\u2A86','gbreve':'\u011F','Gbreve':'\u011E','Gcedil':'\u0122','gcirc':'\u011D','Gcirc':'\u011C','gcy':'\u0433','Gcy':'\u0413','gdot':'\u0121','Gdot':'\u0120','ge':'\u2265','gE':'\u2267','gel':'\u22DB','gEl':'\u2A8C','geq':'\u2265','geqq':'\u2267','geqslant':'\u2A7E','ges':'\u2A7E','gescc':'\u2AA9','gesdot':'\u2A80','gesdoto':'\u2A82','gesdotol':'\u2A84','gesl':'\u22DB\uFE00','gesles':'\u2A94','gfr':'\uD835\uDD24','Gfr':'\uD835\uDD0A','gg':'\u226B','Gg':'\u22D9','ggg':'\u22D9','gimel':'\u2137','gjcy':'\u0453','GJcy':'\u0403','gl':'\u2277','gla':'\u2AA5','glE':'\u2A92','glj':'\u2AA4','gnap':'\u2A8A','gnapprox':'\u2A8A','gne':'\u2A88','gnE':'\u2269','gneq':'\u2A88','gneqq':'\u2269','gnsim':'\u22E7','gopf':'\uD835\uDD58','Gopf':'\uD835\uDD3E','grave':'`','GreaterEqual':'\u2265','GreaterEqualLess':'\u22DB','GreaterFullEqual':'\u2267','GreaterGreater':'\u2AA2','GreaterLess':'\u2277','GreaterSlantEqual':'\u2A7E','GreaterTilde':'\u2273','gscr':'\u210A','Gscr':'\uD835\uDCA2','gsim':'\u2273','gsime':'\u2A8E','gsiml':'\u2A90','gt':'>','Gt':'\u226B','GT':'>','gtcc':'\u2AA7','gtcir':'\u2A7A','gtdot':'\u22D7','gtlPar':'\u2995','gtquest':'\u2A7C','gtrapprox':'\u2A86','gtrarr':'\u2978','gtrdot':'\u22D7','gtreqless':'\u22DB','gtreqqless':'\u2A8C','gtrless':'\u2277','gtrsim':'\u2273','gvertneqq':'\u2269\uFE00','gvnE':'\u2269\uFE00','Hacek':'\u02C7','hairsp':'\u200A','half':'\xBD','hamilt':'\u210B','hardcy':'\u044A','HARDcy':'\u042A','harr':'\u2194','hArr':'\u21D4','harrcir':'\u2948','harrw':'\u21AD','Hat':'^','hbar':'\u210F','hcirc':'\u0125','Hcirc':'\u0124','hearts':'\u2665','heartsuit':'\u2665','hellip':'\u2026','hercon':'\u22B9','hfr':'\uD835\uDD25','Hfr':'\u210C','HilbertSpace':'\u210B','hksearow':'\u2925','hkswarow':'\u2926','hoarr':'\u21FF','homtht':'\u223B','hookleftarrow':'\u21A9','hookrightarrow':'\u21AA','hopf':'\uD835\uDD59','Hopf':'\u210D','horbar':'\u2015','HorizontalLine':'\u2500','hscr':'\uD835\uDCBD','Hscr':'\u210B','hslash':'\u210F','hstrok':'\u0127','Hstrok':'\u0126','HumpDownHump':'\u224E','HumpEqual':'\u224F','hybull':'\u2043','hyphen':'\u2010','iacute':'\xED','Iacute':'\xCD','ic':'\u2063','icirc':'\xEE','Icirc':'\xCE','icy':'\u0438','Icy':'\u0418','Idot':'\u0130','iecy':'\u0435','IEcy':'\u0415','iexcl':'\xA1','iff':'\u21D4','ifr':'\uD835\uDD26','Ifr':'\u2111','igrave':'\xEC','Igrave':'\xCC','ii':'\u2148','iiiint':'\u2A0C','iiint':'\u222D','iinfin':'\u29DC','iiota':'\u2129','ijlig':'\u0133','IJlig':'\u0132','Im':'\u2111','imacr':'\u012B','Imacr':'\u012A','image':'\u2111','ImaginaryI':'\u2148','imagline':'\u2110','imagpart':'\u2111','imath':'\u0131','imof':'\u22B7','imped':'\u01B5','Implies':'\u21D2','in':'\u2208','incare':'\u2105','infin':'\u221E','infintie':'\u29DD','inodot':'\u0131','int':'\u222B','Int':'\u222C','intcal':'\u22BA','integers':'\u2124','Integral':'\u222B','intercal':'\u22BA','Intersection':'\u22C2','intlarhk':'\u2A17','intprod':'\u2A3C','InvisibleComma':'\u2063','InvisibleTimes':'\u2062','iocy':'\u0451','IOcy':'\u0401','iogon':'\u012F','Iogon':'\u012E','iopf':'\uD835\uDD5A','Iopf':'\uD835\uDD40','iota':'\u03B9','Iota':'\u0399','iprod':'\u2A3C','iquest':'\xBF','iscr':'\uD835\uDCBE','Iscr':'\u2110','isin':'\u2208','isindot':'\u22F5','isinE':'\u22F9','isins':'\u22F4','isinsv':'\u22F3','isinv':'\u2208','it':'\u2062','itilde':'\u0129','Itilde':'\u0128','iukcy':'\u0456','Iukcy':'\u0406','iuml':'\xEF','Iuml':'\xCF','jcirc':'\u0135','Jcirc':'\u0134','jcy':'\u0439','Jcy':'\u0419','jfr':'\uD835\uDD27','Jfr':'\uD835\uDD0D','jmath':'\u0237','jopf':'\uD835\uDD5B','Jopf':'\uD835\uDD41','jscr':'\uD835\uDCBF','Jscr':'\uD835\uDCA5','jsercy':'\u0458','Jsercy':'\u0408','jukcy':'\u0454','Jukcy':'\u0404','kappa':'\u03BA','Kappa':'\u039A','kappav':'\u03F0','kcedil':'\u0137','Kcedil':'\u0136','kcy':'\u043A','Kcy':'\u041A','kfr':'\uD835\uDD28','Kfr':'\uD835\uDD0E','kgreen':'\u0138','khcy':'\u0445','KHcy':'\u0425','kjcy':'\u045C','KJcy':'\u040C','kopf':'\uD835\uDD5C','Kopf':'\uD835\uDD42','kscr':'\uD835\uDCC0','Kscr':'\uD835\uDCA6','lAarr':'\u21DA','lacute':'\u013A','Lacute':'\u0139','laemptyv':'\u29B4','lagran':'\u2112','lambda':'\u03BB','Lambda':'\u039B','lang':'\u27E8','Lang':'\u27EA','langd':'\u2991','langle':'\u27E8','lap':'\u2A85','Laplacetrf':'\u2112','laquo':'\xAB','larr':'\u2190','lArr':'\u21D0','Larr':'\u219E','larrb':'\u21E4','larrbfs':'\u291F','larrfs':'\u291D','larrhk':'\u21A9','larrlp':'\u21AB','larrpl':'\u2939','larrsim':'\u2973','larrtl':'\u21A2','lat':'\u2AAB','latail':'\u2919','lAtail':'\u291B','late':'\u2AAD','lates':'\u2AAD\uFE00','lbarr':'\u290C','lBarr':'\u290E','lbbrk':'\u2772','lbrace':'{','lbrack':'[','lbrke':'\u298B','lbrksld':'\u298F','lbrkslu':'\u298D','lcaron':'\u013E','Lcaron':'\u013D','lcedil':'\u013C','Lcedil':'\u013B','lceil':'\u2308','lcub':'{','lcy':'\u043B','Lcy':'\u041B','ldca':'\u2936','ldquo':'\u201C','ldquor':'\u201E','ldrdhar':'\u2967','ldrushar':'\u294B','ldsh':'\u21B2','le':'\u2264','lE':'\u2266','LeftAngleBracket':'\u27E8','leftarrow':'\u2190','Leftarrow':'\u21D0','LeftArrow':'\u2190','LeftArrowBar':'\u21E4','LeftArrowRightArrow':'\u21C6','leftarrowtail':'\u21A2','LeftCeiling':'\u2308','LeftDoubleBracket':'\u27E6','LeftDownTeeVector':'\u2961','LeftDownVector':'\u21C3','LeftDownVectorBar':'\u2959','LeftFloor':'\u230A','leftharpoondown':'\u21BD','leftharpoonup':'\u21BC','leftleftarrows':'\u21C7','leftrightarrow':'\u2194','Leftrightarrow':'\u21D4','LeftRightArrow':'\u2194','leftrightarrows':'\u21C6','leftrightharpoons':'\u21CB','leftrightsquigarrow':'\u21AD','LeftRightVector':'\u294E','LeftTee':'\u22A3','LeftTeeArrow':'\u21A4','LeftTeeVector':'\u295A','leftthreetimes':'\u22CB','LeftTriangle':'\u22B2','LeftTriangleBar':'\u29CF','LeftTriangleEqual':'\u22B4','LeftUpDownVector':'\u2951','LeftUpTeeVector':'\u2960','LeftUpVector':'\u21BF','LeftUpVectorBar':'\u2958','LeftVector':'\u21BC','LeftVectorBar':'\u2952','leg':'\u22DA','lEg':'\u2A8B','leq':'\u2264','leqq':'\u2266','leqslant':'\u2A7D','les':'\u2A7D','lescc':'\u2AA8','lesdot':'\u2A7F','lesdoto':'\u2A81','lesdotor':'\u2A83','lesg':'\u22DA\uFE00','lesges':'\u2A93','lessapprox':'\u2A85','lessdot':'\u22D6','lesseqgtr':'\u22DA','lesseqqgtr':'\u2A8B','LessEqualGreater':'\u22DA','LessFullEqual':'\u2266','LessGreater':'\u2276','lessgtr':'\u2276','LessLess':'\u2AA1','lesssim':'\u2272','LessSlantEqual':'\u2A7D','LessTilde':'\u2272','lfisht':'\u297C','lfloor':'\u230A','lfr':'\uD835\uDD29','Lfr':'\uD835\uDD0F','lg':'\u2276','lgE':'\u2A91','lHar':'\u2962','lhard':'\u21BD','lharu':'\u21BC','lharul':'\u296A','lhblk':'\u2584','ljcy':'\u0459','LJcy':'\u0409','ll':'\u226A','Ll':'\u22D8','llarr':'\u21C7','llcorner':'\u231E','Lleftarrow':'\u21DA','llhard':'\u296B','lltri':'\u25FA','lmidot':'\u0140','Lmidot':'\u013F','lmoust':'\u23B0','lmoustache':'\u23B0','lnap':'\u2A89','lnapprox':'\u2A89','lne':'\u2A87','lnE':'\u2268','lneq':'\u2A87','lneqq':'\u2268','lnsim':'\u22E6','loang':'\u27EC','loarr':'\u21FD','lobrk':'\u27E6','longleftarrow':'\u27F5','Longleftarrow':'\u27F8','LongLeftArrow':'\u27F5','longleftrightarrow':'\u27F7','Longleftrightarrow':'\u27FA','LongLeftRightArrow':'\u27F7','longmapsto':'\u27FC','longrightarrow':'\u27F6','Longrightarrow':'\u27F9','LongRightArrow':'\u27F6','looparrowleft':'\u21AB','looparrowright':'\u21AC','lopar':'\u2985','lopf':'\uD835\uDD5D','Lopf':'\uD835\uDD43','loplus':'\u2A2D','lotimes':'\u2A34','lowast':'\u2217','lowbar':'_','LowerLeftArrow':'\u2199','LowerRightArrow':'\u2198','loz':'\u25CA','lozenge':'\u25CA','lozf':'\u29EB','lpar':'(','lparlt':'\u2993','lrarr':'\u21C6','lrcorner':'\u231F','lrhar':'\u21CB','lrhard':'\u296D','lrm':'\u200E','lrtri':'\u22BF','lsaquo':'\u2039','lscr':'\uD835\uDCC1','Lscr':'\u2112','lsh':'\u21B0','Lsh':'\u21B0','lsim':'\u2272','lsime':'\u2A8D','lsimg':'\u2A8F','lsqb':'[','lsquo':'\u2018','lsquor':'\u201A','lstrok':'\u0142','Lstrok':'\u0141','lt':'<','Lt':'\u226A','LT':'<','ltcc':'\u2AA6','ltcir':'\u2A79','ltdot':'\u22D6','lthree':'\u22CB','ltimes':'\u22C9','ltlarr':'\u2976','ltquest':'\u2A7B','ltri':'\u25C3','ltrie':'\u22B4','ltrif':'\u25C2','ltrPar':'\u2996','lurdshar':'\u294A','luruhar':'\u2966','lvertneqq':'\u2268\uFE00','lvnE':'\u2268\uFE00','macr':'\xAF','male':'\u2642','malt':'\u2720','maltese':'\u2720','map':'\u21A6','Map':'\u2905','mapsto':'\u21A6','mapstodown':'\u21A7','mapstoleft':'\u21A4','mapstoup':'\u21A5','marker':'\u25AE','mcomma':'\u2A29','mcy':'\u043C','Mcy':'\u041C','mdash':'\u2014','mDDot':'\u223A','measuredangle':'\u2221','MediumSpace':'\u205F','Mellintrf':'\u2133','mfr':'\uD835\uDD2A','Mfr':'\uD835\uDD10','mho':'\u2127','micro':'\xB5','mid':'\u2223','midast':'*','midcir':'\u2AF0','middot':'\xB7','minus':'\u2212','minusb':'\u229F','minusd':'\u2238','minusdu':'\u2A2A','MinusPlus':'\u2213','mlcp':'\u2ADB','mldr':'\u2026','mnplus':'\u2213','models':'\u22A7','mopf':'\uD835\uDD5E','Mopf':'\uD835\uDD44','mp':'\u2213','mscr':'\uD835\uDCC2','Mscr':'\u2133','mstpos':'\u223E','mu':'\u03BC','Mu':'\u039C','multimap':'\u22B8','mumap':'\u22B8','nabla':'\u2207','nacute':'\u0144','Nacute':'\u0143','nang':'\u2220\u20D2','nap':'\u2249','napE':'\u2A70\u0338','napid':'\u224B\u0338','napos':'\u0149','napprox':'\u2249','natur':'\u266E','natural':'\u266E','naturals':'\u2115','nbsp':'\xA0','nbump':'\u224E\u0338','nbumpe':'\u224F\u0338','ncap':'\u2A43','ncaron':'\u0148','Ncaron':'\u0147','ncedil':'\u0146','Ncedil':'\u0145','ncong':'\u2247','ncongdot':'\u2A6D\u0338','ncup':'\u2A42','ncy':'\u043D','Ncy':'\u041D','ndash':'\u2013','ne':'\u2260','nearhk':'\u2924','nearr':'\u2197','neArr':'\u21D7','nearrow':'\u2197','nedot':'\u2250\u0338','NegativeMediumSpace':'\u200B','NegativeThickSpace':'\u200B','NegativeThinSpace':'\u200B','NegativeVeryThinSpace':'\u200B','nequiv':'\u2262','nesear':'\u2928','nesim':'\u2242\u0338','NestedGreaterGreater':'\u226B','NestedLessLess':'\u226A','NewLine':'\n','nexist':'\u2204','nexists':'\u2204','nfr':'\uD835\uDD2B','Nfr':'\uD835\uDD11','nge':'\u2271','ngE':'\u2267\u0338','ngeq':'\u2271','ngeqq':'\u2267\u0338','ngeqslant':'\u2A7E\u0338','nges':'\u2A7E\u0338','nGg':'\u22D9\u0338','ngsim':'\u2275','ngt':'\u226F','nGt':'\u226B\u20D2','ngtr':'\u226F','nGtv':'\u226B\u0338','nharr':'\u21AE','nhArr':'\u21CE','nhpar':'\u2AF2','ni':'\u220B','nis':'\u22FC','nisd':'\u22FA','niv':'\u220B','njcy':'\u045A','NJcy':'\u040A','nlarr':'\u219A','nlArr':'\u21CD','nldr':'\u2025','nle':'\u2270','nlE':'\u2266\u0338','nleftarrow':'\u219A','nLeftarrow':'\u21CD','nleftrightarrow':'\u21AE','nLeftrightarrow':'\u21CE','nleq':'\u2270','nleqq':'\u2266\u0338','nleqslant':'\u2A7D\u0338','nles':'\u2A7D\u0338','nless':'\u226E','nLl':'\u22D8\u0338','nlsim':'\u2274','nlt':'\u226E','nLt':'\u226A\u20D2','nltri':'\u22EA','nltrie':'\u22EC','nLtv':'\u226A\u0338','nmid':'\u2224','NoBreak':'\u2060','NonBreakingSpace':'\xA0','nopf':'\uD835\uDD5F','Nopf':'\u2115','not':'\xAC','Not':'\u2AEC','NotCongruent':'\u2262','NotCupCap':'\u226D','NotDoubleVerticalBar':'\u2226','NotElement':'\u2209','NotEqual':'\u2260','NotEqualTilde':'\u2242\u0338','NotExists':'\u2204','NotGreater':'\u226F','NotGreaterEqual':'\u2271','NotGreaterFullEqual':'\u2267\u0338','NotGreaterGreater':'\u226B\u0338','NotGreaterLess':'\u2279','NotGreaterSlantEqual':'\u2A7E\u0338','NotGreaterTilde':'\u2275','NotHumpDownHump':'\u224E\u0338','NotHumpEqual':'\u224F\u0338','notin':'\u2209','notindot':'\u22F5\u0338','notinE':'\u22F9\u0338','notinva':'\u2209','notinvb':'\u22F7','notinvc':'\u22F6','NotLeftTriangle':'\u22EA','NotLeftTriangleBar':'\u29CF\u0338','NotLeftTriangleEqual':'\u22EC','NotLess':'\u226E','NotLessEqual':'\u2270','NotLessGreater':'\u2278','NotLessLess':'\u226A\u0338','NotLessSlantEqual':'\u2A7D\u0338','NotLessTilde':'\u2274','NotNestedGreaterGreater':'\u2AA2\u0338','NotNestedLessLess':'\u2AA1\u0338','notni':'\u220C','notniva':'\u220C','notnivb':'\u22FE','notnivc':'\u22FD','NotPrecedes':'\u2280','NotPrecedesEqual':'\u2AAF\u0338','NotPrecedesSlantEqual':'\u22E0','NotReverseElement':'\u220C','NotRightTriangle':'\u22EB','NotRightTriangleBar':'\u29D0\u0338','NotRightTriangleEqual':'\u22ED','NotSquareSubset':'\u228F\u0338','NotSquareSubsetEqual':'\u22E2','NotSquareSuperset':'\u2290\u0338','NotSquareSupersetEqual':'\u22E3','NotSubset':'\u2282\u20D2','NotSubsetEqual':'\u2288','NotSucceeds':'\u2281','NotSucceedsEqual':'\u2AB0\u0338','NotSucceedsSlantEqual':'\u22E1','NotSucceedsTilde':'\u227F\u0338','NotSuperset':'\u2283\u20D2','NotSupersetEqual':'\u2289','NotTilde':'\u2241','NotTildeEqual':'\u2244','NotTildeFullEqual':'\u2247','NotTildeTilde':'\u2249','NotVerticalBar':'\u2224','npar':'\u2226','nparallel':'\u2226','nparsl':'\u2AFD\u20E5','npart':'\u2202\u0338','npolint':'\u2A14','npr':'\u2280','nprcue':'\u22E0','npre':'\u2AAF\u0338','nprec':'\u2280','npreceq':'\u2AAF\u0338','nrarr':'\u219B','nrArr':'\u21CF','nrarrc':'\u2933\u0338','nrarrw':'\u219D\u0338','nrightarrow':'\u219B','nRightarrow':'\u21CF','nrtri':'\u22EB','nrtrie':'\u22ED','nsc':'\u2281','nsccue':'\u22E1','nsce':'\u2AB0\u0338','nscr':'\uD835\uDCC3','Nscr':'\uD835\uDCA9','nshortmid':'\u2224','nshortparallel':'\u2226','nsim':'\u2241','nsime':'\u2244','nsimeq':'\u2244','nsmid':'\u2224','nspar':'\u2226','nsqsube':'\u22E2','nsqsupe':'\u22E3','nsub':'\u2284','nsube':'\u2288','nsubE':'\u2AC5\u0338','nsubset':'\u2282\u20D2','nsubseteq':'\u2288','nsubseteqq':'\u2AC5\u0338','nsucc':'\u2281','nsucceq':'\u2AB0\u0338','nsup':'\u2285','nsupe':'\u2289','nsupE':'\u2AC6\u0338','nsupset':'\u2283\u20D2','nsupseteq':'\u2289','nsupseteqq':'\u2AC6\u0338','ntgl':'\u2279','ntilde':'\xF1','Ntilde':'\xD1','ntlg':'\u2278','ntriangleleft':'\u22EA','ntrianglelefteq':'\u22EC','ntriangleright':'\u22EB','ntrianglerighteq':'\u22ED','nu':'\u03BD','Nu':'\u039D','num':'#','numero':'\u2116','numsp':'\u2007','nvap':'\u224D\u20D2','nvdash':'\u22AC','nvDash':'\u22AD','nVdash':'\u22AE','nVDash':'\u22AF','nvge':'\u2265\u20D2','nvgt':'>\u20D2','nvHarr':'\u2904','nvinfin':'\u29DE','nvlArr':'\u2902','nvle':'\u2264\u20D2','nvlt':'<\u20D2','nvltrie':'\u22B4\u20D2','nvrArr':'\u2903','nvrtrie':'\u22B5\u20D2','nvsim':'\u223C\u20D2','nwarhk':'\u2923','nwarr':'\u2196','nwArr':'\u21D6','nwarrow':'\u2196','nwnear':'\u2927','oacute':'\xF3','Oacute':'\xD3','oast':'\u229B','ocir':'\u229A','ocirc':'\xF4','Ocirc':'\xD4','ocy':'\u043E','Ocy':'\u041E','odash':'\u229D','odblac':'\u0151','Odblac':'\u0150','odiv':'\u2A38','odot':'\u2299','odsold':'\u29BC','oelig':'\u0153','OElig':'\u0152','ofcir':'\u29BF','ofr':'\uD835\uDD2C','Ofr':'\uD835\uDD12','ogon':'\u02DB','ograve':'\xF2','Ograve':'\xD2','ogt':'\u29C1','ohbar':'\u29B5','ohm':'\u03A9','oint':'\u222E','olarr':'\u21BA','olcir':'\u29BE','olcross':'\u29BB','oline':'\u203E','olt':'\u29C0','omacr':'\u014D','Omacr':'\u014C','omega':'\u03C9','Omega':'\u03A9','omicron':'\u03BF','Omicron':'\u039F','omid':'\u29B6','ominus':'\u2296','oopf':'\uD835\uDD60','Oopf':'\uD835\uDD46','opar':'\u29B7','OpenCurlyDoubleQuote':'\u201C','OpenCurlyQuote':'\u2018','operp':'\u29B9','oplus':'\u2295','or':'\u2228','Or':'\u2A54','orarr':'\u21BB','ord':'\u2A5D','order':'\u2134','orderof':'\u2134','ordf':'\xAA','ordm':'\xBA','origof':'\u22B6','oror':'\u2A56','orslope':'\u2A57','orv':'\u2A5B','oS':'\u24C8','oscr':'\u2134','Oscr':'\uD835\uDCAA','oslash':'\xF8','Oslash':'\xD8','osol':'\u2298','otilde':'\xF5','Otilde':'\xD5','otimes':'\u2297','Otimes':'\u2A37','otimesas':'\u2A36','ouml':'\xF6','Ouml':'\xD6','ovbar':'\u233D','OverBar':'\u203E','OverBrace':'\u23DE','OverBracket':'\u23B4','OverParenthesis':'\u23DC','par':'\u2225','para':'\xB6','parallel':'\u2225','parsim':'\u2AF3','parsl':'\u2AFD','part':'\u2202','PartialD':'\u2202','pcy':'\u043F','Pcy':'\u041F','percnt':'%','period':'.','permil':'\u2030','perp':'\u22A5','pertenk':'\u2031','pfr':'\uD835\uDD2D','Pfr':'\uD835\uDD13','phi':'\u03C6','Phi':'\u03A6','phiv':'\u03D5','phmmat':'\u2133','phone':'\u260E','pi':'\u03C0','Pi':'\u03A0','pitchfork':'\u22D4','piv':'\u03D6','planck':'\u210F','planckh':'\u210E','plankv':'\u210F','plus':'+','plusacir':'\u2A23','plusb':'\u229E','pluscir':'\u2A22','plusdo':'\u2214','plusdu':'\u2A25','pluse':'\u2A72','PlusMinus':'\xB1','plusmn':'\xB1','plussim':'\u2A26','plustwo':'\u2A27','pm':'\xB1','Poincareplane':'\u210C','pointint':'\u2A15','popf':'\uD835\uDD61','Popf':'\u2119','pound':'\xA3','pr':'\u227A','Pr':'\u2ABB','prap':'\u2AB7','prcue':'\u227C','pre':'\u2AAF','prE':'\u2AB3','prec':'\u227A','precapprox':'\u2AB7','preccurlyeq':'\u227C','Precedes':'\u227A','PrecedesEqual':'\u2AAF','PrecedesSlantEqual':'\u227C','PrecedesTilde':'\u227E','preceq':'\u2AAF','precnapprox':'\u2AB9','precneqq':'\u2AB5','precnsim':'\u22E8','precsim':'\u227E','prime':'\u2032','Prime':'\u2033','primes':'\u2119','prnap':'\u2AB9','prnE':'\u2AB5','prnsim':'\u22E8','prod':'\u220F','Product':'\u220F','profalar':'\u232E','profline':'\u2312','profsurf':'\u2313','prop':'\u221D','Proportion':'\u2237','Proportional':'\u221D','propto':'\u221D','prsim':'\u227E','prurel':'\u22B0','pscr':'\uD835\uDCC5','Pscr':'\uD835\uDCAB','psi':'\u03C8','Psi':'\u03A8','puncsp':'\u2008','qfr':'\uD835\uDD2E','Qfr':'\uD835\uDD14','qint':'\u2A0C','qopf':'\uD835\uDD62','Qopf':'\u211A','qprime':'\u2057','qscr':'\uD835\uDCC6','Qscr':'\uD835\uDCAC','quaternions':'\u210D','quatint':'\u2A16','quest':'?','questeq':'\u225F','quot':'"','QUOT':'"','rAarr':'\u21DB','race':'\u223D\u0331','racute':'\u0155','Racute':'\u0154','radic':'\u221A','raemptyv':'\u29B3','rang':'\u27E9','Rang':'\u27EB','rangd':'\u2992','range':'\u29A5','rangle':'\u27E9','raquo':'\xBB','rarr':'\u2192','rArr':'\u21D2','Rarr':'\u21A0','rarrap':'\u2975','rarrb':'\u21E5','rarrbfs':'\u2920','rarrc':'\u2933','rarrfs':'\u291E','rarrhk':'\u21AA','rarrlp':'\u21AC','rarrpl':'\u2945','rarrsim':'\u2974','rarrtl':'\u21A3','Rarrtl':'\u2916','rarrw':'\u219D','ratail':'\u291A','rAtail':'\u291C','ratio':'\u2236','rationals':'\u211A','rbarr':'\u290D','rBarr':'\u290F','RBarr':'\u2910','rbbrk':'\u2773','rbrace':'}','rbrack':']','rbrke':'\u298C','rbrksld':'\u298E','rbrkslu':'\u2990','rcaron':'\u0159','Rcaron':'\u0158','rcedil':'\u0157','Rcedil':'\u0156','rceil':'\u2309','rcub':'}','rcy':'\u0440','Rcy':'\u0420','rdca':'\u2937','rdldhar':'\u2969','rdquo':'\u201D','rdquor':'\u201D','rdsh':'\u21B3','Re':'\u211C','real':'\u211C','realine':'\u211B','realpart':'\u211C','reals':'\u211D','rect':'\u25AD','reg':'\xAE','REG':'\xAE','ReverseElement':'\u220B','ReverseEquilibrium':'\u21CB','ReverseUpEquilibrium':'\u296F','rfisht':'\u297D','rfloor':'\u230B','rfr':'\uD835\uDD2F','Rfr':'\u211C','rHar':'\u2964','rhard':'\u21C1','rharu':'\u21C0','rharul':'\u296C','rho':'\u03C1','Rho':'\u03A1','rhov':'\u03F1','RightAngleBracket':'\u27E9','rightarrow':'\u2192','Rightarrow':'\u21D2','RightArrow':'\u2192','RightArrowBar':'\u21E5','RightArrowLeftArrow':'\u21C4','rightarrowtail':'\u21A3','RightCeiling':'\u2309','RightDoubleBracket':'\u27E7','RightDownTeeVector':'\u295D','RightDownVector':'\u21C2','RightDownVectorBar':'\u2955','RightFloor':'\u230B','rightharpoondown':'\u21C1','rightharpoonup':'\u21C0','rightleftarrows':'\u21C4','rightleftharpoons':'\u21CC','rightrightarrows':'\u21C9','rightsquigarrow':'\u219D','RightTee':'\u22A2','RightTeeArrow':'\u21A6','RightTeeVector':'\u295B','rightthreetimes':'\u22CC','RightTriangle':'\u22B3','RightTriangleBar':'\u29D0','RightTriangleEqual':'\u22B5','RightUpDownVector':'\u294F','RightUpTeeVector':'\u295C','RightUpVector':'\u21BE','RightUpVectorBar':'\u2954','RightVector':'\u21C0','RightVectorBar':'\u2953','ring':'\u02DA','risingdotseq':'\u2253','rlarr':'\u21C4','rlhar':'\u21CC','rlm':'\u200F','rmoust':'\u23B1','rmoustache':'\u23B1','rnmid':'\u2AEE','roang':'\u27ED','roarr':'\u21FE','robrk':'\u27E7','ropar':'\u2986','ropf':'\uD835\uDD63','Ropf':'\u211D','roplus':'\u2A2E','rotimes':'\u2A35','RoundImplies':'\u2970','rpar':')','rpargt':'\u2994','rppolint':'\u2A12','rrarr':'\u21C9','Rrightarrow':'\u21DB','rsaquo':'\u203A','rscr':'\uD835\uDCC7','Rscr':'\u211B','rsh':'\u21B1','Rsh':'\u21B1','rsqb':']','rsquo':'\u2019','rsquor':'\u2019','rthree':'\u22CC','rtimes':'\u22CA','rtri':'\u25B9','rtrie':'\u22B5','rtrif':'\u25B8','rtriltri':'\u29CE','RuleDelayed':'\u29F4','ruluhar':'\u2968','rx':'\u211E','sacute':'\u015B','Sacute':'\u015A','sbquo':'\u201A','sc':'\u227B','Sc':'\u2ABC','scap':'\u2AB8','scaron':'\u0161','Scaron':'\u0160','sccue':'\u227D','sce':'\u2AB0','scE':'\u2AB4','scedil':'\u015F','Scedil':'\u015E','scirc':'\u015D','Scirc':'\u015C','scnap':'\u2ABA','scnE':'\u2AB6','scnsim':'\u22E9','scpolint':'\u2A13','scsim':'\u227F','scy':'\u0441','Scy':'\u0421','sdot':'\u22C5','sdotb':'\u22A1','sdote':'\u2A66','searhk':'\u2925','searr':'\u2198','seArr':'\u21D8','searrow':'\u2198','sect':'\xA7','semi':';','seswar':'\u2929','setminus':'\u2216','setmn':'\u2216','sext':'\u2736','sfr':'\uD835\uDD30','Sfr':'\uD835\uDD16','sfrown':'\u2322','sharp':'\u266F','shchcy':'\u0449','SHCHcy':'\u0429','shcy':'\u0448','SHcy':'\u0428','ShortDownArrow':'\u2193','ShortLeftArrow':'\u2190','shortmid':'\u2223','shortparallel':'\u2225','ShortRightArrow':'\u2192','ShortUpArrow':'\u2191','shy':'\xAD','sigma':'\u03C3','Sigma':'\u03A3','sigmaf':'\u03C2','sigmav':'\u03C2','sim':'\u223C','simdot':'\u2A6A','sime':'\u2243','simeq':'\u2243','simg':'\u2A9E','simgE':'\u2AA0','siml':'\u2A9D','simlE':'\u2A9F','simne':'\u2246','simplus':'\u2A24','simrarr':'\u2972','slarr':'\u2190','SmallCircle':'\u2218','smallsetminus':'\u2216','smashp':'\u2A33','smeparsl':'\u29E4','smid':'\u2223','smile':'\u2323','smt':'\u2AAA','smte':'\u2AAC','smtes':'\u2AAC\uFE00','softcy':'\u044C','SOFTcy':'\u042C','sol':'/','solb':'\u29C4','solbar':'\u233F','sopf':'\uD835\uDD64','Sopf':'\uD835\uDD4A','spades':'\u2660','spadesuit':'\u2660','spar':'\u2225','sqcap':'\u2293','sqcaps':'\u2293\uFE00','sqcup':'\u2294','sqcups':'\u2294\uFE00','Sqrt':'\u221A','sqsub':'\u228F','sqsube':'\u2291','sqsubset':'\u228F','sqsubseteq':'\u2291','sqsup':'\u2290','sqsupe':'\u2292','sqsupset':'\u2290','sqsupseteq':'\u2292','squ':'\u25A1','square':'\u25A1','Square':'\u25A1','SquareIntersection':'\u2293','SquareSubset':'\u228F','SquareSubsetEqual':'\u2291','SquareSuperset':'\u2290','SquareSupersetEqual':'\u2292','SquareUnion':'\u2294','squarf':'\u25AA','squf':'\u25AA','srarr':'\u2192','sscr':'\uD835\uDCC8','Sscr':'\uD835\uDCAE','ssetmn':'\u2216','ssmile':'\u2323','sstarf':'\u22C6','star':'\u2606','Star':'\u22C6','starf':'\u2605','straightepsilon':'\u03F5','straightphi':'\u03D5','strns':'\xAF','sub':'\u2282','Sub':'\u22D0','subdot':'\u2ABD','sube':'\u2286','subE':'\u2AC5','subedot':'\u2AC3','submult':'\u2AC1','subne':'\u228A','subnE':'\u2ACB','subplus':'\u2ABF','subrarr':'\u2979','subset':'\u2282','Subset':'\u22D0','subseteq':'\u2286','subseteqq':'\u2AC5','SubsetEqual':'\u2286','subsetneq':'\u228A','subsetneqq':'\u2ACB','subsim':'\u2AC7','subsub':'\u2AD5','subsup':'\u2AD3','succ':'\u227B','succapprox':'\u2AB8','succcurlyeq':'\u227D','Succeeds':'\u227B','SucceedsEqual':'\u2AB0','SucceedsSlantEqual':'\u227D','SucceedsTilde':'\u227F','succeq':'\u2AB0','succnapprox':'\u2ABA','succneqq':'\u2AB6','succnsim':'\u22E9','succsim':'\u227F','SuchThat':'\u220B','sum':'\u2211','Sum':'\u2211','sung':'\u266A','sup':'\u2283','Sup':'\u22D1','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','supdot':'\u2ABE','supdsub':'\u2AD8','supe':'\u2287','supE':'\u2AC6','supedot':'\u2AC4','Superset':'\u2283','SupersetEqual':'\u2287','suphsol':'\u27C9','suphsub':'\u2AD7','suplarr':'\u297B','supmult':'\u2AC2','supne':'\u228B','supnE':'\u2ACC','supplus':'\u2AC0','supset':'\u2283','Supset':'\u22D1','supseteq':'\u2287','supseteqq':'\u2AC6','supsetneq':'\u228B','supsetneqq':'\u2ACC','supsim':'\u2AC8','supsub':'\u2AD4','supsup':'\u2AD6','swarhk':'\u2926','swarr':'\u2199','swArr':'\u21D9','swarrow':'\u2199','swnwar':'\u292A','szlig':'\xDF','Tab':'\t','target':'\u2316','tau':'\u03C4','Tau':'\u03A4','tbrk':'\u23B4','tcaron':'\u0165','Tcaron':'\u0164','tcedil':'\u0163','Tcedil':'\u0162','tcy':'\u0442','Tcy':'\u0422','tdot':'\u20DB','telrec':'\u2315','tfr':'\uD835\uDD31','Tfr':'\uD835\uDD17','there4':'\u2234','therefore':'\u2234','Therefore':'\u2234','theta':'\u03B8','Theta':'\u0398','thetasym':'\u03D1','thetav':'\u03D1','thickapprox':'\u2248','thicksim':'\u223C','ThickSpace':'\u205F\u200A','thinsp':'\u2009','ThinSpace':'\u2009','thkap':'\u2248','thksim':'\u223C','thorn':'\xFE','THORN':'\xDE','tilde':'\u02DC','Tilde':'\u223C','TildeEqual':'\u2243','TildeFullEqual':'\u2245','TildeTilde':'\u2248','times':'\xD7','timesb':'\u22A0','timesbar':'\u2A31','timesd':'\u2A30','tint':'\u222D','toea':'\u2928','top':'\u22A4','topbot':'\u2336','topcir':'\u2AF1','topf':'\uD835\uDD65','Topf':'\uD835\uDD4B','topfork':'\u2ADA','tosa':'\u2929','tprime':'\u2034','trade':'\u2122','TRADE':'\u2122','triangle':'\u25B5','triangledown':'\u25BF','triangleleft':'\u25C3','trianglelefteq':'\u22B4','triangleq':'\u225C','triangleright':'\u25B9','trianglerighteq':'\u22B5','tridot':'\u25EC','trie':'\u225C','triminus':'\u2A3A','TripleDot':'\u20DB','triplus':'\u2A39','trisb':'\u29CD','tritime':'\u2A3B','trpezium':'\u23E2','tscr':'\uD835\uDCC9','Tscr':'\uD835\uDCAF','tscy':'\u0446','TScy':'\u0426','tshcy':'\u045B','TSHcy':'\u040B','tstrok':'\u0167','Tstrok':'\u0166','twixt':'\u226C','twoheadleftarrow':'\u219E','twoheadrightarrow':'\u21A0','uacute':'\xFA','Uacute':'\xDA','uarr':'\u2191','uArr':'\u21D1','Uarr':'\u219F','Uarrocir':'\u2949','ubrcy':'\u045E','Ubrcy':'\u040E','ubreve':'\u016D','Ubreve':'\u016C','ucirc':'\xFB','Ucirc':'\xDB','ucy':'\u0443','Ucy':'\u0423','udarr':'\u21C5','udblac':'\u0171','Udblac':'\u0170','udhar':'\u296E','ufisht':'\u297E','ufr':'\uD835\uDD32','Ufr':'\uD835\uDD18','ugrave':'\xF9','Ugrave':'\xD9','uHar':'\u2963','uharl':'\u21BF','uharr':'\u21BE','uhblk':'\u2580','ulcorn':'\u231C','ulcorner':'\u231C','ulcrop':'\u230F','ultri':'\u25F8','umacr':'\u016B','Umacr':'\u016A','uml':'\xA8','UnderBar':'_','UnderBrace':'\u23DF','UnderBracket':'\u23B5','UnderParenthesis':'\u23DD','Union':'\u22C3','UnionPlus':'\u228E','uogon':'\u0173','Uogon':'\u0172','uopf':'\uD835\uDD66','Uopf':'\uD835\uDD4C','uparrow':'\u2191','Uparrow':'\u21D1','UpArrow':'\u2191','UpArrowBar':'\u2912','UpArrowDownArrow':'\u21C5','updownarrow':'\u2195','Updownarrow':'\u21D5','UpDownArrow':'\u2195','UpEquilibrium':'\u296E','upharpoonleft':'\u21BF','upharpoonright':'\u21BE','uplus':'\u228E','UpperLeftArrow':'\u2196','UpperRightArrow':'\u2197','upsi':'\u03C5','Upsi':'\u03D2','upsih':'\u03D2','upsilon':'\u03C5','Upsilon':'\u03A5','UpTee':'\u22A5','UpTeeArrow':'\u21A5','upuparrows':'\u21C8','urcorn':'\u231D','urcorner':'\u231D','urcrop':'\u230E','uring':'\u016F','Uring':'\u016E','urtri':'\u25F9','uscr':'\uD835\uDCCA','Uscr':'\uD835\uDCB0','utdot':'\u22F0','utilde':'\u0169','Utilde':'\u0168','utri':'\u25B5','utrif':'\u25B4','uuarr':'\u21C8','uuml':'\xFC','Uuml':'\xDC','uwangle':'\u29A7','vangrt':'\u299C','varepsilon':'\u03F5','varkappa':'\u03F0','varnothing':'\u2205','varphi':'\u03D5','varpi':'\u03D6','varpropto':'\u221D','varr':'\u2195','vArr':'\u21D5','varrho':'\u03F1','varsigma':'\u03C2','varsubsetneq':'\u228A\uFE00','varsubsetneqq':'\u2ACB\uFE00','varsupsetneq':'\u228B\uFE00','varsupsetneqq':'\u2ACC\uFE00','vartheta':'\u03D1','vartriangleleft':'\u22B2','vartriangleright':'\u22B3','vBar':'\u2AE8','Vbar':'\u2AEB','vBarv':'\u2AE9','vcy':'\u0432','Vcy':'\u0412','vdash':'\u22A2','vDash':'\u22A8','Vdash':'\u22A9','VDash':'\u22AB','Vdashl':'\u2AE6','vee':'\u2228','Vee':'\u22C1','veebar':'\u22BB','veeeq':'\u225A','vellip':'\u22EE','verbar':'|','Verbar':'\u2016','vert':'|','Vert':'\u2016','VerticalBar':'\u2223','VerticalLine':'|','VerticalSeparator':'\u2758','VerticalTilde':'\u2240','VeryThinSpace':'\u200A','vfr':'\uD835\uDD33','Vfr':'\uD835\uDD19','vltri':'\u22B2','vnsub':'\u2282\u20D2','vnsup':'\u2283\u20D2','vopf':'\uD835\uDD67','Vopf':'\uD835\uDD4D','vprop':'\u221D','vrtri':'\u22B3','vscr':'\uD835\uDCCB','Vscr':'\uD835\uDCB1','vsubne':'\u228A\uFE00','vsubnE':'\u2ACB\uFE00','vsupne':'\u228B\uFE00','vsupnE':'\u2ACC\uFE00','Vvdash':'\u22AA','vzigzag':'\u299A','wcirc':'\u0175','Wcirc':'\u0174','wedbar':'\u2A5F','wedge':'\u2227','Wedge':'\u22C0','wedgeq':'\u2259','weierp':'\u2118','wfr':'\uD835\uDD34','Wfr':'\uD835\uDD1A','wopf':'\uD835\uDD68','Wopf':'\uD835\uDD4E','wp':'\u2118','wr':'\u2240','wreath':'\u2240','wscr':'\uD835\uDCCC','Wscr':'\uD835\uDCB2','xcap':'\u22C2','xcirc':'\u25EF','xcup':'\u22C3','xdtri':'\u25BD','xfr':'\uD835\uDD35','Xfr':'\uD835\uDD1B','xharr':'\u27F7','xhArr':'\u27FA','xi':'\u03BE','Xi':'\u039E','xlarr':'\u27F5','xlArr':'\u27F8','xmap':'\u27FC','xnis':'\u22FB','xodot':'\u2A00','xopf':'\uD835\uDD69','Xopf':'\uD835\uDD4F','xoplus':'\u2A01','xotime':'\u2A02','xrarr':'\u27F6','xrArr':'\u27F9','xscr':'\uD835\uDCCD','Xscr':'\uD835\uDCB3','xsqcup':'\u2A06','xuplus':'\u2A04','xutri':'\u25B3','xvee':'\u22C1','xwedge':'\u22C0','yacute':'\xFD','Yacute':'\xDD','yacy':'\u044F','YAcy':'\u042F','ycirc':'\u0177','Ycirc':'\u0176','ycy':'\u044B','Ycy':'\u042B','yen':'\xA5','yfr':'\uD835\uDD36','Yfr':'\uD835\uDD1C','yicy':'\u0457','YIcy':'\u0407','yopf':'\uD835\uDD6A','Yopf':'\uD835\uDD50','yscr':'\uD835\uDCCE','Yscr':'\uD835\uDCB4','yucy':'\u044E','YUcy':'\u042E','yuml':'\xFF','Yuml':'\u0178','zacute':'\u017A','Zacute':'\u0179','zcaron':'\u017E','Zcaron':'\u017D','zcy':'\u0437','Zcy':'\u0417','zdot':'\u017C','Zdot':'\u017B','zeetrf':'\u2128','ZeroWidthSpace':'\u200B','zeta':'\u03B6','Zeta':'\u0396','zfr':'\uD835\uDD37','Zfr':'\u2128','zhcy':'\u0436','ZHcy':'\u0416','zigrarr':'\u21DD','zopf':'\uD835\uDD6B','Zopf':'\u2124','zscr':'\uD835\uDCCF','Zscr':'\uD835\uDCB5','zwj':'\u200D','zwnj':'\u200C'}; + var decodeMapLegacy = {'aacute':'\xE1','Aacute':'\xC1','acirc':'\xE2','Acirc':'\xC2','acute':'\xB4','aelig':'\xE6','AElig':'\xC6','agrave':'\xE0','Agrave':'\xC0','amp':'&','AMP':'&','aring':'\xE5','Aring':'\xC5','atilde':'\xE3','Atilde':'\xC3','auml':'\xE4','Auml':'\xC4','brvbar':'\xA6','ccedil':'\xE7','Ccedil':'\xC7','cedil':'\xB8','cent':'\xA2','copy':'\xA9','COPY':'\xA9','curren':'\xA4','deg':'\xB0','divide':'\xF7','eacute':'\xE9','Eacute':'\xC9','ecirc':'\xEA','Ecirc':'\xCA','egrave':'\xE8','Egrave':'\xC8','eth':'\xF0','ETH':'\xD0','euml':'\xEB','Euml':'\xCB','frac12':'\xBD','frac14':'\xBC','frac34':'\xBE','gt':'>','GT':'>','iacute':'\xED','Iacute':'\xCD','icirc':'\xEE','Icirc':'\xCE','iexcl':'\xA1','igrave':'\xEC','Igrave':'\xCC','iquest':'\xBF','iuml':'\xEF','Iuml':'\xCF','laquo':'\xAB','lt':'<','LT':'<','macr':'\xAF','micro':'\xB5','middot':'\xB7','nbsp':'\xA0','not':'\xAC','ntilde':'\xF1','Ntilde':'\xD1','oacute':'\xF3','Oacute':'\xD3','ocirc':'\xF4','Ocirc':'\xD4','ograve':'\xF2','Ograve':'\xD2','ordf':'\xAA','ordm':'\xBA','oslash':'\xF8','Oslash':'\xD8','otilde':'\xF5','Otilde':'\xD5','ouml':'\xF6','Ouml':'\xD6','para':'\xB6','plusmn':'\xB1','pound':'\xA3','quot':'"','QUOT':'"','raquo':'\xBB','reg':'\xAE','REG':'\xAE','sect':'\xA7','shy':'\xAD','sup1':'\xB9','sup2':'\xB2','sup3':'\xB3','szlig':'\xDF','thorn':'\xFE','THORN':'\xDE','times':'\xD7','uacute':'\xFA','Uacute':'\xDA','ucirc':'\xFB','Ucirc':'\xDB','ugrave':'\xF9','Ugrave':'\xD9','uml':'\xA8','uuml':'\xFC','Uuml':'\xDC','yacute':'\xFD','Yacute':'\xDD','yen':'\xA5','yuml':'\xFF'}; + var decodeMapNumeric = {'0':'\uFFFD','128':'\u20AC','130':'\u201A','131':'\u0192','132':'\u201E','133':'\u2026','134':'\u2020','135':'\u2021','136':'\u02C6','137':'\u2030','138':'\u0160','139':'\u2039','140':'\u0152','142':'\u017D','145':'\u2018','146':'\u2019','147':'\u201C','148':'\u201D','149':'\u2022','150':'\u2013','151':'\u2014','152':'\u02DC','153':'\u2122','154':'\u0161','155':'\u203A','156':'\u0153','158':'\u017E','159':'\u0178'}; + var invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111]; + + /*--------------------------------------------------------------------------*/ + + var stringFromCharCode = String.fromCharCode; + + var object = {}; + var hasOwnProperty = object.hasOwnProperty; + var has = function(object, propertyName) { + return hasOwnProperty.call(object, propertyName); + }; + + var contains = function(array, value) { + var index = -1; + var length = array.length; + while (++index < length) { + if (array[index] == value) { + return true; + } + } + return false; + }; + + var merge = function(options, defaults) { + if (!options) { + return defaults; + } + var result = {}; + var key; + for (key in defaults) { + // A `hasOwnProperty` check is not needed here, since only recognized + // option names are used anyway. Any others are ignored. + result[key] = has(options, key) ? options[key] : defaults[key]; + } + return result; + }; + + // Modified version of `ucs2encode`; see https://mths.be/punycode. + var codePointToSymbol = function(codePoint, strict) { + var output = ''; + if ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) { + // See issue #4: + // “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is + // greater than 0x10FFFF, then this is a parse error. Return a U+FFFD + // REPLACEMENT CHARACTER.” + if (strict) { + parseError('character reference outside the permissible Unicode range'); + } + return '\uFFFD'; + } + if (has(decodeMapNumeric, codePoint)) { + if (strict) { + parseError('disallowed character reference'); + } + return decodeMapNumeric[codePoint]; + } + if (strict && contains(invalidReferenceCodePoints, codePoint)) { + parseError('disallowed character reference'); + } + if (codePoint > 0xFFFF) { + codePoint -= 0x10000; + output += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + output += stringFromCharCode(codePoint); + return output; + }; + + var hexEscape = function(codePoint) { + return '&#x' + codePoint.toString(16).toUpperCase() + ';'; + }; + + var decEscape = function(codePoint) { + return '&#' + codePoint + ';'; + }; + + var parseError = function(message) { + throw Error('Parse error: ' + message); + }; + + /*--------------------------------------------------------------------------*/ + + var encode = function(string, options) { + options = merge(options, encode.options); + var strict = options.strict; + if (strict && regexInvalidRawCodePoint.test(string)) { + parseError('forbidden code point'); + } + var encodeEverything = options.encodeEverything; + var useNamedReferences = options.useNamedReferences; + var allowUnsafeSymbols = options.allowUnsafeSymbols; + var escapeCodePoint = options.decimal ? decEscape : hexEscape; + + var escapeBmpSymbol = function(symbol) { + return escapeCodePoint(symbol.charCodeAt(0)); + }; + + if (encodeEverything) { + // Encode ASCII symbols. + string = string.replace(regexAsciiWhitelist, function(symbol) { + // Use named references if requested & possible. + if (useNamedReferences && has(encodeMap, symbol)) { + return '&' + encodeMap[symbol] + ';'; + } + return escapeBmpSymbol(symbol); + }); + // Shorten a few escapes that represent two symbols, of which at least one + // is within the ASCII range. + if (useNamedReferences) { + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒') + .replace(/fj/g, 'fj'); + } + // Encode non-ASCII symbols. + if (useNamedReferences) { + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } + // Note: any remaining non-ASCII symbols are handled outside of the `if`. + } else if (useNamedReferences) { + // Apply named character references. + // Encode `<>"'&` using named character references. + if (!allowUnsafeSymbols) { + string = string.replace(regexEscape, function(string) { + return '&' + encodeMap[string] + ';'; // no need to check `has()` here + }); + } + // Shorten escapes that represent two symbols, of which at least one is + // `<>"'&`. + string = string + .replace(/>\u20D2/g, '>⃒') + .replace(/<\u20D2/g, '<⃒'); + // Encode non-ASCII symbols that can be replaced with a named reference. + string = string.replace(regexEncodeNonAscii, function(string) { + // Note: there is no need to check `has(encodeMap, string)` here. + return '&' + encodeMap[string] + ';'; + }); + } else if (!allowUnsafeSymbols) { + // Encode `<>"'&` using hexadecimal escapes, now that they’re not handled + // using named character references. + string = string.replace(regexEscape, escapeBmpSymbol); + } + return string + // Encode astral symbols. + .replace(regexAstralSymbols, function($0) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + var high = $0.charCodeAt(0); + var low = $0.charCodeAt(1); + var codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000; + return escapeCodePoint(codePoint); + }) + // Encode any remaining BMP symbols that are not printable ASCII symbols + // using a hexadecimal escape. + .replace(regexBmpWhitelist, escapeBmpSymbol); + }; + // Expose default options (so they can be overridden globally). + encode.options = { + 'allowUnsafeSymbols': false, + 'encodeEverything': false, + 'strict': false, + 'useNamedReferences': false, + 'decimal' : false + }; + + var decode = function(html, options) { + options = merge(options, decode.options); + var strict = options.strict; + if (strict && regexInvalidEntity.test(html)) { + parseError('malformed character reference'); + } + return html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) { + var codePoint; + var semicolon; + var decDigits; + var hexDigits; + var reference; + var next; + + if ($1) { + reference = $1; + // Note: there is no need to check `has(decodeMap, reference)`. + return decodeMap[reference]; + } + + if ($2) { + // Decode named character references without trailing `;`, e.g. `&`. + // This is only a parse error if it gets converted to `&`, or if it is + // followed by `=` in an attribute context. + reference = $2; + next = $3; + if (next && options.isAttributeValue) { + if (strict && next == '=') { + parseError('`&` did not start a character reference'); + } + return $0; + } else { + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + // Note: there is no need to check `has(decodeMapLegacy, reference)`. + return decodeMapLegacy[reference] + (next || ''); + } + } + + if ($4) { + // Decode decimal escapes, e.g. `𝌆`. + decDigits = $4; + semicolon = $5; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(decDigits, 10); + return codePointToSymbol(codePoint, strict); + } + + if ($6) { + // Decode hexadecimal escapes, e.g. `𝌆`. + hexDigits = $6; + semicolon = $7; + if (strict && !semicolon) { + parseError('character reference was not terminated by a semicolon'); + } + codePoint = parseInt(hexDigits, 16); + return codePointToSymbol(codePoint, strict); + } + + // If we’re still here, `if ($7)` is implied; it’s an ambiguous + // ampersand for sure. https://mths.be/notes/ambiguous-ampersands + if (strict) { + parseError( + 'named character reference was not terminated by a semicolon' + ); + } + return $0; + }); + }; + // Expose default options (so they can be overridden globally). + decode.options = { + 'isAttributeValue': false, + 'strict': false + }; + + var escape = function(string) { + return string.replace(regexEscape, function($0) { + // Note: there is no need to check `has(escapeMap, $0)` here. + return escapeMap[$0]; + }); + }; + + /*--------------------------------------------------------------------------*/ + + var he = { + 'version': '1.2.0', + 'encode': encode, + 'decode': decode, + 'escape': escape, + 'unescape': decode + }; + + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && !freeExports.nodeType) { + if (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = he; + } else { // in Narwhal or RingoJS v0.7.0- + for (var key in he) { + has(he, key) && (freeExports[key] = he[key]); + } + } + } else { // in Rhino or a web browser + root.he = he; + } + + }(commonjsGlobal)); + }(he, he.exports)); + + (function (exports) { + + /** + * Various utility functions used throughout Mocha's codebase. + * @module utils + */ + + /** + * Module dependencies. + */ + var path = require$$1; + var util = require$$0$1; + var he$1 = he.exports; + + const MOCHA_ID_PROP_NAME = '__mocha_id__'; + + /** + * Inherit the prototype methods from one constructor into another. + * + * @param {function} ctor - Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor - Constructor function to inherit prototype from. + * @throws {TypeError} if either constructor is null, or if super constructor + * lacks a prototype. + */ + exports.inherits = util.inherits; + + /** + * Escape special characters in the given string of html. + * + * @private + * @param {string} html + * @return {string} + */ + exports.escape = function (html) { + return he$1.encode(String(html), {useNamedReferences: false}); + }; + + /** + * Test if the given obj is type of string. + * + * @private + * @param {Object} obj + * @return {boolean} + */ + exports.isString = function (obj) { + return typeof obj === 'string'; + }; + + /** + * Compute a slug from the given `str`. + * + * @private + * @param {string} str + * @return {string} + */ + exports.slug = function (str) { + return str + .toLowerCase() + .replace(/\s+/g, '-') + .replace(/[^-\w]/g, '') + .replace(/-{2,}/g, '-'); + }; + + /** + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @param {string} str + * @return {string} + */ + exports.clean = function (str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n') + .replace(/^\uFEFF/, '') + // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content + .replace( + /^function(?:\s*|\s[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\}|((?:.|\n)*))$/, + '$1$2$3' + ); + + var spaces = str.match(/^\n?( *)/)[1].length; + var tabs = str.match(/^\n?(\t*)/)[1].length; + var re = new RegExp( + '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', + 'gm' + ); + + str = str.replace(re, ''); + + return str.trim(); + }; + + /** + * If a value could have properties, and has none, this function is called, + * which returns a string representation of the empty value. + * + * Functions w/ no properties return `'[Function]'` + * Arrays w/ length === 0 return `'[]'` + * Objects w/ no properties return `'{}'` + * All else: return result of `value.toString()` + * + * @private + * @param {*} value The value to inspect. + * @param {string} typeHint The type of the value + * @returns {string} + */ + function emptyRepresentation(value, typeHint) { + switch (typeHint) { + case 'function': + return '[Function]'; + case 'object': + return '{}'; + case 'array': + return '[]'; + default: + return value.toString(); + } + } + + /** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it + * is. + * + * @private + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString + * @param {*} value The value to test. + * @returns {string} Computed type + * @example + * canonicalType({}) // 'object' + * canonicalType([]) // 'array' + * canonicalType(1) // 'number' + * canonicalType(false) // 'boolean' + * canonicalType(Infinity) // 'number' + * canonicalType(null) // 'null' + * canonicalType(new Date()) // 'date' + * canonicalType(/foo/) // 'regexp' + * canonicalType('type') // 'string' + * canonicalType(global) // 'global' + * canonicalType(new String('foo') // 'object' + * canonicalType(async function() {}) // 'asyncfunction' + * canonicalType(await import(name)) // 'module' + */ + var canonicalType = (exports.canonicalType = function canonicalType(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (isBuffer(value)) { + return 'buffer'; + } + return Object.prototype.toString + .call(value) + .replace(/^\[.+\s(.+?)]$/, '$1') + .toLowerCase(); + }); + + /** + * + * Returns a general type or data structure of a variable + * @private + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures + * @param {*} value The value to test. + * @returns {string} One of undefined, boolean, number, string, bigint, symbol, object + * @example + * type({}) // 'object' + * type([]) // 'array' + * type(1) // 'number' + * type(false) // 'boolean' + * type(Infinity) // 'number' + * type(null) // 'null' + * type(new Date()) // 'object' + * type(/foo/) // 'object' + * type('type') // 'string' + * type(global) // 'object' + * type(new String('foo') // 'string' + */ + exports.type = function type(value) { + // Null is special + if (value === null) return 'null'; + const primitives = new Set([ + 'undefined', + 'boolean', + 'number', + 'string', + 'bigint', + 'symbol' + ]); + const _type = typeof value; + if (_type === 'function') return _type; + if (primitives.has(_type)) return _type; + if (value instanceof String) return 'string'; + if (value instanceof Error) return 'error'; + if (Array.isArray(value)) return 'array'; + + return _type; + }; + + /** + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, return result of function + * {@link emptyRepresentation}. + * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of + * JSON.stringify(). + * + * @private + * @see exports.type + * @param {*} value + * @return {string} + */ + exports.stringify = function (value) { + var typeHint = canonicalType(value); + + if (!~['object', 'array', 'function'].indexOf(typeHint)) { + if (typeHint === 'buffer') { + var json = Buffer.prototype.toJSON.call(value); + // Based on the toJSON result + return jsonStringify( + json.data && json.type ? json.data : json, + 2 + ).replace(/,(\n|$)/g, '$1'); + } + + // IE7/IE8 has a bizarre String constructor; needs to be coerced + // into an array and back to obj. + if (typeHint === 'string' && typeof value === 'object') { + value = value.split('').reduce(function (acc, char, idx) { + acc[idx] = char; + return acc; + }, {}); + typeHint = 'object'; + } else { + return jsonStringify(value); + } + } + + for (var prop in value) { + if (Object.prototype.hasOwnProperty.call(value, prop)) { + return jsonStringify( + exports.canonicalize(value, null, typeHint), + 2 + ).replace(/,(\n|$)/g, '$1'); + } + } + + return emptyRepresentation(value, typeHint); + }; + + /** + * like JSON.stringify but more sense. + * + * @private + * @param {Object} object + * @param {number=} spaces + * @param {number=} depth + * @returns {*} + */ + function jsonStringify(object, spaces, depth) { + if (typeof spaces === 'undefined') { + // primitive types + return _stringify(object); + } + + depth = depth || 1; + var space = spaces * depth; + var str = Array.isArray(object) ? '[' : '{'; + var end = Array.isArray(object) ? ']' : '}'; + var length = + typeof object.length === 'number' + ? object.length + : Object.keys(object).length; + // `.repeat()` polyfill + function repeat(s, n) { + return new Array(n).join(s); + } + + function _stringify(val) { + switch (canonicalType(val)) { + case 'null': + case 'undefined': + val = '[' + val + ']'; + break; + case 'array': + case 'object': + val = jsonStringify(val, spaces, depth + 1); + break; + case 'boolean': + case 'regexp': + case 'symbol': + case 'number': + val = + val === 0 && 1 / val === -Infinity // `-0` + ? '-0' + : val.toString(); + break; + case 'bigint': + val = val.toString() + 'n'; + break; + case 'date': + var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString(); + val = '[Date: ' + sDate + ']'; + break; + case 'buffer': + var json = val.toJSON(); + // Based on the toJSON result + json = json.data && json.type ? json.data : json; + val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; + break; + default: + val = + val === '[Function]' || val === '[Circular]' + ? val + : JSON.stringify(val); // string + } + return val; + } + + for (var i in object) { + if (!Object.prototype.hasOwnProperty.call(object, i)) { + continue; // not my business + } + --length; + str += + '\n ' + + repeat(' ', space) + + (Array.isArray(object) ? '' : '"' + i + '": ') + // key + _stringify(object[i]) + // value + (length ? ',' : ''); // comma + } + + return ( + str + + // [], {} + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end) + ); + } + + /** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` + * + * @private + * @see {@link exports.stringify} + * @param {*} value Thing to inspect. May or may not have properties. + * @param {Array} [stack=[]] Stack of seen values + * @param {string} [typeHint] Type hint + * @return {(Object|Array|Function|string|undefined)} + */ + exports.canonicalize = function canonicalize(value, stack, typeHint) { + var canonicalizedObj; + /* eslint-disable no-unused-vars */ + var prop; + /* eslint-enable no-unused-vars */ + typeHint = typeHint || canonicalType(value); + function withStack(value, fn) { + stack.push(value); + fn(); + stack.pop(); + } + + stack = stack || []; + + if (stack.indexOf(value) !== -1) { + return '[Circular]'; + } + + switch (typeHint) { + case 'undefined': + case 'buffer': + case 'null': + canonicalizedObj = value; + break; + case 'array': + withStack(value, function () { + canonicalizedObj = value.map(function (item) { + return exports.canonicalize(item, stack); + }); + }); + break; + case 'function': + /* eslint-disable-next-line no-unused-vars, no-unreachable-loop */ + for (prop in value) { + canonicalizedObj = {}; + break; + } + /* eslint-enable guard-for-in */ + if (!canonicalizedObj) { + canonicalizedObj = emptyRepresentation(value, typeHint); + break; + } + /* falls through */ + case 'object': + canonicalizedObj = canonicalizedObj || {}; + withStack(value, function () { + Object.keys(value) + .sort() + .forEach(function (key) { + canonicalizedObj[key] = exports.canonicalize(value[key], stack); + }); + }); + break; + case 'date': + case 'number': + case 'regexp': + case 'boolean': + case 'symbol': + canonicalizedObj = value; + break; + default: + canonicalizedObj = value + ''; + } + + return canonicalizedObj; + }; + + /** + * @summary + * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) + * @description + * When invoking this function you get a filter function that get the Error.stack as an input, + * and return a prettify output. + * (i.e: strip Mocha and internal node functions from stack trace). + * @returns {Function} + */ + exports.stackTraceFilter = function () { + // TODO: Replace with `process.browser` + var is = typeof document === 'undefined' ? {node: true} : {browser: true}; + var slash = path.sep; + var cwd; + if (is.node) { + cwd = exports.cwd() + slash; + } else { + cwd = ( + typeof location === 'undefined' ? window.location : location + ).href.replace(/\/[^/]*$/, '/'); + slash = '/'; + } + + function isMochaInternal(line) { + return ( + ~line.indexOf('node_modules' + slash + 'mocha' + slash) || + ~line.indexOf(slash + 'mocha.js') || + ~line.indexOf(slash + 'mocha.min.js') + ); + } + + function isNodeInternal(line) { + return ( + ~line.indexOf('(timers.js:') || + ~line.indexOf('(events.js:') || + ~line.indexOf('(node.js:') || + ~line.indexOf('(module.js:') || + ~line.indexOf('GeneratorFunctionPrototype.next (native)') || + false + ); + } + + return function (stack) { + stack = stack.split('\n'); + + stack = stack.reduce(function (list, line) { + if (isMochaInternal(line)) { + return list; + } + + if (is.node && isNodeInternal(line)) { + return list; + } + + // Clean up cwd(absolute) + if (/:\d+:\d+\)?$/.test(line)) { + line = line.replace('(' + cwd, '('); + } + + list.push(line); + return list; + }, []); + + return stack.join('\n'); + }; + }; + + /** + * Crude, but effective. + * @public + * @param {*} value + * @returns {boolean} Whether or not `value` is a Promise + */ + exports.isPromise = function isPromise(value) { + return ( + typeof value === 'object' && + value !== null && + typeof value.then === 'function' + ); + }; + + /** + * Clamps a numeric value to an inclusive range. + * + * @param {number} value - Value to be clamped. + * @param {number[]} range - Two element array specifying [min, max] range. + * @returns {number} clamped value + */ + exports.clamp = function clamp(value, range) { + return Math.min(Math.max(value, range[0]), range[1]); + }; + + /** + * It's a noop. + * @public + */ + exports.noop = function () {}; + + /** + * Creates a map-like object. + * + * @description + * A "map" is an object with no prototype, for our purposes. In some cases + * this would be more appropriate than a `Map`, especially if your environment + * doesn't support it. Recommended for use in Mocha's public APIs. + * + * @public + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Custom_and_Null_objects|MDN:Map} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects} + * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Custom_and_Null_objects|MDN:Object.assign} + * @param {...*} [obj] - Arguments to `Object.assign()`. + * @returns {Object} An object with no prototype, having `...obj` properties + */ + exports.createMap = function (obj) { + return Object.assign.apply( + null, + [Object.create(null)].concat(Array.prototype.slice.call(arguments)) + ); + }; + + /** + * Creates a read-only map-like object. + * + * @description + * This differs from {@link module:utils.createMap createMap} only in that + * the argument must be non-empty, because the result is frozen. + * + * @see {@link module:utils.createMap createMap} + * @param {...*} [obj] - Arguments to `Object.assign()`. + * @returns {Object} A frozen object with no prototype, having `...obj` properties + * @throws {TypeError} if argument is not a non-empty object. + */ + exports.defineConstants = function (obj) { + if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) { + throw new TypeError('Invalid argument; expected a non-empty object'); + } + return Object.freeze(exports.createMap(obj)); + }; + + /** + * Returns current working directory + * + * Wrapper around `process.cwd()` for isolation + * @private + */ + exports.cwd = function cwd() { + return process.cwd(); + }; + + /** + * Returns `true` if Mocha is running in a browser. + * Checks for `process.browser`. + * @returns {boolean} + * @private + */ + exports.isBrowser = function isBrowser() { + return Boolean(browser$2); + }; + + /* + * Casts `value` to an array; useful for optionally accepting array parameters + * + * It follows these rules, depending on `value`. If `value` is... + * 1. `undefined`: return an empty Array + * 2. `null`: return an array with a single `null` element + * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable + * 4. otherwise: return an array with a single element, `value` + * @param {*} value - Something to cast to an Array + * @returns {Array<*>} + */ + exports.castArray = function castArray(value) { + if (value === undefined) { + return []; + } + if (value === null) { + return [null]; + } + if ( + typeof value === 'object' && + (typeof value[Symbol.iterator] === 'function' || value.length !== undefined) + ) { + return Array.from(value); + } + return [value]; + }; + + exports.constants = exports.defineConstants({ + MOCHA_ID_PROP_NAME + }); + + const uniqueIDBase = + 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'; + + /** + * Creates a new unique identifier + * Does not create cryptographically safe ids. + * Trivial copy of nanoid/non-secure + * @returns {string} Unique identifier + */ + exports.uniqueID = () => { + let id = ''; + for (let i = 0; i < 21; i++) { + id += uniqueIDBase[(Math.random() * 64) | 0]; + } + return id; + }; + + exports.assignNewMochaID = obj => { + const id = exports.uniqueID(); + Object.defineProperty(obj, MOCHA_ID_PROP_NAME, { + get() { + return id; + } + }); + return obj; + }; + + /** + * Retrieves a Mocha ID from an object, if present. + * @param {*} [obj] - Object + * @returns {string|void} + */ + exports.getMochaID = obj => + obj && typeof obj === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined; + }(utils$3)); + + var _nodeResolve_empty = {}; + + var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _nodeResolve_empty + }); + + var require$$18 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + + var browser$1 = { + info: 'ℹ️', + success: '✅', + warning: '⚠️', + error: '❌️' + }; + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events); + + /** + @module Pending + */ + + var pending = Pending$2; + + /** + * Initialize a new `Pending` error with the given message. + * + * @param {string} message + */ + function Pending$2(message) { + this.message = message; + } + + var browser = {exports: {}}; + + /** + * Helpers. + */ + + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + var ms = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); + }; + + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'weeks': + case 'week': + case 'w': + return n * w; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } + } + + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; + } + + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + return ms + ' ms'; + } + + /** + * Pluralization helper. + */ + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = ms; + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. + + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); + + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + return debug; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + + createDebug.enable(createDebug.load()); + + return createDebug; + } + + var common$1 = setup; + + (function (module, exports) { + /** + * This is the web browser implementation of `debug()`. + */ + + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = (() => { + let warned = false; + + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; + })(); + + /** + * Colors. + */ + + exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' + ]; + + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + + // eslint-disable-next-line complexity + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); + } + + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); + } + + /** + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. + * + * @api public + */ + exports.log = console.debug || console.log || (() => {}); + + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = common$1(exports); + + const {formatters} = module.exports; + + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + }(browser, browser.exports)); + + const {format} = require$$0$1; + + /** + * Contains error codes, factory functions to create throwable error objects, + * and warning/deprecation functions. + * @module + */ + + /** + * process.emitWarning or a polyfill + * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options + * @ignore + */ + const emitWarning = (msg, type) => { + if (process.emitWarning) { + process.emitWarning(msg, type); + } else { + /* istanbul ignore next */ + nextTick$1(function () { + console.warn(type + ': ' + msg); + }); + } + }; + + /** + * Show a deprecation warning. Each distinct message is only displayed once. + * Ignores empty messages. + * + * @param {string} [msg] - Warning to print + * @private + */ + const deprecate = msg => { + msg = String(msg); + if (msg && !deprecate.cache[msg]) { + deprecate.cache[msg] = true; + emitWarning(msg, 'DeprecationWarning'); + } + }; + deprecate.cache = {}; + + /** + * Show a generic warning. + * Ignores empty messages. + * + * @param {string} [msg] - Warning to print + * @private + */ + const warn = msg => { + if (msg) { + emitWarning(msg); + } + }; + + /** + * When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`. + * @public + * @namespace + * @memberof module:lib/errors + */ + var constants$4 = { + /** + * An unrecoverable error. + * @constant + * @default + */ + FATAL: 'ERR_MOCHA_FATAL', + + /** + * The type of an argument to a function call is invalid + * @constant + * @default + */ + INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE', + + /** + * The value of an argument to a function call is invalid + * @constant + * @default + */ + INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE', + + /** + * Something was thrown, but it wasn't an `Error` + * @constant + * @default + */ + INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION', + + /** + * An interface (e.g., `Mocha.interfaces`) is unknown or invalid + * @constant + * @default + */ + INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE', + + /** + * A reporter (.e.g, `Mocha.reporters`) is unknown or invalid + * @constant + * @default + */ + INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER', + + /** + * `done()` was called twice in a `Test` or `Hook` callback + * @constant + * @default + */ + MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE', + + /** + * No files matched the pattern provided by the user + * @constant + * @default + */ + NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN', + + /** + * Known, but unsupported behavior of some kind + * @constant + * @default + */ + UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED', + + /** + * Invalid state transition occurring in `Mocha` instance + * @constant + * @default + */ + INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING', + + /** + * Invalid state transition occurring in `Mocha` instance + * @constant + * @default + */ + INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED', + + /** + * Use of `only()` w/ `--forbid-only` results in this error. + * @constant + * @default + */ + FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY', + + /** + * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid + * @constant + * @default + */ + INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION', + + /** + * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid + * @constant + * @default + */ + INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION', + + /** + * When a runnable exceeds its allowed run time. + * @constant + * @default + */ + TIMEOUT: 'ERR_MOCHA_TIMEOUT', + + /** + * Input file is not able to be parsed + * @constant + * @default + */ + UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE' + }; + + /** + * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}. + * @private + */ + const MOCHA_ERRORS = new Set(Object.values(constants$4)); + + /** + * Creates an error object to be thrown when no files to be tested could be found using specified pattern. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} pattern - User-specified argument value. + * @returns {Error} instance detailing the error condition + */ + function createNoFilesMatchPatternError(message, pattern) { + var err = new Error(message); + err.code = constants$4.NO_FILES_MATCH_PATTERN; + err.pattern = pattern; + return err; + } + + /** + * Creates an error object to be thrown when the reporter specified in the options was not found. + * + * @public + * @param {string} message - Error message to be displayed. + * @param {string} reporter - User-specified reporter value. + * @returns {Error} instance detailing the error condition + */ + function createInvalidReporterError(message, reporter) { + var err = new TypeError(message); + err.code = constants$4.INVALID_REPORTER; + err.reporter = reporter; + return err; + } + + /** + * Creates an error object to be thrown when the interface specified in the options was not found. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} ui - User-specified interface value. + * @returns {Error} instance detailing the error condition + */ + function createInvalidInterfaceError(message, ui) { + var err = new Error(message); + err.code = constants$4.INVALID_INTERFACE; + err.interface = ui; + return err; + } + + /** + * Creates an error object to be thrown when a behavior, option, or parameter is unsupported. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @returns {Error} instance detailing the error condition + */ + function createUnsupportedError$2(message) { + var err = new Error(message); + err.code = constants$4.UNSUPPORTED; + return err; + } + + /** + * Creates an error object to be thrown when an argument is missing. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} argument - Argument name. + * @param {string} expected - Expected argument datatype. + * @returns {Error} instance detailing the error condition + */ + function createMissingArgumentError$1(message, argument, expected) { + return createInvalidArgumentTypeError$1(message, argument, expected); + } + + /** + * Creates an error object to be thrown when an argument did not use the supported type + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} argument - Argument name. + * @param {string} expected - Expected argument datatype. + * @returns {Error} instance detailing the error condition + */ + function createInvalidArgumentTypeError$1(message, argument, expected) { + var err = new TypeError(message); + err.code = constants$4.INVALID_ARG_TYPE; + err.argument = argument; + err.expected = expected; + err.actual = typeof argument; + return err; + } + + /** + * Creates an error object to be thrown when an argument did not use the supported value + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} argument - Argument name. + * @param {string} value - Argument value. + * @param {string} [reason] - Why value is invalid. + * @returns {Error} instance detailing the error condition + */ + function createInvalidArgumentValueError(message, argument, value, reason) { + var err = new TypeError(message); + err.code = constants$4.INVALID_ARG_VALUE; + err.argument = argument; + err.value = value; + err.reason = typeof reason !== 'undefined' ? reason : 'is invalid'; + return err; + } + + /** + * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @returns {Error} instance detailing the error condition + */ + function createInvalidExceptionError$2(message, value) { + var err = new Error(message); + err.code = constants$4.INVALID_EXCEPTION; + err.valueType = typeof value; + err.value = value; + return err; + } + + /** + * Creates an error object to be thrown when an unrecoverable error occurs. + * + * @public + * @static + * @param {string} message - Error message to be displayed. + * @returns {Error} instance detailing the error condition + */ + function createFatalError$1(message, value) { + var err = new Error(message); + err.code = constants$4.FATAL; + err.valueType = typeof value; + err.value = value; + return err; + } + + /** + * Dynamically creates a plugin-type-specific error based on plugin type + * @param {string} message - Error message + * @param {"reporter"|"ui"} pluginType - Plugin type. Future: expand as needed + * @param {string} [pluginId] - Name/path of plugin, if any + * @throws When `pluginType` is not known + * @public + * @static + * @returns {Error} + */ + function createInvalidLegacyPluginError(message, pluginType, pluginId) { + switch (pluginType) { + case 'reporter': + return createInvalidReporterError(message, pluginId); + case 'ui': + return createInvalidInterfaceError(message, pluginId); + default: + throw new Error('unknown pluginType "' + pluginType + '"'); + } + } + + /** + * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type + * @deprecated + * @param {string} message - Error message + * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed + * @param {string} [pluginId] - Name/path of plugin, if any + * @throws When `pluginType` is not known + * @public + * @static + * @returns {Error} + */ + function createInvalidPluginError(...args) { + deprecate('Use createInvalidLegacyPluginError() instead'); + return createInvalidLegacyPluginError(...args); + } + + /** + * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed. + * @param {string} message The error message to be displayed. + * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun` + * @param {Mocha} instance the mocha instance that throw this error + * @static + */ + function createMochaInstanceAlreadyDisposedError( + message, + cleanReferencesAfterRun, + instance + ) { + var err = new Error(message); + err.code = constants$4.INSTANCE_ALREADY_DISPOSED; + err.cleanReferencesAfterRun = cleanReferencesAfterRun; + err.instance = instance; + return err; + } + + /** + * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress. + * @param {string} message The error message to be displayed. + * @static + * @public + */ + function createMochaInstanceAlreadyRunningError(message, instance) { + var err = new Error(message); + err.code = constants$4.INSTANCE_ALREADY_RUNNING; + err.instance = instance; + return err; + } + + /** + * Creates an error object to be thrown when done() is called multiple times in a test + * + * @public + * @param {Runnable} runnable - Original runnable + * @param {Error} [originalErr] - Original error, if any + * @returns {Error} instance detailing the error condition + * @static + */ + function createMultipleDoneError$1(runnable, originalErr) { + var title; + try { + title = format('<%s>', runnable.fullTitle()); + if (runnable.parent.root) { + title += ' (of root suite)'; + } + } catch (ignored) { + title = format('<%s> (of unknown suite)', runnable.title); + } + var message = format( + 'done() called multiple times in %s %s', + runnable.type ? runnable.type : 'unknown runnable', + title + ); + if (runnable.file) { + message += format(' of file %s', runnable.file); + } + if (originalErr) { + message += format('; in addition, done() received error: %s', originalErr); + } + + var err = new Error(message); + err.code = constants$4.MULTIPLE_DONE; + err.valueType = typeof originalErr; + err.value = originalErr; + return err; + } + + /** + * Creates an error object to be thrown when `.only()` is used with + * `--forbid-only`. + * @static + * @public + * @param {Mocha} mocha - Mocha instance + * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY} + */ + function createForbiddenExclusivityError$1(mocha) { + var err = new Error( + mocha.isWorker + ? '`.only` is not supported in parallel mode' + : '`.only` forbidden by --forbid-only' + ); + err.code = constants$4.FORBIDDEN_EXCLUSIVITY; + return err; + } + + /** + * Creates an error object to be thrown when a plugin definition is invalid + * @static + * @param {string} msg - Error message + * @param {PluginDefinition} [pluginDef] - Problematic plugin definition + * @public + * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION} + */ + function createInvalidPluginDefinitionError(msg, pluginDef) { + const err = new Error(msg); + err.code = constants$4.INVALID_PLUGIN_DEFINITION; + err.pluginDef = pluginDef; + return err; + } + + /** + * Creates an error object to be thrown when a plugin implementation (user code) is invalid + * @static + * @param {string} msg - Error message + * @param {Object} [opts] - Plugin definition and user-supplied implementation + * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition + * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied) + * @public + * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION} + */ + function createInvalidPluginImplementationError( + msg, + {pluginDef, pluginImpl} = {} + ) { + const err = new Error(msg); + err.code = constants$4.INVALID_PLUGIN_IMPLEMENTATION; + err.pluginDef = pluginDef; + err.pluginImpl = pluginImpl; + return err; + } + + /** + * Creates an error object to be thrown when a runnable exceeds its allowed run time. + * @static + * @param {string} msg - Error message + * @param {number} [timeout] - Timeout in ms + * @param {string} [file] - File, if given + * @returns {MochaTimeoutError} + */ + function createTimeoutError$1(msg, timeout, file) { + const err = new Error(msg); + err.code = constants$4.TIMEOUT; + err.timeout = timeout; + err.file = file; + return err; + } + + /** + * Creates an error object to be thrown when file is unparsable + * @public + * @static + * @param {string} message - Error message to be displayed. + * @param {string} filename - File name + * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE} + */ + function createUnparsableFileError(message, filename) { + var err = new Error(message); + err.code = constants$4.UNPARSABLE_FILE; + return err; + } + + /** + * Returns `true` if an error came out of Mocha. + * _Can suffer from false negatives, but not false positives._ + * @static + * @public + * @param {*} err - Error, or anything + * @returns {boolean} + */ + const isMochaError$1 = err => + Boolean(err && typeof err === 'object' && MOCHA_ERRORS.has(err.code)); + + var errors$2 = { + constants: constants$4, + createFatalError: createFatalError$1, + createForbiddenExclusivityError: createForbiddenExclusivityError$1, + createInvalidArgumentTypeError: createInvalidArgumentTypeError$1, + createInvalidArgumentValueError, + createInvalidExceptionError: createInvalidExceptionError$2, + createInvalidInterfaceError, + createInvalidLegacyPluginError, + createInvalidPluginDefinitionError, + createInvalidPluginError, + createInvalidPluginImplementationError, + createInvalidReporterError, + createMissingArgumentError: createMissingArgumentError$1, + createMochaInstanceAlreadyDisposedError, + createMochaInstanceAlreadyRunningError, + createMultipleDoneError: createMultipleDoneError$1, + createNoFilesMatchPatternError, + createTimeoutError: createTimeoutError$1, + createUnparsableFileError, + createUnsupportedError: createUnsupportedError$2, + deprecate, + isMochaError: isMochaError$1, + warn + }; + + var EventEmitter$1 = require$$0.EventEmitter; + var Pending$1 = pending; + var debug$1 = browser.exports('mocha:runnable'); + var milliseconds = ms$1; + var utils$2 = utils$3; + const { + createInvalidExceptionError: createInvalidExceptionError$1, + createMultipleDoneError, + createTimeoutError + } = errors$2; + + /** + * Save timer references to avoid Sinon interfering (see GH-237). + * @private + */ + var Date$3 = commonjsGlobal.Date; + var setTimeout$2 = commonjsGlobal.setTimeout; + var clearTimeout$1 = commonjsGlobal.clearTimeout; + var toString = Object.prototype.toString; + + var runnable = Runnable$3; + + /** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @class + * @extends external:EventEmitter + * @public + * @param {String} title + * @param {Function} fn + */ + function Runnable$3(title, fn) { + this.title = title; + this.fn = fn; + this.body = (fn || '').toString(); + this.async = fn && fn.length; + this.sync = !this.async; + this._timeout = 2000; + this._slow = 75; + this._retries = -1; + utils$2.assignNewMochaID(this); + Object.defineProperty(this, 'id', { + get() { + return utils$2.getMochaID(this); + } + }); + this.reset(); + } + + /** + * Inherit from `EventEmitter.prototype`. + */ + utils$2.inherits(Runnable$3, EventEmitter$1); + + /** + * Resets the state initially or for a next run. + */ + Runnable$3.prototype.reset = function () { + this.timedOut = false; + this._currentRetry = 0; + this.pending = false; + delete this.state; + delete this.err; + }; + + /** + * Get current timeout value in msecs. + * + * @private + * @returns {number} current timeout threshold value + */ + /** + * @summary + * Set timeout threshold value (msecs). + * + * @description + * A string argument can use shorthand (e.g., "2s") and will be converted. + * The value will be clamped to range [0, 2^31-1]. + * If clamped value matches either range endpoint, timeouts will be disabled. + * + * @private + * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value} + * @param {number|string} ms - Timeout threshold value. + * @returns {Runnable} this + * @chainable + */ + Runnable$3.prototype.timeout = function (ms) { + if (!arguments.length) { + return this._timeout; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + + // Clamp to range + var INT_MAX = Math.pow(2, 31) - 1; + var range = [0, INT_MAX]; + ms = utils$2.clamp(ms, range); + + // see #1652 for reasoning + if (ms === range[0] || ms === range[1]) { + this._timeout = 0; + } else { + this._timeout = ms; + } + debug$1('timeout %d', this._timeout); + + if (this.timer) { + this.resetTimeout(); + } + return this; + }; + + /** + * Set or get slow `ms`. + * + * @private + * @param {number|string} ms + * @return {Runnable|number} ms or Runnable instance. + */ + Runnable$3.prototype.slow = function (ms) { + if (!arguments.length || typeof ms === 'undefined') { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug$1('slow %d', ms); + this._slow = ms; + return this; + }; + + /** + * Halt and mark as pending. + * + * @memberof Mocha.Runnable + * @public + */ + Runnable$3.prototype.skip = function () { + this.pending = true; + throw new Pending$1('sync skip; aborting execution'); + }; + + /** + * Check if this runnable or its parent suite is marked as pending. + * + * @private + */ + Runnable$3.prototype.isPending = function () { + return this.pending || (this.parent && this.parent.isPending()); + }; + + /** + * Return `true` if this Runnable has failed. + * @return {boolean} + * @private + */ + Runnable$3.prototype.isFailed = function () { + return !this.isPending() && this.state === constants$3.STATE_FAILED; + }; + + /** + * Return `true` if this Runnable has passed. + * @return {boolean} + * @private + */ + Runnable$3.prototype.isPassed = function () { + return !this.isPending() && this.state === constants$3.STATE_PASSED; + }; + + /** + * Set or get number of retries. + * + * @private + */ + Runnable$3.prototype.retries = function (n) { + if (!arguments.length) { + return this._retries; + } + this._retries = n; + }; + + /** + * Set or get current retry + * + * @private + */ + Runnable$3.prototype.currentRetry = function (n) { + if (!arguments.length) { + return this._currentRetry; + } + this._currentRetry = n; + }; + + /** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Mocha.Runnable + * @public + * @return {string} + */ + Runnable$3.prototype.fullTitle = function () { + return this.titlePath().join(' '); + }; + + /** + * Return the title path generated by concatenating the parent's title path with the title. + * + * @memberof Mocha.Runnable + * @public + * @return {string[]} + */ + Runnable$3.prototype.titlePath = function () { + return this.parent.titlePath().concat([this.title]); + }; + + /** + * Clear the timeout. + * + * @private + */ + Runnable$3.prototype.clearTimeout = function () { + clearTimeout$1(this.timer); + }; + + /** + * Reset the timeout. + * + * @private + */ + Runnable$3.prototype.resetTimeout = function () { + var self = this; + var ms = this.timeout(); + + if (ms === 0) { + return; + } + this.clearTimeout(); + this.timer = setTimeout$2(function () { + if (self.timeout() === 0) { + return; + } + self.callback(self._timeoutError(ms)); + self.timedOut = true; + }, ms); + }; + + /** + * Set or get a list of whitelisted globals for this test run. + * + * @private + * @param {string[]} globals + */ + Runnable$3.prototype.globals = function (globals) { + if (!arguments.length) { + return this._allowedGlobals; + } + this._allowedGlobals = globals; + }; + + /** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @private + */ + Runnable$3.prototype.run = function (fn) { + var self = this; + var start = new Date$3(); + var ctx = this.ctx; + var finished; + var errorWasHandled = false; + + if (this.isPending()) return fn(); + + // Sometimes the ctx exists, but it is not runnable + if (ctx && ctx.runnable) { + ctx.runnable(this); + } + + // called multiple times + function multiple(err) { + if (errorWasHandled) { + return; + } + errorWasHandled = true; + self.emit('error', createMultipleDoneError(self, err)); + } + + // finished + function done(err) { + var ms = self.timeout(); + if (self.timedOut) { + return; + } + + if (finished) { + return multiple(err); + } + + self.clearTimeout(); + self.duration = new Date$3() - start; + finished = true; + if (!err && self.duration > ms && ms > 0) { + err = self._timeoutError(ms); + } + fn(err); + } + + // for .resetTimeout() and Runner#uncaught() + this.callback = done; + + if (this.fn && typeof this.fn.call !== 'function') { + done( + new TypeError( + 'A runnable must be passed a function as its second argument.' + ) + ); + return; + } + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout(); + + // allows skip() to be used in an explicit async context + this.skip = function asyncSkip() { + this.pending = true; + done(); + // halt execution, the uncaught handler will ignore the failure. + throw new Pending$1('async skip; aborting execution'); + }; + + try { + callFnAsync(this.fn); + } catch (err) { + // handles async runnables which actually run synchronously + errorWasHandled = true; + if (err instanceof Pending$1) { + return; // done() is already called in this.skip() + } else if (this.allowUncaught) { + throw err; + } + done(Runnable$3.toValueOrError(err)); + } + return; + } + + // sync or promise-returning + try { + callFn(this.fn); + } catch (err) { + errorWasHandled = true; + if (err instanceof Pending$1) { + return done(); + } else if (this.allowUncaught) { + throw err; + } + done(Runnable$3.toValueOrError(err)); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result.then( + function () { + done(); + // Return null so libraries like bluebird do not warn about + // subsequently constructed Promises. + return null; + }, + function (reason) { + done(reason || new Error('Promise rejected with no or falsy reason')); + } + ); + } else { + if (self.asyncOnly) { + return done( + new Error( + '--async-only option in use without declaring `done()` or returning a promise' + ) + ); + } + + done(); + } + } + + function callFnAsync(fn) { + var result = fn.call(ctx, function (err) { + if (err instanceof Error || toString.call(err) === '[object Error]') { + return done(err); + } + if (err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done( + new Error('done() invoked with non-Error: ' + JSON.stringify(err)) + ); + } + return done(new Error('done() invoked with non-Error: ' + err)); + } + if (result && utils$2.isPromise(result)) { + return done( + new Error( + 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.' + ) + ); + } + + done(); + }); + } + }; + + /** + * Instantiates a "timeout" error + * + * @param {number} ms - Timeout (in milliseconds) + * @returns {Error} a "timeout" error + * @private + */ + Runnable$3.prototype._timeoutError = function (ms) { + let msg = `Timeout of ${ms}ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.`; + if (this.file) { + msg += ' (' + this.file + ')'; + } + return createTimeoutError(msg, ms, this.file); + }; + + var constants$3 = utils$2.defineConstants( + /** + * {@link Runnable}-related constants. + * @public + * @memberof Runnable + * @readonly + * @static + * @alias constants + * @enum {string} + */ + { + /** + * Value of `state` prop when a `Runnable` has failed + */ + STATE_FAILED: 'failed', + /** + * Value of `state` prop when a `Runnable` has passed + */ + STATE_PASSED: 'passed', + /** + * Value of `state` prop when a `Runnable` has been skipped by user + */ + STATE_PENDING: 'pending' + } + ); + + /** + * Given `value`, return identity if truthy, otherwise create an "invalid exception" error and return that. + * @param {*} [value] - Value to return, if present + * @returns {*|Error} `value`, otherwise an `Error` + * @private + */ + Runnable$3.toValueOrError = function (value) { + return ( + value || + createInvalidExceptionError$1( + 'Runnable failed with falsy or undefined exception. Please throw an Error instead.', + value + ) + ); + }; + + Runnable$3.constants = constants$3; + + var suite = {exports: {}}; + + var Runnable$2 = runnable; + const {inherits, constants: constants$2} = utils$3; + const {MOCHA_ID_PROP_NAME: MOCHA_ID_PROP_NAME$1} = constants$2; + + /** + * Expose `Hook`. + */ + + var hook = Hook; + + /** + * Initialize a new `Hook` with the given `title` and callback `fn` + * + * @class + * @extends Runnable + * @param {String} title + * @param {Function} fn + */ + function Hook(title, fn) { + Runnable$2.call(this, title, fn); + this.type = 'hook'; + } + + /** + * Inherit from `Runnable.prototype`. + */ + inherits(Hook, Runnable$2); + + /** + * Resets the state for a next run. + */ + Hook.prototype.reset = function () { + Runnable$2.prototype.reset.call(this); + delete this._error; + }; + + /** + * Get or set the test `err`. + * + * @memberof Hook + * @public + * @param {Error} err + * @return {Error} + */ + Hook.prototype.error = function (err) { + if (!arguments.length) { + err = this._error; + this._error = null; + return err; + } + + this._error = err; + }; + + /** + * Returns an object suitable for IPC. + * Functions are represented by keys beginning with `$$`. + * @private + * @returns {Object} + */ + Hook.prototype.serialize = function serialize() { + return { + $$currentRetry: this.currentRetry(), + $$fullTitle: this.fullTitle(), + $$isPending: Boolean(this.isPending()), + $$titlePath: this.titlePath(), + ctx: + this.ctx && this.ctx.currentTest + ? { + currentTest: { + title: this.ctx.currentTest.title, + [MOCHA_ID_PROP_NAME$1]: this.ctx.currentTest.id + } + } + : {}, + duration: this.duration, + file: this.file, + parent: { + $$fullTitle: this.parent.fullTitle(), + [MOCHA_ID_PROP_NAME$1]: this.parent.id + }, + state: this.state, + title: this.title, + type: this.type, + [MOCHA_ID_PROP_NAME$1]: this.id + }; + }; + + (function (module, exports) { + + /** + * Module dependencies. + * @private + */ + const {EventEmitter} = require$$0; + const Hook = hook; + var { + assignNewMochaID, + clamp, + constants: utilsConstants, + defineConstants, + getMochaID, + inherits, + isString + } = utils$3; + const debug = browser.exports('mocha:suite'); + const milliseconds = ms$1; + const errors = errors$2; + + const {MOCHA_ID_PROP_NAME} = utilsConstants; + + /** + * Expose `Suite`. + */ + + module.exports = Suite; + + /** + * Create a new `Suite` with the given `title` and parent `Suite`. + * + * @public + * @param {Suite} parent - Parent suite (required!) + * @param {string} title - Title + * @return {Suite} + */ + Suite.create = function (parent, title) { + var suite = new Suite(title, parent.ctx); + suite.parent = parent; + title = suite.fullTitle(); + parent.addSuite(suite); + return suite; + }; + + /** + * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`. + * + * @public + * @class + * @extends EventEmitter + * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter} + * @param {string} title - Suite title. + * @param {Context} parentContext - Parent context instance. + * @param {boolean} [isRoot=false] - Whether this is the root suite. + */ + function Suite(title, parentContext, isRoot) { + if (!isString(title)) { + throw errors.createInvalidArgumentTypeError( + 'Suite argument "title" must be a string. Received type "' + + typeof title + + '"', + 'title', + 'string' + ); + } + this.title = title; + function Context() {} + Context.prototype = parentContext; + this.ctx = new Context(); + this.suites = []; + this.tests = []; + this.root = isRoot === true; + this.pending = false; + this._retries = -1; + this._beforeEach = []; + this._beforeAll = []; + this._afterEach = []; + this._afterAll = []; + this._timeout = 2000; + this._slow = 75; + this._bail = false; + this._onlyTests = []; + this._onlySuites = []; + assignNewMochaID(this); + + Object.defineProperty(this, 'id', { + get() { + return getMochaID(this); + } + }); + + this.reset(); + } + + /** + * Inherit from `EventEmitter.prototype`. + */ + inherits(Suite, EventEmitter); + + /** + * Resets the state initially or for a next run. + */ + Suite.prototype.reset = function () { + this.delayed = false; + function doReset(thingToReset) { + thingToReset.reset(); + } + this.suites.forEach(doReset); + this.tests.forEach(doReset); + this._beforeEach.forEach(doReset); + this._afterEach.forEach(doReset); + this._beforeAll.forEach(doReset); + this._afterAll.forEach(doReset); + }; + + /** + * Return a clone of this `Suite`. + * + * @private + * @return {Suite} + */ + Suite.prototype.clone = function () { + var suite = new Suite(this.title); + debug('clone'); + suite.ctx = this.ctx; + suite.root = this.root; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.slow(this.slow()); + suite.bail(this.bail()); + return suite; + }; + + /** + * Set or get timeout `ms` or short-hand such as "2s". + * + * @private + * @todo Do not attempt to set value if `ms` is undefined + * @param {number|string} ms + * @return {Suite|number} for chaining + */ + Suite.prototype.timeout = function (ms) { + if (!arguments.length) { + return this._timeout; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + + // Clamp to range + var INT_MAX = Math.pow(2, 31) - 1; + var range = [0, INT_MAX]; + ms = clamp(ms, range); + + debug('timeout %d', ms); + this._timeout = parseInt(ms, 10); + return this; + }; + + /** + * Set or get number of times to retry a failed test. + * + * @private + * @param {number|string} n + * @return {Suite|number} for chaining + */ + Suite.prototype.retries = function (n) { + if (!arguments.length) { + return this._retries; + } + debug('retries %d', n); + this._retries = parseInt(n, 10) || 0; + return this; + }; + + /** + * Set or get slow `ms` or short-hand such as "2s". + * + * @private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ + Suite.prototype.slow = function (ms) { + if (!arguments.length) { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } + debug('slow %d', ms); + this._slow = ms; + return this; + }; + + /** + * Set or get whether to bail after first error. + * + * @private + * @param {boolean} bail + * @return {Suite|number} for chaining + */ + Suite.prototype.bail = function (bail) { + if (!arguments.length) { + return this._bail; + } + debug('bail %s', bail); + this._bail = bail; + return this; + }; + + /** + * Check if this suite or its parent suite is marked as pending. + * + * @private + */ + Suite.prototype.isPending = function () { + return this.pending || (this.parent && this.parent.isPending()); + }; + + /** + * Generic hook-creator. + * @private + * @param {string} title - Title of hook + * @param {Function} fn - Hook callback + * @returns {Hook} A new hook + */ + Suite.prototype._createHook = function (title, fn) { + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + hook.file = this.file; + return hook; + }; + + /** + * Run `fn(test[, done])` before running tests. + * + * @private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ + Suite.prototype.beforeAll = function (title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeAll.push(hook); + this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook); + return this; + }; + + /** + * Run `fn(test[, done])` after running tests. + * + * @private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ + Suite.prototype.afterAll = function (title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterAll.push(hook); + this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook); + return this; + }; + + /** + * Run `fn(test[, done])` before each test case. + * + * @private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ + Suite.prototype.beforeEach = function (title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._beforeEach.push(hook); + this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook); + return this; + }; + + /** + * Run `fn(test[, done])` after each test case. + * + * @private + * @param {string} title + * @param {Function} fn + * @return {Suite} for chaining + */ + Suite.prototype.afterEach = function (title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = this._createHook(title, fn); + this._afterEach.push(hook); + this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook); + return this; + }; + + /** + * Add a test `suite`. + * + * @private + * @param {Suite} suite + * @return {Suite} for chaining + */ + Suite.prototype.addSuite = function (suite) { + suite.parent = this; + suite.root = false; + suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.slow(this.slow()); + suite.bail(this.bail()); + this.suites.push(suite); + this.emit(constants.EVENT_SUITE_ADD_SUITE, suite); + return this; + }; + + /** + * Add a `test` to this suite. + * + * @private + * @param {Test} test + * @return {Suite} for chaining + */ + Suite.prototype.addTest = function (test) { + test.parent = this; + test.timeout(this.timeout()); + test.retries(this.retries()); + test.slow(this.slow()); + test.ctx = this.ctx; + this.tests.push(test); + this.emit(constants.EVENT_SUITE_ADD_TEST, test); + return this; + }; + + /** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @memberof Suite + * @public + * @return {string} + */ + Suite.prototype.fullTitle = function () { + return this.titlePath().join(' '); + }; + + /** + * Return the title path generated by recursively concatenating the parent's + * title path. + * + * @memberof Suite + * @public + * @return {string[]} + */ + Suite.prototype.titlePath = function () { + var result = []; + if (this.parent) { + result = result.concat(this.parent.titlePath()); + } + if (!this.root) { + result.push(this.title); + } + return result; + }; + + /** + * Return the total number of tests. + * + * @memberof Suite + * @public + * @return {number} + */ + Suite.prototype.total = function () { + return ( + this.suites.reduce(function (sum, suite) { + return sum + suite.total(); + }, 0) + this.tests.length + ); + }; + + /** + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. + * + * @private + * @param {Function} fn + * @return {Suite} + */ + Suite.prototype.eachTest = function (fn) { + this.tests.forEach(fn); + this.suites.forEach(function (suite) { + suite.eachTest(fn); + }); + return this; + }; + + /** + * This will run the root suite if we happen to be running in delayed mode. + * @private + */ + Suite.prototype.run = function run() { + if (this.root) { + this.emit(constants.EVENT_ROOT_SUITE_RUN); + } + }; + + /** + * Determines whether a suite has an `only` test or suite as a descendant. + * + * @private + * @returns {Boolean} + */ + Suite.prototype.hasOnly = function hasOnly() { + return ( + this._onlyTests.length > 0 || + this._onlySuites.length > 0 || + this.suites.some(function (suite) { + return suite.hasOnly(); + }) + ); + }; + + /** + * Filter suites based on `isOnly` logic. + * + * @private + * @returns {Boolean} + */ + Suite.prototype.filterOnly = function filterOnly() { + if (this._onlyTests.length) { + // If the suite contains `only` tests, run those and ignore any nested suites. + this.tests = this._onlyTests; + this.suites = []; + } else { + // Otherwise, do not run any of the tests in this suite. + this.tests = []; + this._onlySuites.forEach(function (onlySuite) { + // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite. + // Otherwise, all of the tests on this `only` suite should be run, so don't filter it. + if (onlySuite.hasOnly()) { + onlySuite.filterOnly(); + } + }); + // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants. + var onlySuites = this._onlySuites; + this.suites = this.suites.filter(function (childSuite) { + return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly(); + }); + } + // Keep the suite only if there is something to run + return this.tests.length > 0 || this.suites.length > 0; + }; + + /** + * Adds a suite to the list of subsuites marked `only`. + * + * @private + * @param {Suite} suite + */ + Suite.prototype.appendOnlySuite = function (suite) { + this._onlySuites.push(suite); + }; + + /** + * Marks a suite to be `only`. + * + * @private + */ + Suite.prototype.markOnly = function () { + this.parent && this.parent.appendOnlySuite(this); + }; + + /** + * Adds a test to the list of tests marked `only`. + * + * @private + * @param {Test} test + */ + Suite.prototype.appendOnlyTest = function (test) { + this._onlyTests.push(test); + }; + + /** + * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants. + * @private + */ + Suite.prototype.getHooks = function getHooks(name) { + return this['_' + name]; + }; + + /** + * cleans all references from this suite and all child suites. + */ + Suite.prototype.dispose = function () { + this.suites.forEach(function (suite) { + suite.dispose(); + }); + this.cleanReferences(); + }; + + /** + * Cleans up the references to all the deferred functions + * (before/after/beforeEach/afterEach) and tests of a Suite. + * These must be deleted otherwise a memory leak can happen, + * as those functions may reference variables from closures, + * thus those variables can never be garbage collected as long + * as the deferred functions exist. + * + * @private + */ + Suite.prototype.cleanReferences = function cleanReferences() { + function cleanArrReferences(arr) { + for (var i = 0; i < arr.length; i++) { + delete arr[i].fn; + } + } + + if (Array.isArray(this._beforeAll)) { + cleanArrReferences(this._beforeAll); + } + + if (Array.isArray(this._beforeEach)) { + cleanArrReferences(this._beforeEach); + } + + if (Array.isArray(this._afterAll)) { + cleanArrReferences(this._afterAll); + } + + if (Array.isArray(this._afterEach)) { + cleanArrReferences(this._afterEach); + } + + for (var i = 0; i < this.tests.length; i++) { + delete this.tests[i].fn; + } + }; + + /** + * Returns an object suitable for IPC. + * Functions are represented by keys beginning with `$$`. + * @private + * @returns {Object} + */ + Suite.prototype.serialize = function serialize() { + return { + _bail: this._bail, + $$fullTitle: this.fullTitle(), + $$isPending: Boolean(this.isPending()), + root: this.root, + title: this.title, + [MOCHA_ID_PROP_NAME]: this.id, + parent: this.parent ? {[MOCHA_ID_PROP_NAME]: this.parent.id} : null + }; + }; + + var constants = defineConstants( + /** + * {@link Suite}-related constants. + * @public + * @memberof Suite + * @alias constants + * @readonly + * @static + * @enum {string} + */ + { + /** + * Event emitted after a test file has been loaded. Not emitted in browser. + */ + EVENT_FILE_POST_REQUIRE: 'post-require', + /** + * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected. + */ + EVENT_FILE_PRE_REQUIRE: 'pre-require', + /** + * Event emitted immediately after a test file has been loaded. Not emitted in browser. + */ + EVENT_FILE_REQUIRE: 'require', + /** + * Event emitted when `global.run()` is called (use with `delay` option). + */ + EVENT_ROOT_SUITE_RUN: 'run', + + /** + * Namespace for collection of a `Suite`'s "after all" hooks. + */ + HOOK_TYPE_AFTER_ALL: 'afterAll', + /** + * Namespace for collection of a `Suite`'s "after each" hooks. + */ + HOOK_TYPE_AFTER_EACH: 'afterEach', + /** + * Namespace for collection of a `Suite`'s "before all" hooks. + */ + HOOK_TYPE_BEFORE_ALL: 'beforeAll', + /** + * Namespace for collection of a `Suite`'s "before each" hooks. + */ + HOOK_TYPE_BEFORE_EACH: 'beforeEach', + + /** + * Emitted after a child `Suite` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_SUITE: 'suite', + /** + * Emitted after an "after all" `Hook` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll', + /** + * Emitted after an "after each" `Hook` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach', + /** + * Emitted after an "before all" `Hook` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll', + /** + * Emitted after an "before each" `Hook` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach', + /** + * Emitted after a `Test` has been added to a `Suite`. + */ + EVENT_SUITE_ADD_TEST: 'test' + } + ); + + Suite.constants = constants; + }(suite)); + + /** + * Module dependencies. + * @private + */ + var EventEmitter = require$$0.EventEmitter; + var Pending = pending; + var utils$1 = utils$3; + var debug = browser.exports('mocha:runner'); + var Runnable$1 = runnable; + var Suite$2 = suite.exports; + var HOOK_TYPE_BEFORE_EACH = Suite$2.constants.HOOK_TYPE_BEFORE_EACH; + var HOOK_TYPE_AFTER_EACH = Suite$2.constants.HOOK_TYPE_AFTER_EACH; + var HOOK_TYPE_AFTER_ALL = Suite$2.constants.HOOK_TYPE_AFTER_ALL; + var HOOK_TYPE_BEFORE_ALL = Suite$2.constants.HOOK_TYPE_BEFORE_ALL; + var EVENT_ROOT_SUITE_RUN = Suite$2.constants.EVENT_ROOT_SUITE_RUN; + var STATE_FAILED = Runnable$1.constants.STATE_FAILED; + var STATE_PASSED = Runnable$1.constants.STATE_PASSED; + var STATE_PENDING = Runnable$1.constants.STATE_PENDING; + var stackFilter = utils$1.stackTraceFilter(); + var stringify = utils$1.stringify; + + const { + createInvalidExceptionError, + createUnsupportedError: createUnsupportedError$1, + createFatalError, + isMochaError, + constants: errorConstants + } = errors$2; + + /** + * Non-enumerable globals. + * @private + * @readonly + */ + var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date', + 'setImmediate', + 'clearImmediate' + ]; + + var constants$1 = utils$1.defineConstants( + /** + * {@link Runner}-related constants. + * @public + * @memberof Runner + * @readonly + * @alias constants + * @static + * @enum {string} + */ + { + /** + * Emitted when {@link Hook} execution begins + */ + EVENT_HOOK_BEGIN: 'hook', + /** + * Emitted when {@link Hook} execution ends + */ + EVENT_HOOK_END: 'hook end', + /** + * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution) + */ + EVENT_RUN_BEGIN: 'start', + /** + * Emitted when Root {@link Suite} execution has been delayed via `delay` option + */ + EVENT_DELAY_BEGIN: 'waiting', + /** + * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()` + */ + EVENT_DELAY_END: 'ready', + /** + * Emitted when Root {@link Suite} execution ends + */ + EVENT_RUN_END: 'end', + /** + * Emitted when {@link Suite} execution begins + */ + EVENT_SUITE_BEGIN: 'suite', + /** + * Emitted when {@link Suite} execution ends + */ + EVENT_SUITE_END: 'suite end', + /** + * Emitted when {@link Test} execution begins + */ + EVENT_TEST_BEGIN: 'test', + /** + * Emitted when {@link Test} execution ends + */ + EVENT_TEST_END: 'test end', + /** + * Emitted when {@link Test} execution fails + */ + EVENT_TEST_FAIL: 'fail', + /** + * Emitted when {@link Test} execution succeeds + */ + EVENT_TEST_PASS: 'pass', + /** + * Emitted when {@link Test} becomes pending + */ + EVENT_TEST_PENDING: 'pending', + /** + * Emitted when {@link Test} execution has failed, but will retry + */ + EVENT_TEST_RETRY: 'retry', + /** + * Initial state of Runner + */ + STATE_IDLE: 'idle', + /** + * State set to this value when the Runner has started running + */ + STATE_RUNNING: 'running', + /** + * State set to this value when the Runner has stopped + */ + STATE_STOPPED: 'stopped' + } + ); + + class Runner extends EventEmitter { + /** + * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}. + * + * @extends external:EventEmitter + * @public + * @class + * @param {Suite} suite - Root suite + * @param {Object} [opts] - Settings object + * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done. + * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready. + * @param {boolean} [opts.dryRun] - Whether to report tests without running them. + * @param {boolean} [opts.failZero] - Whether to fail test run if zero tests encountered. + */ + constructor(suite, opts = {}) { + super(); + + var self = this; + this._globals = []; + this._abort = false; + this.suite = suite; + this._opts = opts; + this.state = constants$1.STATE_IDLE; + this.total = suite.total(); + this.failures = 0; + /** + * @type {Map>>} + */ + this._eventListeners = new Map(); + this.on(constants$1.EVENT_TEST_END, function (test) { + if (test.type === 'test' && test.retriedTest() && test.parent) { + var idx = + test.parent.tests && test.parent.tests.indexOf(test.retriedTest()); + if (idx > -1) test.parent.tests[idx] = test; + } + self.checkGlobals(test); + }); + this.on(constants$1.EVENT_HOOK_END, function (hook) { + self.checkGlobals(hook); + }); + this._defaultGrep = /.*/; + this.grep(this._defaultGrep); + this.globals(this.globalProps()); + + this.uncaught = this._uncaught.bind(this); + this.unhandled = (reason, promise) => { + if (isMochaError(reason)) { + debug( + 'trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:', + reason + ); + this.uncaught(reason); + } else { + debug( + 'trapped unhandled rejection from (probably) user code; re-emitting on process' + ); + this._removeEventListener( + process, + 'unhandledRejection', + this.unhandled + ); + try { + process.emit('unhandledRejection', reason, promise); + } finally { + this._addEventListener(process, 'unhandledRejection', this.unhandled); + } + } + }; + } + } + + /** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @private + */ + Runner.immediately = commonjsGlobal.setImmediate || nextTick$1; + + /** + * Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed. + * @param {EventEmitter} target - The `EventEmitter` + * @param {string} eventName - The event name + * @param {string} fn - Listener function + * @private + */ + Runner.prototype._addEventListener = function (target, eventName, listener) { + debug( + '_addEventListener(): adding for event %s; %d current listeners', + eventName, + target.listenerCount(eventName) + ); + /* istanbul ignore next */ + if ( + this._eventListeners.has(target) && + this._eventListeners.get(target).has(eventName) && + this._eventListeners.get(target).get(eventName).has(listener) + ) { + debug( + 'warning: tried to attach duplicate event listener for %s', + eventName + ); + return; + } + target.on(eventName, listener); + const targetListeners = this._eventListeners.has(target) + ? this._eventListeners.get(target) + : new Map(); + const targetEventListeners = targetListeners.has(eventName) + ? targetListeners.get(eventName) + : new Set(); + targetEventListeners.add(listener); + targetListeners.set(eventName, targetEventListeners); + this._eventListeners.set(target, targetListeners); + }; + + /** + * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping. + * @param {EventEmitter} target - The `EventEmitter` + * @param {string} eventName - The event name + * @param {function} listener - Listener function + * @private + */ + Runner.prototype._removeEventListener = function (target, eventName, listener) { + target.removeListener(eventName, listener); + + if (this._eventListeners.has(target)) { + const targetListeners = this._eventListeners.get(target); + if (targetListeners.has(eventName)) { + const targetEventListeners = targetListeners.get(eventName); + targetEventListeners.delete(listener); + if (!targetEventListeners.size) { + targetListeners.delete(eventName); + } + } + if (!targetListeners.size) { + this._eventListeners.delete(target); + } + } else { + debug('trying to remove listener for untracked object %s', target); + } + }; + + /** + * Removes all event handlers set during a run on this instance. + * Remark: this does _not_ clean/dispose the tests or suites themselves. + */ + Runner.prototype.dispose = function () { + this.removeAllListeners(); + this._eventListeners.forEach((targetListeners, target) => { + targetListeners.forEach((targetEventListeners, eventName) => { + targetEventListeners.forEach(listener => { + target.removeListener(eventName, listener); + }); + }); + }); + this._eventListeners.clear(); + }; + + /** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @public + * @memberof Runner + * @param {RegExp} re + * @param {boolean} invert + * @return {Runner} Runner instance. + */ + Runner.prototype.grep = function (re, invert) { + debug('grep(): setting to %s', re); + this._grep = re; + this._invert = invert; + this.total = this.grepTotal(this.suite); + return this; + }; + + /** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @memberof Runner + * @public + * @param {Suite} suite + * @return {number} + */ + Runner.prototype.grepTotal = function (suite) { + var self = this; + var total = 0; + + suite.eachTest(function (test) { + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (match) { + total++; + } + }); + + return total; + }; + + /** + * Return a list of global properties. + * + * @return {Array} + * @private + */ + Runner.prototype.globalProps = function () { + var props = Object.keys(commonjsGlobal); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~props.indexOf(globals[i])) { + continue; + } + props.push(globals[i]); + } + + return props; + }; + + /** + * Allow the given `arr` of globals. + * + * @public + * @memberof Runner + * @param {Array} arr + * @return {Runner} Runner instance. + */ + Runner.prototype.globals = function (arr) { + if (!arguments.length) { + return this._globals; + } + debug('globals(): setting to %O', arr); + this._globals = this._globals.concat(arr); + return this; + }; + + /** + * Check for global variable leaks. + * + * @private + */ + Runner.prototype.checkGlobals = function (test) { + if (!this.checkLeaks) { + return; + } + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if (this.prevGlobalsLength === globals.length) { + return; + } + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); + this._globals = this._globals.concat(leaks); + + if (leaks.length) { + var msg = `global leak(s) detected: ${leaks.map(e => `'${e}'`).join(', ')}`; + this.fail(test, new Error(msg)); + } + }; + + /** + * Fail the given `test`. + * + * If `test` is a hook, failures work in the following pattern: + * - If bail, run corresponding `after each` and `after` hooks, + * then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @private + * @param {Runnable} test + * @param {Error} err + * @param {boolean} [force=false] - Whether to fail a pending test. + */ + Runner.prototype.fail = function (test, err, force) { + force = force === true; + if (test.isPending() && !force) { + return; + } + if (this.state === constants$1.STATE_STOPPED) { + if (err.code === errorConstants.MULTIPLE_DONE) { + throw err; + } + throw createFatalError( + 'Test failed after root suite execution completed!', + err + ); + } + + ++this.failures; + debug('total number of failures: %d', this.failures); + test.state = STATE_FAILED; + + if (!isError(err)) { + err = thrown2Error(err); + } + + // Filter the stack traces + if (!this.fullStackTrace) { + const alreadyFiltered = new Set(); + let currentErr = err; + + while (currentErr && currentErr.stack && !alreadyFiltered.has(currentErr)) { + alreadyFiltered.add(currentErr); + + try { + currentErr.stack = stackFilter(currentErr.stack); + } catch (ignore) { + // some environments do not take kindly to monkeying with the stack + } + + currentErr = currentErr.cause; + } + } + + this.emit(constants$1.EVENT_TEST_FAIL, test, err); + }; + + /** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @private + * @param {string} name + * @param {Function} fn + */ + + Runner.prototype.hook = function (name, fn) { + if (this._opts.dryRun) return fn(); + + var suite = this.suite; + var hooks = suite.getHooks(name); + var self = this; + + function next(i) { + var hook = hooks[i]; + if (!hook) { + return fn(); + } + self.currentRunnable = hook; + + if (name === HOOK_TYPE_BEFORE_ALL) { + hook.ctx.currentTest = hook.parent.tests[0]; + } else if (name === HOOK_TYPE_AFTER_ALL) { + hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1]; + } else { + hook.ctx.currentTest = self.test; + } + + setHookTitle(hook); + + hook.allowUncaught = self.allowUncaught; + + self.emit(constants$1.EVENT_HOOK_BEGIN, hook); + + if (!hook.listeners('error').length) { + self._addEventListener(hook, 'error', function (err) { + self.fail(hook, err); + }); + } + + hook.run(function cbHookRun(err) { + var testError = hook.error(); + if (testError) { + self.fail(self.test, testError); + } + // conditional skip + if (hook.pending) { + if (name === HOOK_TYPE_AFTER_EACH) { + // TODO define and implement use case + if (self.test) { + self.test.pending = true; + } + } else if (name === HOOK_TYPE_BEFORE_EACH) { + if (self.test) { + self.test.pending = true; + } + self.emit(constants$1.EVENT_HOOK_END, hook); + hook.pending = false; // activates hook for next test + return fn(new Error('abort hookDown')); + } else if (name === HOOK_TYPE_BEFORE_ALL) { + suite.tests.forEach(function (test) { + test.pending = true; + }); + suite.suites.forEach(function (suite) { + suite.pending = true; + }); + hooks = []; + } else { + hook.pending = false; + var errForbid = createUnsupportedError$1('`this.skip` forbidden'); + self.fail(hook, errForbid); + return fn(errForbid); + } + } else if (err) { + self.fail(hook, err); + // stop executing hooks, notify callee of hook err + return fn(err); + } + self.emit(constants$1.EVENT_HOOK_END, hook); + delete hook.ctx.currentTest; + setHookTitle(hook); + next(++i); + }); + + function setHookTitle(hook) { + hook.originalTitle = hook.originalTitle || hook.title; + if (hook.ctx && hook.ctx.currentTest) { + hook.title = `${hook.originalTitle} for "${hook.ctx.currentTest.title}"`; + } else { + var parentTitle; + if (hook.parent.title) { + parentTitle = hook.parent.title; + } else { + parentTitle = hook.parent.root ? '{root}' : ''; + } + hook.title = `${hook.originalTitle} in "${parentTitle}"`; + } + } + } + + Runner.immediately(function () { + next(0); + }); + }; + + /** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @private + * @param {string} name + * @param {Array} suites + * @param {Function} fn + */ + Runner.prototype.hooks = function (name, suites, fn) { + var self = this; + var orig = this.suite; + + function next(suite) { + self.suite = suite; + + if (!suite) { + self.suite = orig; + return fn(); + } + + self.hook(name, function (err) { + if (err) { + var errSuite = self.suite; + self.suite = orig; + return fn(err, errSuite); + } + + next(suites.pop()); + }); + } + + next(suites.pop()); + }; + + /** + * Run 'afterEach' hooks from bottom up. + * + * @param {String} name + * @param {Function} fn + * @private + */ + Runner.prototype.hookUp = function (name, fn) { + var suites = [this.suite].concat(this.parents()).reverse(); + this.hooks(name, suites, fn); + }; + + /** + * Run 'beforeEach' hooks from top level down. + * + * @param {String} name + * @param {Function} fn + * @private + */ + Runner.prototype.hookDown = function (name, fn) { + var suites = [this.suite].concat(this.parents()); + this.hooks(name, suites, fn); + }; + + /** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @private + */ + Runner.prototype.parents = function () { + var suite = this.suite; + var suites = []; + while (suite.parent) { + suite = suite.parent; + suites.push(suite); + } + return suites; + }; + + /** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @private + */ + Runner.prototype.runTest = function (fn) { + if (this._opts.dryRun) return Runner.immediately(fn); + + var self = this; + var test = this.test; + + if (!test) { + return; + } + + if (this.asyncOnly) { + test.asyncOnly = true; + } + this._addEventListener(test, 'error', function (err) { + self.fail(test, err); + }); + if (this.allowUncaught) { + test.allowUncaught = true; + return test.run(fn); + } + try { + test.run(fn); + } catch (err) { + fn(err); + } + }; + + /** + * Run tests in the given `suite` and invoke the callback `fn()` when complete. + * + * @private + * @param {Suite} suite + * @param {Function} fn + */ + Runner.prototype.runTests = function (suite, fn) { + var self = this; + var tests = suite.tests.slice(); + var test; + + function hookErr(_, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + self.hookUp(HOOK_TYPE_AFTER_EACH, function (err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) { + return hookErr(err2, errSuite2, true); + } + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) { + tests = []; + } + + if (self._abort) { + return fn(); + } + + if (err) { + return hookErr(err, errSuite, true); + } + + // next test + test = tests.shift(); + + // all done + if (!test) { + return fn(); + } + + // grep + var match = self._grep.test(test.fullTitle()); + if (self._invert) { + match = !match; + } + if (!match) { + // Run immediately only if we have defined a grep. When we + // define a grep — It can cause maximum callstack error if + // the grep is doing a large recursive loop by neglecting + // all tests. The run immediately function also comes with + // a performance cost. So we don't want to run immediately + // if we run the whole test suite, because running the whole + // test suite don't do any immediate recursive loops. Thus, + // allowing a JS runtime to breathe. + if (self._grep !== self._defaultGrep) { + Runner.immediately(next); + } else { + next(); + } + return; + } + + // static skip, no hooks are executed + if (test.isPending()) { + if (self.forbidPending) { + self.fail(test, new Error('Pending test forbidden'), true); + } else { + test.state = STATE_PENDING; + self.emit(constants$1.EVENT_TEST_PENDING, test); + } + self.emit(constants$1.EVENT_TEST_END, test); + return next(); + } + + // execute test and hook(s) + self.emit(constants$1.EVENT_TEST_BEGIN, (self.test = test)); + self.hookDown(HOOK_TYPE_BEFORE_EACH, function (err, errSuite) { + // conditional skip within beforeEach + if (test.isPending()) { + if (self.forbidPending) { + self.fail(test, new Error('Pending test forbidden'), true); + } else { + test.state = STATE_PENDING; + self.emit(constants$1.EVENT_TEST_PENDING, test); + } + self.emit(constants$1.EVENT_TEST_END, test); + // skip inner afterEach hooks below errSuite level + var origSuite = self.suite; + self.suite = errSuite || self.suite; + return self.hookUp(HOOK_TYPE_AFTER_EACH, function (e, eSuite) { + self.suite = origSuite; + next(e, eSuite); + }); + } + if (err) { + return hookErr(err, errSuite, false); + } + self.currentRunnable = self.test; + self.runTest(function (err) { + test = self.test; + // conditional skip within it + if (test.pending) { + if (self.forbidPending) { + self.fail(test, new Error('Pending test forbidden'), true); + } else { + test.state = STATE_PENDING; + self.emit(constants$1.EVENT_TEST_PENDING, test); + } + self.emit(constants$1.EVENT_TEST_END, test); + return self.hookUp(HOOK_TYPE_AFTER_EACH, next); + } else if (err) { + var retry = test.currentRetry(); + if (retry < test.retries()) { + var clonedTest = test.clone(); + clonedTest.currentRetry(retry + 1); + tests.unshift(clonedTest); + + self.emit(constants$1.EVENT_TEST_RETRY, test, err); + + // Early return + hook trigger so that it doesn't + // increment the count wrong + return self.hookUp(HOOK_TYPE_AFTER_EACH, next); + } else { + self.fail(test, err); + } + self.emit(constants$1.EVENT_TEST_END, test); + return self.hookUp(HOOK_TYPE_AFTER_EACH, next); + } + + test.state = STATE_PASSED; + self.emit(constants$1.EVENT_TEST_PASS, test); + self.emit(constants$1.EVENT_TEST_END, test); + self.hookUp(HOOK_TYPE_AFTER_EACH, next); + }); + }); + } + + this.next = next; + this.hookErr = hookErr; + next(); + }; + + /** + * Run the given `suite` and invoke the callback `fn()` when complete. + * + * @private + * @param {Suite} suite + * @param {Function} fn + */ + Runner.prototype.runSuite = function (suite, fn) { + var i = 0; + var self = this; + var total = this.grepTotal(suite); + + debug('runSuite(): running %s', suite.fullTitle()); + + if (!total || (self.failures && suite._bail)) { + debug('runSuite(): bailing'); + return fn(); + } + + this.emit(constants$1.EVENT_SUITE_BEGIN, (this.suite = suite)); + + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite === suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + + if (self._abort) { + return done(); + } + + var curr = suite.suites[i++]; + if (!curr) { + return done(); + } + + // Avoid grep neglecting large number of tests causing a + // huge recursive loop and thus a maximum call stack error. + // See comment in `this.runTests()` for more information. + if (self._grep !== self._defaultGrep) { + Runner.immediately(function () { + self.runSuite(curr, next); + }); + } else { + self.runSuite(curr, next); + } + } + + function done(errSuite) { + self.suite = suite; + self.nextSuite = next; + + // remove reference to test + delete self.test; + + self.hook(HOOK_TYPE_AFTER_ALL, function () { + self.emit(constants$1.EVENT_SUITE_END, suite); + fn(errSuite); + }); + } + + this.nextSuite = next; + + this.hook(HOOK_TYPE_BEFORE_ALL, function (err) { + if (err) { + return done(); + } + self.runTests(suite, next); + }); + }; + + /** + * Handle uncaught exceptions within runner. + * + * This function is bound to the instance as `Runner#uncaught` at instantiation + * time. It's intended to be listening on the `Process.uncaughtException` event. + * In order to not leak EE listeners, we need to ensure no more than a single + * `uncaughtException` listener exists per `Runner`. The only way to do + * this--because this function needs the context (and we don't have lambdas)--is + * to use `Function.prototype.bind`. We need strict equality to unregister and + * _only_ unregister the _one_ listener we set from the + * `Process.uncaughtException` event; would be poor form to just remove + * everything. See {@link Runner#run} for where the event listener is registered + * and unregistered. + * @param {Error} err - Some uncaught error + * @private + */ + Runner.prototype._uncaught = function (err) { + // this is defensive to prevent future developers from mis-calling this function. + // it's more likely that it'd be called with the incorrect context--say, the global + // `process` object--than it would to be called with a context that is not a "subclass" + // of `Runner`. + if (!(this instanceof Runner)) { + throw createFatalError( + 'Runner#uncaught() called with invalid context', + this + ); + } + if (err instanceof Pending) { + debug('uncaught(): caught a Pending'); + return; + } + // browser does not exit script when throwing in global.onerror() + if (this.allowUncaught && !utils$1.isBrowser()) { + debug('uncaught(): bubbling exception due to --allow-uncaught'); + throw err; + } + + if (this.state === constants$1.STATE_STOPPED) { + debug('uncaught(): throwing after run has completed!'); + throw err; + } + + if (err) { + debug('uncaught(): got truthy exception %O', err); + } else { + debug('uncaught(): undefined/falsy exception'); + err = createInvalidExceptionError( + 'Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger', + err + ); + } + + if (!isError(err)) { + err = thrown2Error(err); + debug('uncaught(): converted "error" %o to Error', err); + } + err.uncaught = true; + + var runnable = this.currentRunnable; + + if (!runnable) { + runnable = new Runnable$1('Uncaught error outside test suite'); + debug('uncaught(): no current Runnable; created a phony one'); + runnable.parent = this.suite; + + if (this.state === constants$1.STATE_RUNNING) { + debug('uncaught(): failing gracefully'); + this.fail(runnable, err); + } else { + // Can't recover from this failure + debug('uncaught(): test run has not yet started; unrecoverable'); + this.emit(constants$1.EVENT_RUN_BEGIN); + this.fail(runnable, err); + this.emit(constants$1.EVENT_RUN_END); + } + + return; + } + + runnable.clearTimeout(); + + if (runnable.isFailed()) { + debug('uncaught(): Runnable has already failed'); + // Ignore error if already failed + return; + } else if (runnable.isPending()) { + debug('uncaught(): pending Runnable wound up failing!'); + // report 'pending test' retrospectively as failed + this.fail(runnable, err, true); + return; + } + + // we cannot recover gracefully if a Runnable has already passed + // then fails asynchronously + if (runnable.isPassed()) { + debug('uncaught(): Runnable has already passed; bailing gracefully'); + this.fail(runnable, err); + this.abort(); + } else { + debug('uncaught(): forcing Runnable to complete with Error'); + return runnable.callback(err); + } + }; + + /** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @public + * @memberof Runner + * @param {Function} fn - Callback when finished + * @param {Object} [opts] - For subclasses + * @param {string[]} opts.files - Files to run + * @param {Options} opts.options - command-line options + * @returns {Runner} Runner instance. + */ + Runner.prototype.run = function (fn, opts = {}) { + var rootSuite = this.suite; + var options = opts.options || {}; + + debug('run(): got options: %O', options); + fn = fn || function () {}; + + const end = () => { + if (!this.total && this._opts.failZero) this.failures = 1; + + debug('run(): root suite completed; emitting %s', constants$1.EVENT_RUN_END); + this.emit(constants$1.EVENT_RUN_END); + }; + + const begin = () => { + debug('run(): emitting %s', constants$1.EVENT_RUN_BEGIN); + this.emit(constants$1.EVENT_RUN_BEGIN); + debug('run(): emitted %s', constants$1.EVENT_RUN_BEGIN); + + this.runSuite(rootSuite, end); + }; + + const prepare = () => { + debug('run(): starting'); + // If there is an `only` filter + if (rootSuite.hasOnly()) { + rootSuite.filterOnly(); + debug('run(): filtered exclusive Runnables'); + } + this.state = constants$1.STATE_RUNNING; + if (this._opts.delay) { + this.emit(constants$1.EVENT_DELAY_END); + debug('run(): "delay" ended'); + } + + return begin(); + }; + + // references cleanup to avoid memory leaks + if (this._opts.cleanReferencesAfterRun) { + this.on(constants$1.EVENT_SUITE_END, suite => { + suite.cleanReferences(); + }); + } + + // callback + this.on(constants$1.EVENT_RUN_END, function () { + this.state = constants$1.STATE_STOPPED; + debug('run(): emitted %s', constants$1.EVENT_RUN_END); + fn(this.failures); + }); + + this._removeEventListener(process, 'uncaughtException', this.uncaught); + this._removeEventListener(process, 'unhandledRejection', this.unhandled); + this._addEventListener(process, 'uncaughtException', this.uncaught); + this._addEventListener(process, 'unhandledRejection', this.unhandled); + + if (this._opts.delay) { + // for reporters, I guess. + // might be nice to debounce some dots while we wait. + this.emit(constants$1.EVENT_DELAY_BEGIN, rootSuite); + rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare); + debug('run(): waiting for green light due to --delay'); + } else { + Runner.immediately(prepare); + } + + return this; + }; + + /** + * Toggle partial object linking behavior; used for building object references from + * unique ID's. Does nothing in serial mode, because the object references already exist. + * Subclasses can implement this (e.g., `ParallelBufferedRunner`) + * @abstract + * @param {boolean} [value] - If `true`, enable partial object linking, otherwise disable + * @returns {Runner} + * @chainable + * @public + * @example + * // this reporter needs proper object references when run in parallel mode + * class MyReporter() { + * constructor(runner) { + * this.runner.linkPartialObjects(true) + * .on(EVENT_SUITE_BEGIN, suite => { + // this Suite may be the same object... + * }) + * .on(EVENT_TEST_BEGIN, test => { + * // ...as the `test.parent` property + * }); + * } + * } + */ + Runner.prototype.linkPartialObjects = function (value) { + return this; + }; + + /* + * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`. + * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead. + * @public + * @memberof Runner + * @param {Object} [opts] - Options for {@link Runner#run} + * @returns {Promise} Failure count + */ + Runner.prototype.runAsync = async function runAsync(opts = {}) { + return new Promise(resolve => { + this.run(resolve, opts); + }); + }; + + /** + * Cleanly abort execution. + * + * @memberof Runner + * @public + * @return {Runner} Runner instance. + */ + Runner.prototype.abort = function () { + debug('abort(): aborting'); + this._abort = true; + + return this; + }; + + /** + * Returns `true` if Mocha is running in parallel mode. For reporters. + * + * Subclasses should return an appropriate value. + * @public + * @returns {false} + */ + Runner.prototype.isParallelMode = function isParallelMode() { + return false; + }; + + /** + * Configures an alternate reporter for worker processes to use. Subclasses + * using worker processes should implement this. + * @public + * @param {string} path - Absolute path to alternate reporter for worker processes to use + * @returns {Runner} + * @throws When in serial mode + * @chainable + * @abstract + */ + Runner.prototype.workerReporter = function () { + throw createUnsupportedError$1('workerReporter() not supported in serial mode'); + }; + + /** + * Filter leaks with the given globals flagged as `ok`. + * + * @private + * @param {Array} ok + * @param {Array} globals + * @return {Array} + */ + function filterLeaks(ok, globals) { + return globals.filter(function (key) { + // Firefox and Chrome exposes iframes as index inside the window object + if (/^\d+/.test(key)) { + return false; + } + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method + // not init at first it is assigned in some seconds + if (commonjsGlobal.navigator && /^getInterface/.test(key)) { + return false; + } + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (commonjsGlobal.navigator && /^\d+/.test(key)) { + return false; + } + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) { + return false; + } + + var matched = ok.filter(function (ok) { + if (~ok.indexOf('*')) { + return key.indexOf(ok.split('*')[0]) === 0; + } + return key === ok; + }); + return !matched.length && (!commonjsGlobal.navigator || key !== 'onerror'); + }); + } + + /** + * Check if argument is an instance of Error object or a duck-typed equivalent. + * + * @private + * @param {Object} err - object to check + * @param {string} err.message - error message + * @returns {boolean} + */ + function isError(err) { + return err instanceof Error || (err && typeof err.message === 'string'); + } + + /** + * + * Converts thrown non-extensible type into proper Error. + * + * @private + * @param {*} thrown - Non-extensible type thrown by code + * @return {Error} + */ + function thrown2Error(err) { + return new Error( + `the ${utils$1.canonicalType(err)} ${stringify( + err + )} was thrown, throw an Error :)` + ); + } + + Runner.constants = constants$1; + + /** + * Node.js' `EventEmitter` + * @external EventEmitter + * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter} + */ + + var runner = Runner; + + (function (module, exports) { + /** + * @module Base + */ + /** + * Module dependencies. + */ + + var diff = lib; + var milliseconds = ms$1; + var utils = utils$3; + var supportsColor = require$$18; + var symbols = browser$1; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + + const isBrowser = utils.isBrowser(); + + function getBrowserWindowSize() { + if ('innerHeight' in commonjsGlobal) { + return [commonjsGlobal.innerHeight, commonjsGlobal.innerWidth]; + } + // In a Web Worker, the DOM Window is not available. + return [640, 480]; + } + + /** + * Expose `Base`. + */ + + exports = module.exports = Base; + + /** + * Check if both stdio streams are associated with a tty. + */ + + var isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY); + + /** + * Save log references to avoid tests interfering (see GH-3604). + */ + var consoleLog = console.log; + + /** + * Enable coloring by default, except in the browser interface. + */ + + exports.useColors = + !isBrowser && + (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined); + + /** + * Inline diffs instead of +/- + */ + + exports.inlineDiffs = false; + + /** + * Truncate diffs longer than this value to avoid slow performance + */ + exports.maxDiffSize = 8192; + + /** + * Default color map. + */ + + exports.colors = { + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 32, + 'diff removed': 31, + 'diff added inline': '30;42', + 'diff removed inline': '30;41' + }; + + /** + * Default symbol map. + */ + + exports.symbols = { + ok: symbols.success, + err: symbols.error, + dot: '.', + comma: ',', + bang: '!' + }; + + /** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @private + * @param {string} type + * @param {string} str + * @return {string} + */ + var color = (exports.color = function (type, str) { + if (!exports.useColors) { + return String(str); + } + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; + }); + + /** + * Expose term window size, with some defaults for when stderr is not a tty. + */ + + exports.window = { + width: 75 + }; + + if (isatty) { + if (isBrowser) { + exports.window.width = getBrowserWindowSize()[1]; + } else { + exports.window.width = process.stdout.getWindowSize(1)[0]; + } + } + + /** + * Expose some basic cursor interactions that are common among reporters. + */ + + exports.cursor = { + hide: function () { + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function () { + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function () { + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function () { + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function () { + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } + }; + + var showDiff = (exports.showDiff = function (err) { + return ( + err && + err.showDiff !== false && + sameType(err.actual, err.expected) && + err.expected !== undefined + ); + }); + + function stringifyDiffObjs(err) { + if (!utils.isString(err.actual) || !utils.isString(err.expected)) { + err.actual = utils.stringify(err.actual); + err.expected = utils.stringify(err.expected); + } + } + + /** + * Returns a diff between 2 strings with coloured ANSI output. + * + * @description + * The diff will be either inline or unified dependent on the value + * of `Base.inlineDiff`. + * + * @param {string} actual + * @param {string} expected + * @return {string} Diff + */ + + var generateDiff = (exports.generateDiff = function (actual, expected) { + try { + var maxLen = exports.maxDiffSize; + var skipped = 0; + if (maxLen > 0) { + skipped = Math.max(actual.length - maxLen, expected.length - maxLen); + actual = actual.slice(0, maxLen); + expected = expected.slice(0, maxLen); + } + let result = exports.inlineDiffs + ? inlineDiff(actual, expected) + : unifiedDiff(actual, expected); + if (skipped > 0) { + result = `${result}\n [mocha] output truncated to ${maxLen} characters, see "maxDiffSize" reporter-option\n`; + } + return result; + } catch (err) { + var msg = + '\n ' + + color('diff added', '+ expected') + + ' ' + + color('diff removed', '- actual: failed to generate Mocha diff') + + '\n'; + return msg; + } + }); + + /** + * Traverses err.cause and returns all stack traces + * + * @private + * @param {Error} err + * @param {Set} [seen] + * @return {FullErrorStack} + */ + var getFullErrorStack = function (err, seen) { + if (seen && seen.has(err)) { + return { message: '', msg: '', stack: '' }; + } + + var message; + + if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else { + message = ''; + } + + var msg; + var stack = err.stack || message; + var index = message ? stack.indexOf(message) : -1; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + + if (err.cause) { + seen = seen || new Set(); + seen.add(err); + const causeStack = getFullErrorStack(err.cause, seen); + stack += '\n Caused by: ' + causeStack.msg + (causeStack.stack ? '\n' + causeStack.stack : ''); + } + } + + return { + message, + msg, + stack + }; + }; + + /** + * Outputs the given `failures` as a list. + * + * @public + * @memberof Mocha.reporters.Base + * @variation 1 + * @param {Object[]} failures - Each is Test instance with corresponding + * Error property + */ + exports.list = function (failures) { + var multipleErr, multipleTest; + Base.consoleLog(); + failures.forEach(function (test, i) { + // format + var fmt = + color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var err; + if (test.err && test.err.multiple) { + if (multipleTest !== test) { + multipleTest = test; + multipleErr = [test.err].concat(test.err.multiple); + } + err = multipleErr.shift(); + } else { + err = test.err; + } + + var { message, msg, stack } = getFullErrorStack(err); + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + // explicitly show diff + if (!exports.hideDiff && showDiff(err)) { + stringifyDiffObjs(err); + fmt = + color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + msg += generateDiff(err.actual, err.expected); + } + + // indent stack trace + stack = stack.replace(/^/gm, ' '); + + // indented test title + var testTitle = ''; + test.titlePath().forEach(function (str, index) { + if (index !== 0) { + testTitle += '\n '; + } + for (var i = 0; i < index; i++) { + testTitle += ' '; + } + testTitle += str; + }); + + Base.consoleLog(fmt, i + 1, testTitle, msg, stack); + }); + }; + + /** + * Constructs a new `Base` reporter instance. + * + * @description + * All other reporters generally inherit from this reporter. + * + * @public + * @class + * @memberof Mocha.reporters + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Base(runner, options) { + var failures = (this.failures = []); + + if (!runner) { + throw new TypeError('Missing runner argument'); + } + this.options = options || {}; + this.runner = runner; + this.stats = runner.stats; // assigned so Reporters keep a closer reference + + var maxDiffSizeOpt = + this.options.reporterOption && this.options.reporterOption.maxDiffSize; + if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) { + exports.maxDiffSize = Number(maxDiffSizeOpt); + } + + runner.on(EVENT_TEST_PASS, function (test) { + if (test.duration > test.slow()) { + test.speed = 'slow'; + } else if (test.duration > test.slow() / 2) { + test.speed = 'medium'; + } else { + test.speed = 'fast'; + } + }); + + runner.on(EVENT_TEST_FAIL, function (test, err) { + if (showDiff(err)) { + stringifyDiffObjs(err); + } + // more than one error per test + if (test.err && err instanceof Error) { + test.err.multiple = (test.err.multiple || []).concat(err); + } else { + test.err = err; + } + failures.push(test); + }); + } + + /** + * Outputs common epilogue used by many of the bundled reporters. + * + * @public + * @memberof Mocha.reporters + */ + Base.prototype.epilogue = function () { + var stats = this.stats; + var fmt; + + Base.consoleLog(); + + // passes + fmt = + color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + Base.consoleLog(fmt, stats.passes || 0, milliseconds(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + color('pending', ' %d pending'); + + Base.consoleLog(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + Base.consoleLog(fmt, stats.failures); + + Base.list(this.failures); + Base.consoleLog(); + } + + Base.consoleLog(); + }; + + /** + * Pads the given `str` to `len`. + * + * @private + * @param {string} str + * @param {string} len + * @return {string} + */ + function pad(str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; + } + + /** + * Returns inline diff between 2 strings with coloured ANSI output. + * + * @private + * @param {String} actual + * @param {String} expected + * @return {string} Diff + */ + function inlineDiff(actual, expected) { + var msg = errorDiff(actual, expected); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines + .map(function (str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }) + .join('\n'); + } + + // legend + msg = + '\n' + + color('diff removed inline', 'actual') + + ' ' + + color('diff added inline', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; + } + + /** + * Returns unified diff between two strings with coloured ANSI output. + * + * @private + * @param {String} actual + * @param {String} expected + * @return {string} The diff. + */ + function unifiedDiff(actual, expected) { + var indent = ' '; + function cleanUp(line) { + if (line[0] === '+') { + return indent + colorLines('diff added', line); + } + if (line[0] === '-') { + return indent + colorLines('diff removed', line); + } + if (line.match(/@@/)) { + return '--'; + } + if (line.match(/\\ No newline/)) { + return null; + } + return indent + line; + } + function notBlank(line) { + return typeof line !== 'undefined' && line !== null; + } + var msg = diff.createPatch('string', actual, expected); + var lines = msg.split('\n').splice(5); + return ( + '\n ' + + colorLines('diff added', '+ expected') + + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n') + ); + } + + /** + * Returns character diff for `err`. + * + * @private + * @param {String} actual + * @param {String} expected + * @return {string} the diff + */ + function errorDiff(actual, expected) { + return diff + .diffWordsWithSpace(actual, expected) + .map(function (str) { + if (str.added) { + return colorLines('diff added inline', str.value); + } + if (str.removed) { + return colorLines('diff removed inline', str.value); + } + return str.value; + }) + .join(''); + } + + /** + * Colors lines for `str`, using the color `name`. + * + * @private + * @param {string} name + * @param {string} str + * @return {string} + */ + function colorLines(name, str) { + return str + .split('\n') + .map(function (str) { + return color(name, str); + }) + .join('\n'); + } + + /** + * Object#toString reference. + */ + var objToString = Object.prototype.toString; + + /** + * Checks that a / b have the same type. + * + * @private + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ + function sameType(a, b) { + return objToString.call(a) === objToString.call(b); + } + + Base.consoleLog = consoleLog; + + Base.abstract = true; + + /** + * An object with all stack traces recursively mounted from each err.cause + * @memberof module:lib/reporters/base + * @typedef {Object} FullErrorStack + * @property {string} message + * @property {string} msg + * @property {string} stack + */ + }(base$1, base$1.exports)); + + var dot = {exports: {}}; + + (function (module, exports) { + /** + * @module Dot + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var inherits = utils$3.inherits; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var EVENT_RUN_END = constants.EVENT_RUN_END; + + /** + * Expose `Dot`. + */ + + module.exports = Dot; + + /** + * Constructs a new `Dot` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Dot(runner, options) { + Base.call(this, runner, options); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var n = -1; + + runner.on(EVENT_RUN_BEGIN, function () { + process.stdout.write('\n'); + }); + + runner.on(EVENT_TEST_PENDING, function () { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(Base.color('pending', Base.symbols.comma)); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + if (++n % width === 0) { + process.stdout.write('\n '); + } + if (test.speed === 'slow') { + process.stdout.write(Base.color('bright yellow', Base.symbols.dot)); + } else { + process.stdout.write(Base.color(test.speed, Base.symbols.dot)); + } + }); + + runner.on(EVENT_TEST_FAIL, function () { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(Base.color('fail', Base.symbols.bang)); + }); + + runner.once(EVENT_RUN_END, function () { + process.stdout.write('\n'); + self.epilogue(); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(Dot, Base); + + Dot.description = 'dot matrix representation'; + }(dot)); + + var doc = {exports: {}}; + + (function (module, exports) { + /** + * @module Doc + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var utils = utils$3; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; + var EVENT_SUITE_END = constants.EVENT_SUITE_END; + + /** + * Expose `Doc`. + */ + + module.exports = Doc; + + /** + * Constructs a new `Doc` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Doc(runner, options) { + Base.call(this, runner, options); + + var indents = 2; + + function indent() { + return Array(indents).join(' '); + } + + runner.on(EVENT_SUITE_BEGIN, function (suite) { + if (suite.root) { + return; + } + ++indents; + Base.consoleLog('%s
      ', indent()); + ++indents; + Base.consoleLog('%s

      %s

      ', indent(), utils.escape(suite.title)); + Base.consoleLog('%s
      ', indent()); + }); + + runner.on(EVENT_SUITE_END, function (suite) { + if (suite.root) { + return; + } + Base.consoleLog('%s
      ', indent()); + --indents; + Base.consoleLog('%s
      ', indent()); + --indents; + }); + + runner.on(EVENT_TEST_PASS, function (test) { + Base.consoleLog('%s
      %s
      ', indent(), utils.escape(test.title)); + Base.consoleLog('%s
      %s
      ', indent(), utils.escape(test.file)); + var code = utils.escape(utils.clean(test.body)); + Base.consoleLog('%s
      %s
      ', indent(), code); + }); + + runner.on(EVENT_TEST_FAIL, function (test, err) { + Base.consoleLog( + '%s
      %s
      ', + indent(), + utils.escape(test.title) + ); + Base.consoleLog( + '%s
      %s
      ', + indent(), + utils.escape(test.file) + ); + var code = utils.escape(utils.clean(test.body)); + Base.consoleLog( + '%s
      %s
      ', + indent(), + code + ); + Base.consoleLog( + '%s
      %s
      ', + indent(), + utils.escape(err) + ); + }); + } + + Doc.description = 'HTML documentation'; + }(doc)); + + var tap = {exports: {}}; + + (function (module, exports) { + /** + * @module TAP + */ + /** + * Module dependencies. + */ + + var util = require$$0$1; + var Base = base$1.exports; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var EVENT_TEST_END = constants.EVENT_TEST_END; + var inherits = utils$3.inherits; + var sprintf = util.format; + + /** + * Expose `TAP`. + */ + + module.exports = TAP; + + /** + * Constructs a new `TAP` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function TAP(runner, options) { + Base.call(this, runner, options); + + var self = this; + var n = 1; + + var tapVersion = '12'; + if (options && options.reporterOptions) { + if (options.reporterOptions.tapVersion) { + tapVersion = options.reporterOptions.tapVersion.toString(); + } + } + + this._producer = createProducer(tapVersion); + + runner.once(EVENT_RUN_BEGIN, function () { + self._producer.writeVersion(); + }); + + runner.on(EVENT_TEST_END, function () { + ++n; + }); + + runner.on(EVENT_TEST_PENDING, function (test) { + self._producer.writePending(n, test); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + self._producer.writePass(n, test); + }); + + runner.on(EVENT_TEST_FAIL, function (test, err) { + self._producer.writeFail(n, test, err); + }); + + runner.once(EVENT_RUN_END, function () { + self._producer.writeEpilogue(runner.stats); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(TAP, Base); + + /** + * Returns a TAP-safe title of `test`. + * + * @private + * @param {Test} test - Test instance. + * @return {String} title with any hash character removed + */ + function title(test) { + return test.fullTitle().replace(/#/g, ''); + } + + /** + * Writes newline-terminated formatted string to reporter output stream. + * + * @private + * @param {string} format - `printf`-like format string + * @param {...*} [varArgs] - Format string arguments + */ + function println(format, varArgs) { + var vargs = Array.from(arguments); + vargs[0] += '\n'; + process.stdout.write(sprintf.apply(null, vargs)); + } + + /** + * Returns a `tapVersion`-appropriate TAP producer instance, if possible. + * + * @private + * @param {string} tapVersion - Version of TAP specification to produce. + * @returns {TAPProducer} specification-appropriate instance + * @throws {Error} if specification version has no associated producer. + */ + function createProducer(tapVersion) { + var producers = { + 12: new TAP12Producer(), + 13: new TAP13Producer() + }; + var producer = producers[tapVersion]; + + if (!producer) { + throw new Error( + 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion) + ); + } + + return producer; + } + + /** + * @summary + * Constructs a new TAPProducer. + * + * @description + * Only to be used as an abstract base class. + * + * @private + * @constructor + */ + function TAPProducer() {} + + /** + * Writes the TAP version to reporter output stream. + * + * @abstract + */ + TAPProducer.prototype.writeVersion = function () {}; + + /** + * Writes the plan to reporter output stream. + * + * @abstract + * @param {number} ntests - Number of tests that are planned to run. + */ + TAPProducer.prototype.writePlan = function (ntests) { + println('%d..%d', 1, ntests); + }; + + /** + * Writes that test passed to reporter output stream. + * + * @abstract + * @param {number} n - Index of test that passed. + * @param {Test} test - Instance containing test information. + */ + TAPProducer.prototype.writePass = function (n, test) { + println('ok %d %s', n, title(test)); + }; + + /** + * Writes that test was skipped to reporter output stream. + * + * @abstract + * @param {number} n - Index of test that was skipped. + * @param {Test} test - Instance containing test information. + */ + TAPProducer.prototype.writePending = function (n, test) { + println('ok %d %s # SKIP -', n, title(test)); + }; + + /** + * Writes that test failed to reporter output stream. + * + * @abstract + * @param {number} n - Index of test that failed. + * @param {Test} test - Instance containing test information. + * @param {Error} err - Reason the test failed. + */ + TAPProducer.prototype.writeFail = function (n, test, err) { + println('not ok %d %s', n, title(test)); + }; + + /** + * Writes the summary epilogue to reporter output stream. + * + * @abstract + * @param {Object} stats - Object containing run statistics. + */ + TAPProducer.prototype.writeEpilogue = function (stats) { + // :TBD: Why is this not counting pending tests? + println('# tests ' + (stats.passes + stats.failures)); + println('# pass ' + stats.passes); + // :TBD: Why are we not showing pending results? + println('# fail ' + stats.failures); + this.writePlan(stats.passes + stats.failures + stats.pending); + }; + + /** + * @summary + * Constructs a new TAP12Producer. + * + * @description + * Produces output conforming to the TAP12 specification. + * + * @private + * @constructor + * @extends TAPProducer + * @see {@link https://testanything.org/tap-specification.html|Specification} + */ + function TAP12Producer() { + /** + * Writes that test failed to reporter output stream, with error formatting. + * @override + */ + this.writeFail = function (n, test, err) { + TAPProducer.prototype.writeFail.call(this, n, test, err); + if (err.message) { + println(err.message.replace(/^/gm, ' ')); + } + if (err.stack) { + println(err.stack.replace(/^/gm, ' ')); + } + }; + } + + /** + * Inherit from `TAPProducer.prototype`. + */ + inherits(TAP12Producer, TAPProducer); + + /** + * @summary + * Constructs a new TAP13Producer. + * + * @description + * Produces output conforming to the TAP13 specification. + * + * @private + * @constructor + * @extends TAPProducer + * @see {@link https://testanything.org/tap-version-13-specification.html|Specification} + */ + function TAP13Producer() { + /** + * Writes the TAP version to reporter output stream. + * @override + */ + this.writeVersion = function () { + println('TAP version 13'); + }; + + /** + * Writes that test failed to reporter output stream, with error formatting. + * @override + */ + this.writeFail = function (n, test, err) { + TAPProducer.prototype.writeFail.call(this, n, test, err); + var emitYamlBlock = err.message != null || err.stack != null; + if (emitYamlBlock) { + println(indent(1) + '---'); + if (err.message) { + println(indent(2) + 'message: |-'); + println(err.message.replace(/^/gm, indent(3))); + } + if (err.stack) { + println(indent(2) + 'stack: |-'); + println(err.stack.replace(/^/gm, indent(3))); + } + println(indent(1) + '...'); + } + }; + + function indent(level) { + return Array(level + 1).join(' '); + } + } + + /** + * Inherit from `TAPProducer.prototype`. + */ + inherits(TAP13Producer, TAPProducer); + + TAP.description = 'TAP-compatible output'; + }(tap)); + + var json = {exports: {}}; + + var _polyfillNode_fs = {}; + + var _polyfillNode_fs$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + 'default': _polyfillNode_fs + }); + + var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_fs$1); + + (function (module, exports) { + /** + * @module JSON + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var fs = require$$2; + var path = require$$1; + const createUnsupportedError = errors$2.createUnsupportedError; + const utils = utils$3; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_TEST_END = constants.EVENT_TEST_END; + var EVENT_RUN_END = constants.EVENT_RUN_END; + + /** + * Expose `JSON`. + */ + + module.exports = JSONReporter; + + /** + * Constructs a new `JSON` reporter instance. + * + * @public + * @class JSON + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function JSONReporter(runner, options = {}) { + Base.call(this, runner, options); + + var self = this; + var tests = []; + var pending = []; + var failures = []; + var passes = []; + var output; + + if (options.reporterOption && options.reporterOption.output) { + if (utils.isBrowser()) { + throw createUnsupportedError('file output not supported in browser'); + } + output = options.reporterOption.output; + } + + runner.on(EVENT_TEST_END, function (test) { + tests.push(test); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + passes.push(test); + }); + + runner.on(EVENT_TEST_FAIL, function (test) { + failures.push(test); + }); + + runner.on(EVENT_TEST_PENDING, function (test) { + pending.push(test); + }); + + runner.once(EVENT_RUN_END, function () { + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; + + var json = JSON.stringify(obj, null, 2); + if (output) { + try { + fs.mkdirSync(path.dirname(output), {recursive: true}); + fs.writeFileSync(output, json); + } catch (err) { + console.error( + `${Base.symbols.err} [mocha] writing output to "${output}" failed: ${err.message}\n` + ); + process.stdout.write(json); + } + } else { + process.stdout.write(json); + } + }); + } + + /** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @private + * @param {Object} test + * @return {Object} + */ + function clean(test) { + var err = test.err || {}; + if (err instanceof Error) { + err = errorJSON(err); + } + + return { + title: test.title, + fullTitle: test.fullTitle(), + file: test.file, + duration: test.duration, + currentRetry: test.currentRetry(), + speed: test.speed, + err: cleanCycles(err) + }; + } + + /** + * Replaces any circular references inside `obj` with '[object Object]' + * + * @private + * @param {Object} obj + * @return {Object} + */ + function cleanCycles(obj) { + var cache = []; + return JSON.parse( + JSON.stringify(obj, function (key, value) { + if (typeof value === 'object' && value !== null) { + if (cache.indexOf(value) !== -1) { + // Instead of going in a circle, we'll print [object Object] + return '' + value; + } + cache.push(value); + } + + return value; + }) + ); + } + + /** + * Transform an Error object into a JSON object. + * + * @private + * @param {Error} err + * @return {Object} + */ + function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function (key) { + res[key] = err[key]; + }, err); + return res; + } + + JSONReporter.description = 'single JSON object'; + }(json)); + + var html = {exports: {}}; + + /** + @module browser/Progress + */ + + /** + * Expose `Progress`. + */ + + var progress$1 = Progress; + + /** + * Initialize a new `Progress` indicator. + */ + function Progress() { + this.percent = 0; + this.size(0); + this.fontSize(11); + this.font('helvetica, arial, sans-serif'); + } + + /** + * Set progress size to `size`. + * + * @public + * @param {number} size + * @return {Progress} Progress instance. + */ + Progress.prototype.size = function (size) { + this._size = size; + return this; + }; + + /** + * Set text to `text`. + * + * @public + * @param {string} text + * @return {Progress} Progress instance. + */ + Progress.prototype.text = function (text) { + this._text = text; + return this; + }; + + /** + * Set font size to `size`. + * + * @public + * @param {number} size + * @return {Progress} Progress instance. + */ + Progress.prototype.fontSize = function (size) { + this._fontSize = size; + return this; + }; + + /** + * Set font to `family`. + * + * @param {string} family + * @return {Progress} Progress instance. + */ + Progress.prototype.font = function (family) { + this._font = family; + return this; + }; + + /** + * Update percentage to `n`. + * + * @param {number} n + * @return {Progress} Progress instance. + */ + Progress.prototype.update = function (n) { + this.percent = n; + return this; + }; + + /** + * Draw on `ctx`. + * + * @param {CanvasRenderingContext2d} ctx + * @return {Progress} Progress instance. + */ + Progress.prototype.draw = function (ctx) { + try { + var darkMatcher = window.matchMedia('(prefers-color-scheme: dark)'); + var isDarkMode = !!darkMatcher.matches; + var lightColors = { + outerCircle: '#9f9f9f', + innerCircle: '#eee', + text: '#000' + }; + var darkColors = { + outerCircle: '#888', + innerCircle: '#444', + text: '#fff' + }; + var colors = isDarkMode ? darkColors : lightColors; + + var percent = Math.min(this.percent, 100); + var size = this._size; + var half = size / 2; + var x = half; + var y = half; + var rad = half - 1; + var fontSize = this._fontSize; + + ctx.font = fontSize + 'px ' + this._font; + + var angle = Math.PI * 2 * (percent / 100); + ctx.clearRect(0, 0, size, size); + + // outer circle + ctx.strokeStyle = colors.outerCircle; + ctx.beginPath(); + ctx.arc(x, y, rad, 0, angle, false); + ctx.stroke(); + + // inner circle + ctx.strokeStyle = colors.innerCircle; + ctx.beginPath(); + ctx.arc(x, y, rad - 1, 0, angle, true); + ctx.stroke(); + + // text + var text = this._text || (percent | 0) + '%'; + var w = ctx.measureText(text).width; + + ctx.fillStyle = colors.text; + ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1); + } catch (ignore) { + // don't fail if we can't render progress + } + return this; + }; + + (function (module, exports) { + + /* eslint-env browser */ + /** + * @module HTML + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var utils = utils$3; + var Progress = progress$1; + var escapeRe = escapeStringRegexp; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; + var EVENT_SUITE_END = constants.EVENT_SUITE_END; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var escape = utils.escape; + + /** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + + var Date = commonjsGlobal.Date; + + /** + * Expose `HTML`. + */ + + module.exports = HTML; + + /** + * Stats template. + */ + + var statsTemplate = + ''; + + var playIcon = '‣'; + + /** + * Constructs a new `HTML` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function HTML(runner, options) { + Base.call(this, runner, options); + + var self = this; + var stats = this.stats; + var stat = fragment(statsTemplate); + var items = stat.getElementsByTagName('li'); + var passes = items[1].getElementsByTagName('em')[0]; + var passesLink = items[1].getElementsByTagName('a')[0]; + var failures = items[2].getElementsByTagName('em')[0]; + var failuresLink = items[2].getElementsByTagName('a')[0]; + var duration = items[3].getElementsByTagName('em')[0]; + var canvas = stat.getElementsByTagName('canvas')[0]; + var report = fragment('
        '); + var stack = [report]; + var progress; + var ctx; + var root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; + ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); + progress = new Progress(); + } + + if (!root) { + return error('#mocha div missing, add it to your document'); + } + + // pass toggle + on(passesLink, 'click', function (evt) { + evt.preventDefault(); + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test pass'); + } + }); + + // failure toggle + on(failuresLink, 'click', function (evt) { + evt.preventDefault(); + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) { + hideSuitesWithout('test fail'); + } + }); + + root.appendChild(stat); + root.appendChild(report); + + if (progress) { + progress.size(40); + } + + runner.on(EVENT_SUITE_BEGIN, function (suite) { + if (suite.root) { + return; + } + + // suite + var url = self.suiteURL(suite); + var el = fragment( + '
      • %s

      • ', + url, + escape(suite.title) + ); + + // container + stack[0].appendChild(el); + stack.unshift(document.createElement('ul')); + el.appendChild(stack[0]); + }); + + runner.on(EVENT_SUITE_END, function (suite) { + if (suite.root) { + updateStats(); + return; + } + stack.shift(); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + var url = self.testURL(test); + var markup = + '
      • %e%ems ' + + '' + + playIcon + + '

      • '; + var el = fragment(markup, test.speed, test.title, test.duration, url); + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on(EVENT_TEST_FAIL, function (test) { + var el = fragment( + '
      • %e ' + + playIcon + + '

      • ', + test.title, + self.testURL(test) + ); + var stackString; // Note: Includes leading newline + var message = test.err.toString(); + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if (message === '[object Error]') { + message = test.err.message; + } + + if (test.err.stack) { + var indexOfMessage = test.err.stack.indexOf(test.err.message); + if (indexOfMessage === -1) { + stackString = test.err.stack; + } else { + stackString = test.err.stack.slice( + test.err.message.length + indexOfMessage + ); + } + } else if (test.err.sourceURL && test.err.line !== undefined) { + // Safari doesn't give you a stack. Let's at least provide a source line. + stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; + } + + stackString = stackString || ''; + + if (test.err.htmlMessage && stackString) { + el.appendChild( + fragment( + '
        %s\n
        %e
        ', + test.err.htmlMessage, + stackString + ) + ); + } else if (test.err.htmlMessage) { + el.appendChild( + fragment('
        %s
        ', test.err.htmlMessage) + ); + } else { + el.appendChild( + fragment('
        %e%e
        ', message, stackString) + ); + } + + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on(EVENT_TEST_PENDING, function (test) { + var el = fragment( + '
      • %e

      • ', + test.title + ); + appendToStack(el); + updateStats(); + }); + + function appendToStack(el) { + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) { + stack[0].appendChild(el); + } + } + + function updateStats() { + // TODO: add to stats + var percent = ((stats.tests / runner.total) * 100) | 0; + if (progress) { + progress.update(percent).draw(ctx); + } + + // update stats + var ms = new Date() - stats.start; + text(passes, stats.passes); + text(failures, stats.failures); + text(duration, (ms / 1000).toFixed(2)); + } + } + + /** + * Makes a URL, preserving querystring ("search") parameters. + * + * @param {string} s + * @return {string} A new URL. + */ + function makeUrl(s) { + var search = window.location.search; + + // Remove previous grep query parameter if present + if (search) { + search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); + } + + return ( + window.location.pathname + + (search ? search + '&' : '?') + + 'grep=' + + encodeURIComponent(escapeRe(s)) + ); + } + + /** + * Provide suite URL. + * + * @param {Object} [suite] + */ + HTML.prototype.suiteURL = function (suite) { + return makeUrl(suite.fullTitle()); + }; + + /** + * Provide test URL. + * + * @param {Object} [test] + */ + HTML.prototype.testURL = function (test) { + return makeUrl(test.fullTitle()); + }; + + /** + * Adds code toggle functionality for the provided test's list element. + * + * @param {HTMLLIElement} el + * @param {string} contents + */ + HTML.prototype.addCodeToggle = function (el, contents) { + var h2 = el.getElementsByTagName('h2')[0]; + + on(h2, 'click', function () { + pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; + }); + + var pre = fragment('
        %e
        ', utils.clean(contents)); + el.appendChild(pre); + pre.style.display = 'none'; + }; + + /** + * Display error `msg`. + * + * @param {string} msg + */ + function error(msg) { + document.body.appendChild(fragment('
        %s
        ', msg)); + } + + /** + * Return a DOM fragment from `html`. + * + * @param {string} html + */ + function fragment(html) { + var args = arguments; + var div = document.createElement('div'); + var i = 1; + + div.innerHTML = html.replace(/%([se])/g, function (_, type) { + switch (type) { + case 's': + return String(args[i++]); + case 'e': + return escape(args[i++]); + // no default + } + }); + + return div.firstChild; + } + + /** + * Check for suites that do not have elements + * with `classname`, and hide them. + * + * @param {text} classname + */ + function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (!els.length) { + suites[i].className += ' hidden'; + } + } + } + + /** + * Unhide .hidden suites. + */ + function unhide() { + var els = document.getElementsByClassName('suite hidden'); + while (els.length > 0) { + els[0].className = els[0].className.replace('suite hidden', 'suite'); + } + } + + /** + * Set an element's text contents. + * + * @param {HTMLElement} el + * @param {string} contents + */ + function text(el, contents) { + if (el.textContent) { + el.textContent = contents; + } else { + el.innerText = contents; + } + } + + /** + * Listen on `event` with callback `fn`. + */ + function on(el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false); + } else { + el.attachEvent('on' + event, fn); + } + } + + HTML.browserOnly = true; + }(html)); + + var list = {exports: {}}; + + (function (module, exports) { + /** + * @module List + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var inherits = utils$3.inherits; + var constants = runner.constants; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var color = Base.color; + var cursor = Base.cursor; + + /** + * Expose `List`. + */ + + module.exports = List; + + /** + * Constructs a new `List` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function List(runner, options) { + Base.call(this, runner, options); + + var self = this; + var n = 0; + + runner.on(EVENT_RUN_BEGIN, function () { + Base.consoleLog(); + }); + + runner.on(EVENT_TEST_BEGIN, function (test) { + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); + }); + + runner.on(EVENT_TEST_PENDING, function (test) { + var fmt = color('checkmark', ' -') + color('pending', ' %s'); + Base.consoleLog(fmt, test.fullTitle()); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + var fmt = + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s: ') + + color(test.speed, '%dms'); + cursor.CR(); + Base.consoleLog(fmt, test.fullTitle(), test.duration); + }); + + runner.on(EVENT_TEST_FAIL, function (test) { + cursor.CR(); + Base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle()); + }); + + runner.once(EVENT_RUN_END, self.epilogue.bind(self)); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(List, Base); + + List.description = 'like "spec" reporter but flat'; + }(list)); + + var min = {exports: {}}; + + (function (module, exports) { + /** + * @module Min + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var inherits = utils$3.inherits; + var constants = runner.constants; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + + /** + * Expose `Min`. + */ + + module.exports = Min; + + /** + * Constructs a new `Min` reporter instance. + * + * @description + * This minimal test reporter is best used with '--watch'. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Min(runner, options) { + Base.call(this, runner, options); + + runner.on(EVENT_RUN_BEGIN, function () { + // clear screen + process.stdout.write('\u001b[2J'); + // set cursor position + process.stdout.write('\u001b[1;3H'); + }); + + runner.once(EVENT_RUN_END, this.epilogue.bind(this)); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(Min, Base); + + Min.description = 'essentially just a summary'; + }(min)); + + var spec = {exports: {}}; + + (function (module, exports) { + /** + * @module Spec + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var constants = runner.constants; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; + var EVENT_SUITE_END = constants.EVENT_SUITE_END; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var inherits = utils$3.inherits; + var color = Base.color; + + /** + * Expose `Spec`. + */ + + module.exports = Spec; + + /** + * Constructs a new `Spec` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Spec(runner, options) { + Base.call(this, runner, options); + + var self = this; + var indents = 0; + var n = 0; + + function indent() { + return Array(indents).join(' '); + } + + runner.on(EVENT_RUN_BEGIN, function () { + Base.consoleLog(); + }); + + runner.on(EVENT_SUITE_BEGIN, function (suite) { + ++indents; + Base.consoleLog(color('suite', '%s%s'), indent(), suite.title); + }); + + runner.on(EVENT_SUITE_END, function () { + --indents; + if (indents === 1) { + Base.consoleLog(); + } + }); + + runner.on(EVENT_TEST_PENDING, function (test) { + var fmt = indent() + color('pending', ' - %s'); + Base.consoleLog(fmt, test.title); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + var fmt; + if (test.speed === 'fast') { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s'); + Base.consoleLog(fmt, test.title); + } else { + fmt = + indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s') + + color(test.speed, ' (%dms)'); + Base.consoleLog(fmt, test.title, test.duration); + } + }); + + runner.on(EVENT_TEST_FAIL, function (test) { + Base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title); + }); + + runner.once(EVENT_RUN_END, self.epilogue.bind(self)); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(Spec, Base); + + Spec.description = 'hierarchical & verbose [default]'; + }(spec)); + + var nyan = {exports: {}}; + + (function (module, exports) { + /** + * @module Nyan + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var constants = runner.constants; + var inherits = utils$3.inherits; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + + /** + * Expose `Dot`. + */ + + module.exports = NyanCat; + + /** + * Constructs a new `Nyan` reporter instance. + * + * @public + * @class Nyan + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function NyanCat(runner, options) { + Base.call(this, runner, options); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var nyanCatWidth = (this.nyanCatWidth = 11); + + this.colorIndex = 0; + this.numberOfLines = 4; + this.rainbowColors = self.generateColors(); + this.scoreboardWidth = 5; + this.tick = 0; + this.trajectories = [[], [], [], []]; + this.trajectoryWidthMax = width - nyanCatWidth; + + runner.on(EVENT_RUN_BEGIN, function () { + Base.cursor.hide(); + self.draw(); + }); + + runner.on(EVENT_TEST_PENDING, function () { + self.draw(); + }); + + runner.on(EVENT_TEST_PASS, function () { + self.draw(); + }); + + runner.on(EVENT_TEST_FAIL, function () { + self.draw(); + }); + + runner.once(EVENT_RUN_END, function () { + Base.cursor.show(); + for (var i = 0; i < self.numberOfLines; i++) { + process.stdout.write('\n'); + } + self.epilogue(); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(NyanCat, Base); + + /** + * Draw the nyan cat + * + * @private + */ + + NyanCat.prototype.draw = function () { + this.appendRainbow(); + this.drawScoreboard(); + this.drawRainbow(); + this.drawNyanCat(); + this.tick = !this.tick; + }; + + /** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @private + */ + + NyanCat.prototype.drawScoreboard = function () { + var stats = this.stats; + + function draw(type, n) { + process.stdout.write(' '); + process.stdout.write(Base.color(type, n)); + process.stdout.write('\n'); + } + + draw('green', stats.passes); + draw('fail', stats.failures); + draw('pending', stats.pending); + process.stdout.write('\n'); + + this.cursorUp(this.numberOfLines); + }; + + /** + * Append the rainbow. + * + * @private + */ + + NyanCat.prototype.appendRainbow = function () { + var segment = this.tick ? '_' : '-'; + var rainbowified = this.rainbowify(segment); + + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index]; + if (trajectory.length >= this.trajectoryWidthMax) { + trajectory.shift(); + } + trajectory.push(rainbowified); + } + }; + + /** + * Draw the rainbow. + * + * @private + */ + + NyanCat.prototype.drawRainbow = function () { + var self = this; + + this.trajectories.forEach(function (line) { + process.stdout.write('\u001b[' + self.scoreboardWidth + 'C'); + process.stdout.write(line.join('')); + process.stdout.write('\n'); + }); + + this.cursorUp(this.numberOfLines); + }; + + /** + * Draw the nyan cat + * + * @private + */ + NyanCat.prototype.drawNyanCat = function () { + var self = this; + var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var dist = '\u001b[' + startWidth + 'C'; + var padding = ''; + + process.stdout.write(dist); + process.stdout.write('_,------,'); + process.stdout.write('\n'); + + process.stdout.write(dist); + padding = self.tick ? ' ' : ' '; + process.stdout.write('_|' + padding + '/\\_/\\ '); + process.stdout.write('\n'); + + process.stdout.write(dist); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + process.stdout.write(tail + '|' + padding + this.face() + ' '); + process.stdout.write('\n'); + + process.stdout.write(dist); + padding = self.tick ? ' ' : ' '; + process.stdout.write(padding + '"" "" '); + process.stdout.write('\n'); + + this.cursorUp(this.numberOfLines); + }; + + /** + * Draw nyan cat face. + * + * @private + * @return {string} + */ + + NyanCat.prototype.face = function () { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if (stats.passes) { + return '( ^ .^)'; + } + return '( - .-)'; + }; + + /** + * Move cursor up `n`. + * + * @private + * @param {number} n + */ + + NyanCat.prototype.cursorUp = function (n) { + process.stdout.write('\u001b[' + n + 'A'); + }; + + /** + * Move cursor down `n`. + * + * @private + * @param {number} n + */ + + NyanCat.prototype.cursorDown = function (n) { + process.stdout.write('\u001b[' + n + 'B'); + }; + + /** + * Generate rainbow colors. + * + * @private + * @return {Array} + */ + NyanCat.prototype.generateColors = function () { + var colors = []; + + for (var i = 0; i < 6 * 7; i++) { + var pi3 = Math.floor(Math.PI / 3); + var n = i * (1.0 / 6); + var r = Math.floor(3 * Math.sin(n) + 3); + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); + colors.push(36 * r + 6 * g + b + 16); + } + + return colors; + }; + + /** + * Apply rainbow to the given `str`. + * + * @private + * @param {string} str + * @return {string} + */ + NyanCat.prototype.rainbowify = function (str) { + if (!Base.useColors) { + return str; + } + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; + this.colorIndex += 1; + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; + }; + + NyanCat.description = '"nyan cat"'; + }(nyan)); + + var xunit = {exports: {}}; + + (function (module, exports) { + /** + * @module XUnit + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var utils = utils$3; + var fs = require$$2; + var path = require$$1; + var errors = errors$2; + var createUnsupportedError = errors.createUnsupportedError; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var STATE_FAILED = runnable.constants.STATE_FAILED; + var inherits = utils.inherits; + var escape = utils.escape; + + /** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + var Date = commonjsGlobal.Date; + + /** + * Expose `XUnit`. + */ + + module.exports = XUnit; + + /** + * Constructs a new `XUnit` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function XUnit(runner, options) { + Base.call(this, runner, options); + + var stats = this.stats; + var tests = []; + var self = this; + + // the name of the test suite, as it will appear in the resulting XML file + var suiteName; + + // the default name of the test suite if none is provided + var DEFAULT_SUITE_NAME = 'Mocha Tests'; + + if (options && options.reporterOptions) { + if (options.reporterOptions.output) { + if (!fs.createWriteStream) { + throw createUnsupportedError('file output not supported in browser'); + } + + fs.mkdirSync(path.dirname(options.reporterOptions.output), { + recursive: true + }); + self.fileStream = fs.createWriteStream(options.reporterOptions.output); + } + + // get the suite name from the reporter options (if provided) + suiteName = options.reporterOptions.suiteName; + } + + // fall back to the default suite name + suiteName = suiteName || DEFAULT_SUITE_NAME; + + runner.on(EVENT_TEST_PENDING, function (test) { + tests.push(test); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + tests.push(test); + }); + + runner.on(EVENT_TEST_FAIL, function (test) { + tests.push(test); + }); + + runner.once(EVENT_RUN_END, function () { + self.write( + tag( + 'testsuite', + { + name: suiteName, + tests: stats.tests, + failures: 0, + errors: stats.failures, + skipped: stats.tests - stats.failures - stats.passes, + timestamp: new Date().toUTCString(), + time: stats.duration / 1000 || 0 + }, + false + ) + ); + + tests.forEach(function (t) { + self.test(t); + }); + + self.write(''); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(XUnit, Base); + + /** + * Override done to close the stream (if it's a file). + * + * @param failures + * @param {Function} fn + */ + XUnit.prototype.done = function (failures, fn) { + if (this.fileStream) { + this.fileStream.end(function () { + fn(failures); + }); + } else { + fn(failures); + } + }; + + /** + * Write out the given line. + * + * @param {string} line + */ + XUnit.prototype.write = function (line) { + if (this.fileStream) { + this.fileStream.write(line + '\n'); + } else if (typeof process === 'object' && process.stdout) { + process.stdout.write(line + '\n'); + } else { + Base.consoleLog(line); + } + }; + + /** + * Output tag for the given `test.` + * + * @param {Test} test + */ + XUnit.prototype.test = function (test) { + Base.useColors = false; + + var attrs = { + classname: test.parent.fullTitle(), + name: test.title, + file: test.file, + time: test.duration / 1000 || 0 + }; + + if (test.state === STATE_FAILED) { + var err = test.err; + var diff = + !Base.hideDiff && Base.showDiff(err) + ? '\n' + Base.generateDiff(err.actual, err.expected) + : ''; + this.write( + tag( + 'testcase', + attrs, + false, + tag( + 'failure', + {}, + false, + escape(err.message) + escape(diff) + '\n' + escape(err.stack) + ) + ) + ); + } else if (test.isPending()) { + this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + this.write(tag('testcase', attrs, true)); + } + }; + + /** + * HTML tag helper. + * + * @param name + * @param attrs + * @param close + * @param content + * @return {string} + */ + function tag(name, attrs, close, content) { + var end = close ? '/>' : '>'; + var pairs = []; + var tag; + + for (var key in attrs) { + if (Object.prototype.hasOwnProperty.call(attrs, key)) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + } + + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) { + tag += content + '' + '\n'; + buf += title(suite.title) + '\n'; + }); + + runner.on(EVENT_SUITE_END, function () { + --level; + }); + + runner.on(EVENT_TEST_PASS, function (test) { + var code = utils.clean(test.body); + buf += test.title + '.\n'; + buf += '\n```js\n'; + buf += code + '\n'; + buf += '```\n\n'; + }); + + runner.once(EVENT_RUN_END, function () { + process.stdout.write('# TOC\n'); + process.stdout.write(generateTOC(runner.suite)); + process.stdout.write(buf); + }); + } + + Markdown.description = 'GitHub Flavored Markdown'; + }(markdown)); + + var progress = {exports: {}}; + + (function (module, exports) { + /** + * @module Progress + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var constants = runner.constants; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_TEST_END = constants.EVENT_TEST_END; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var inherits = utils$3.inherits; + var color = Base.color; + var cursor = Base.cursor; + + /** + * Expose `Progress`. + */ + + module.exports = Progress; + + /** + * General progress bar color. + */ + + Base.colors.progress = 90; + + /** + * Constructs a new `Progress` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Progress(runner, options) { + Base.call(this, runner, options); + + var self = this; + var width = (Base.window.width * 0.5) | 0; + var total = runner.total; + var complete = 0; + var lastN = -1; + + // default chars + options = options || {}; + var reporterOptions = options.reporterOptions || {}; + + options.open = reporterOptions.open || '['; + options.complete = reporterOptions.complete || '▬'; + options.incomplete = reporterOptions.incomplete || Base.symbols.dot; + options.close = reporterOptions.close || ']'; + options.verbose = reporterOptions.verbose || false; + + // tests started + runner.on(EVENT_RUN_BEGIN, function () { + process.stdout.write('\n'); + cursor.hide(); + }); + + // tests complete + runner.on(EVENT_TEST_END, function () { + complete++; + + var percent = complete / total; + var n = (width * percent) | 0; + var i = width - n; + + if (n === lastN && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + + cursor.CR(); + process.stdout.write('\u001b[J'); + process.stdout.write(color('progress', ' ' + options.open)); + process.stdout.write(Array(n).join(options.complete)); + process.stdout.write(Array(i).join(options.incomplete)); + process.stdout.write(color('progress', options.close)); + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); + } + }); + + // tests are complete, output some stats + // and the failures if any + runner.once(EVENT_RUN_END, function () { + cursor.show(); + process.stdout.write('\n'); + self.epilogue(); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(Progress, Base); + + Progress.description = 'a progress bar'; + }(progress)); + + var landing = {exports: {}}; + + (function (module, exports) { + /** + * @module Landing + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var inherits = utils$3.inherits; + var constants = runner.constants; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_END = constants.EVENT_TEST_END; + var STATE_FAILED = runnable.constants.STATE_FAILED; + + var cursor = Base.cursor; + var color = Base.color; + + /** + * Expose `Landing`. + */ + + module.exports = Landing; + + /** + * Airplane color. + */ + + Base.colors.plane = 0; + + /** + * Airplane crash color. + */ + + Base.colors['plane crash'] = 31; + + /** + * Runway color. + */ + + Base.colors.runway = 90; + + /** + * Constructs a new `Landing` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function Landing(runner, options) { + Base.call(this, runner, options); + + var self = this; + var width = (Base.window.width * 0.75) | 0; + var stream = process.stdout; + + var plane = color('plane', '✈'); + var crashed = -1; + var n = 0; + var total = 0; + + function runway() { + var buf = Array(width).join('-'); + return ' ' + color('runway', buf); + } + + runner.on(EVENT_RUN_BEGIN, function () { + stream.write('\n\n\n '); + cursor.hide(); + }); + + runner.on(EVENT_TEST_END, function (test) { + // check if the plane crashed + var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed; + // show the crash + if (test.state === STATE_FAILED) { + plane = color('plane crash', '✈'); + crashed = col; + } + + // render landing strip + stream.write('\u001b[' + (width + 1) + 'D\u001b[2A'); + stream.write(runway()); + stream.write('\n '); + stream.write(color('runway', Array(col).join('⋅'))); + stream.write(plane); + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); + stream.write(runway()); + stream.write('\u001b[0m'); + }); + + runner.once(EVENT_RUN_END, function () { + cursor.show(); + process.stdout.write('\n'); + self.epilogue(); + }); + + // if cursor is hidden when we ctrl-C, then it will remain hidden unless... + process.once('SIGINT', function () { + cursor.show(); + nextTick$1(function () { + process.kill(process.pid, 'SIGINT'); + }); + }); + } + + /** + * Inherit from `Base.prototype`. + */ + inherits(Landing, Base); + + Landing.description = 'Unicode landing strip'; + }(landing)); + + var jsonStream = {exports: {}}; + + (function (module, exports) { + /** + * @module JSONStream + */ + /** + * Module dependencies. + */ + + var Base = base$1.exports; + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_RUN_END = constants.EVENT_RUN_END; + + /** + * Expose `JSONStream`. + */ + + module.exports = JSONStream; + + /** + * Constructs a new `JSONStream` reporter instance. + * + * @public + * @class + * @memberof Mocha.reporters + * @extends Mocha.reporters.Base + * @param {Runner} runner - Instance triggers reporter actions. + * @param {Object} [options] - runner options + */ + function JSONStream(runner, options) { + Base.call(this, runner, options); + + var self = this; + var total = runner.total; + + runner.once(EVENT_RUN_BEGIN, function () { + writeEvent(['start', {total}]); + }); + + runner.on(EVENT_TEST_PASS, function (test) { + writeEvent(['pass', clean(test)]); + }); + + runner.on(EVENT_TEST_FAIL, function (test, err) { + test = clean(test); + test.err = err.message; + test.stack = err.stack || null; + writeEvent(['fail', test]); + }); + + runner.once(EVENT_RUN_END, function () { + writeEvent(['end', self.stats]); + }); + } + + /** + * Mocha event to be written to the output stream. + * @typedef {Array} JSONStream~MochaEvent + */ + + /** + * Writes Mocha event to reporter output stream. + * + * @private + * @param {JSONStream~MochaEvent} event - Mocha event to be output. + */ + function writeEvent(event) { + process.stdout.write(JSON.stringify(event) + '\n'); + } + + /** + * Returns an object literal representation of `test` + * free of cyclic properties, etc. + * + * @private + * @param {Test} test - Instance used as data source. + * @return {Object} object containing pared-down test instance data + */ + function clean(test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + file: test.file, + duration: test.duration, + currentRetry: test.currentRetry(), + speed: test.speed + }; + } + + JSONStream.description = 'newline delimited JSON events'; + }(jsonStream)); + + (function (exports) { + + // Alias exports to a their normalized format Mocha#reporter to prevent a need + // for dynamic (try/catch) requires, which Browserify doesn't handle. + exports.Base = exports.base = base$1.exports; + exports.Dot = exports.dot = dot.exports; + exports.Doc = exports.doc = doc.exports; + exports.TAP = exports.tap = tap.exports; + exports.JSON = exports.json = json.exports; + exports.HTML = exports.html = html.exports; + exports.List = exports.list = list.exports; + exports.Min = exports.min = min.exports; + exports.Spec = exports.spec = spec.exports; + exports.Nyan = exports.nyan = nyan.exports; + exports.XUnit = exports.xunit = xunit.exports; + exports.Markdown = exports.markdown = markdown.exports; + exports.Progress = exports.progress = progress.exports; + exports.Landing = exports.landing = landing.exports; + exports.JSONStream = exports['json-stream'] = jsonStream.exports; + }(reporters)); + + var diff = true; + var extension = [ + "js", + "cjs", + "mjs" + ]; + var reporter = "spec"; + var slow = 75; + var timeout = 2000; + var ui = "bdd"; + var require$$4 = { + diff: diff, + extension: extension, + "package": "./package.json", + reporter: reporter, + slow: slow, + timeout: timeout, + ui: ui, + "watch-ignore": [ + "node_modules", + ".git" + ] + }; + + /** + * Provides a factory function for a {@link StatsCollector} object. + * @module + */ + + var constants = runner.constants; + var EVENT_TEST_PASS = constants.EVENT_TEST_PASS; + var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL; + var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN; + var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN; + var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING; + var EVENT_RUN_END = constants.EVENT_RUN_END; + var EVENT_TEST_END = constants.EVENT_TEST_END; + + /** + * Test statistics collector. + * + * @public + * @typedef {Object} StatsCollector + * @property {number} suites - integer count of suites run. + * @property {number} tests - integer count of tests run. + * @property {number} passes - integer count of passing tests. + * @property {number} pending - integer count of pending tests. + * @property {number} failures - integer count of failed tests. + * @property {Date} start - time when testing began. + * @property {Date} end - time when testing concluded. + * @property {number} duration - number of msecs that testing took. + */ + + var Date$2 = commonjsGlobal.Date; + + /** + * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`. + * + * @private + * @param {Runner} runner - Runner instance + * @throws {TypeError} If falsy `runner` + */ + function createStatsCollector(runner) { + /** + * @type StatsCollector + */ + var stats = { + suites: 0, + tests: 0, + passes: 0, + pending: 0, + failures: 0 + }; + + if (!runner) { + throw new TypeError('Missing runner argument'); + } + + runner.stats = stats; + + runner.once(EVENT_RUN_BEGIN, function () { + stats.start = new Date$2(); + }); + runner.on(EVENT_SUITE_BEGIN, function (suite) { + suite.root || stats.suites++; + }); + runner.on(EVENT_TEST_PASS, function () { + stats.passes++; + }); + runner.on(EVENT_TEST_FAIL, function () { + stats.failures++; + }); + runner.on(EVENT_TEST_PENDING, function () { + stats.pending++; + }); + runner.on(EVENT_TEST_END, function () { + stats.tests++; + }); + runner.once(EVENT_RUN_END, function () { + stats.end = new Date$2(); + stats.duration = stats.end - stats.start; + }); + } + + var statsCollector = createStatsCollector; + + var interfaces = {}; + + var bdd = {exports: {}}; + + var Runnable = runnable; + var utils = utils$3; + var errors$1 = errors$2; + var createInvalidArgumentTypeError = errors$1.createInvalidArgumentTypeError; + var isString = utils.isString; + + const {MOCHA_ID_PROP_NAME} = utils.constants; + + var test = Test$4; + + /** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @public + * @class + * @extends Runnable + * @param {String} title - Test title (required) + * @param {Function} [fn] - Test callback. If omitted, the Test is considered "pending" + */ + function Test$4(title, fn) { + if (!isString(title)) { + throw createInvalidArgumentTypeError( + 'Test argument "title" should be a string. Received type "' + + typeof title + + '"', + 'title', + 'string' + ); + } + this.type = 'test'; + Runnable.call(this, title, fn); + this.reset(); + } + + /** + * Inherit from `Runnable.prototype`. + */ + utils.inherits(Test$4, Runnable); + + /** + * Resets the state initially or for a next run. + */ + Test$4.prototype.reset = function () { + Runnable.prototype.reset.call(this); + this.pending = !this.fn; + delete this.state; + }; + + /** + * Set or get retried test + * + * @private + */ + Test$4.prototype.retriedTest = function (n) { + if (!arguments.length) { + return this._retriedTest; + } + this._retriedTest = n; + }; + + /** + * Add test to the list of tests marked `only`. + * + * @private + */ + Test$4.prototype.markOnly = function () { + this.parent.appendOnlyTest(this); + }; + + Test$4.prototype.clone = function () { + var test = new Test$4(this.title, this.fn); + test.timeout(this.timeout()); + test.slow(this.slow()); + test.retries(this.retries()); + test.currentRetry(this.currentRetry()); + test.retriedTest(this.retriedTest() || this); + test.globals(this.globals()); + test.parent = this.parent; + test.file = this.file; + test.ctx = this.ctx; + return test; + }; + + /** + * Returns an minimal object suitable for transmission over IPC. + * Functions are represented by keys beginning with `$$`. + * @private + * @returns {Object} + */ + Test$4.prototype.serialize = function serialize() { + return { + $$currentRetry: this._currentRetry, + $$fullTitle: this.fullTitle(), + $$isPending: Boolean(this.pending), + $$retriedTest: this._retriedTest || null, + $$slow: this._slow, + $$titlePath: this.titlePath(), + body: this.body, + duration: this.duration, + err: this.err, + parent: { + $$fullTitle: this.parent.fullTitle(), + [MOCHA_ID_PROP_NAME]: this.parent.id + }, + speed: this.speed, + state: this.state, + title: this.title, + type: this.type, + file: this.file, + [MOCHA_ID_PROP_NAME]: this.id + }; + }; + + /** + @module interfaces/common + */ + + var Suite$1 = suite.exports; + var errors = errors$2; + var createMissingArgumentError = errors.createMissingArgumentError; + var createUnsupportedError = errors.createUnsupportedError; + var createForbiddenExclusivityError = errors.createForbiddenExclusivityError; + + /** + * Functions common to more than one interface. + * + * @private + * @param {Suite[]} suites + * @param {Context} context + * @param {Mocha} mocha + * @return {Object} An object containing common functions. + */ + var common = function (suites, context, mocha) { + /** + * Check if the suite should be tested. + * + * @private + * @param {Suite} suite - suite to check + * @returns {boolean} + */ + function shouldBeTested(suite) { + return ( + !mocha.options.grep || + (mocha.options.grep && + mocha.options.grep.test(suite.fullTitle()) && + !mocha.options.invert) + ); + } + + return { + /** + * This is only present if flag --delay is passed into Mocha. It triggers + * root suite execution. + * + * @param {Suite} suite The root suite. + * @return {Function} A function which runs the root suite + */ + runWithSuite: function runWithSuite(suite) { + return function run() { + suite.run(); + }; + }, + + /** + * Execute before running tests. + * + * @param {string} name + * @param {Function} fn + */ + before: function (name, fn) { + suites[0].beforeAll(name, fn); + }, + + /** + * Execute after running tests. + * + * @param {string} name + * @param {Function} fn + */ + after: function (name, fn) { + suites[0].afterAll(name, fn); + }, + + /** + * Execute before each test case. + * + * @param {string} name + * @param {Function} fn + */ + beforeEach: function (name, fn) { + suites[0].beforeEach(name, fn); + }, + + /** + * Execute after each test case. + * + * @param {string} name + * @param {Function} fn + */ + afterEach: function (name, fn) { + suites[0].afterEach(name, fn); + }, + + suite: { + /** + * Create an exclusive Suite; convenience function + * See docstring for create() below. + * + * @param {Object} opts + * @returns {Suite} + */ + only: function only(opts) { + if (mocha.options.forbidOnly) { + throw createForbiddenExclusivityError(mocha); + } + opts.isOnly = true; + return this.create(opts); + }, + + /** + * Create a Suite, but skip it; convenience function + * See docstring for create() below. + * + * @param {Object} opts + * @returns {Suite} + */ + skip: function skip(opts) { + opts.pending = true; + return this.create(opts); + }, + + /** + * Creates a suite. + * + * @param {Object} opts Options + * @param {string} opts.title Title of Suite + * @param {Function} [opts.fn] Suite Function (not always applicable) + * @param {boolean} [opts.pending] Is Suite pending? + * @param {string} [opts.file] Filepath where this Suite resides + * @param {boolean} [opts.isOnly] Is Suite exclusive? + * @returns {Suite} + */ + create: function create(opts) { + var suite = Suite$1.create(suites[0], opts.title); + suite.pending = Boolean(opts.pending); + suite.file = opts.file; + suites.unshift(suite); + if (opts.isOnly) { + suite.markOnly(); + } + if ( + suite.pending && + mocha.options.forbidPending && + shouldBeTested(suite) + ) { + throw createUnsupportedError('Pending test forbidden'); + } + if (typeof opts.fn === 'function') { + opts.fn.call(suite); + suites.shift(); + } else if (typeof opts.fn === 'undefined' && !suite.pending) { + throw createMissingArgumentError( + 'Suite "' + + suite.fullTitle() + + '" was defined but no callback was supplied. ' + + 'Supply a callback or explicitly skip the suite.', + 'callback', + 'function' + ); + } else if (!opts.fn && suite.pending) { + suites.shift(); + } + + return suite; + } + }, + + test: { + /** + * Exclusive test-case. + * + * @param {Object} mocha + * @param {Function} test + * @returns {*} + */ + only: function (mocha, test) { + if (mocha.options.forbidOnly) { + throw createForbiddenExclusivityError(mocha); + } + test.markOnly(); + return test; + }, + + /** + * Pending test case. + * + * @param {string} title + */ + skip: function (title) { + context.test(title); + } + } + }; + }; + + var Test$3 = test; + var EVENT_FILE_PRE_REQUIRE$2 = + suite.exports.constants.EVENT_FILE_PRE_REQUIRE; + + /** + * BDD-style interface: + * + * describe('Array', function() { + * describe('#indexOf()', function() { + * it('should return -1 when not present', function() { + * // ... + * }); + * + * it('should return the index when present', function() { + * // ... + * }); + * }); + * }); + * + * @param {Suite} suite Root suite. + */ + bdd.exports = function bddInterface(suite) { + var suites = [suite]; + + suite.on(EVENT_FILE_PRE_REQUIRE$2, function (context, file, mocha) { + var common$1 = common(suites, context, mocha); + + context.before = common$1.before; + context.after = common$1.after; + context.beforeEach = common$1.beforeEach; + context.afterEach = common$1.afterEach; + context.run = mocha.options.delay && common$1.runWithSuite(suite); + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.describe = context.context = function (title, fn) { + return common$1.suite.create({ + title, + file, + fn + }); + }; + + /** + * Pending describe. + */ + + context.xdescribe = + context.xcontext = + context.describe.skip = + function (title, fn) { + return common$1.suite.skip({ + title, + file, + fn + }); + }; + + /** + * Exclusive suite. + */ + + context.describe.only = function (title, fn) { + return common$1.suite.only({ + title, + file, + fn + }); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.it = context.specify = function (title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } + var test = new Test$3(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.it.only = function (title, fn) { + return common$1.test.only(mocha, context.it(title, fn)); + }; + + /** + * Pending test case. + */ + + context.xit = + context.xspecify = + context.it.skip = + function (title) { + return context.it(title); + }; + }); + }; + + bdd.exports.description = 'BDD or RSpec style [default]'; + + var tdd = {exports: {}}; + + var Test$2 = test; + var EVENT_FILE_PRE_REQUIRE$1 = + suite.exports.constants.EVENT_FILE_PRE_REQUIRE; + + /** + * TDD-style interface: + * + * suite('Array', function() { + * suite('#indexOf()', function() { + * suiteSetup(function() { + * + * }); + * + * test('should return -1 when not present', function() { + * + * }); + * + * test('should return the index when present', function() { + * + * }); + * + * suiteTeardown(function() { + * + * }); + * }); + * }); + * + * @param {Suite} suite Root suite. + */ + tdd.exports = function (suite) { + var suites = [suite]; + + suite.on(EVENT_FILE_PRE_REQUIRE$1, function (context, file, mocha) { + var common$1 = common(suites, context, mocha); + + context.setup = common$1.beforeEach; + context.teardown = common$1.afterEach; + context.suiteSetup = common$1.before; + context.suiteTeardown = common$1.after; + context.run = mocha.options.delay && common$1.runWithSuite(suite); + + /** + * Describe a "suite" with the given `title` and callback `fn` containing + * nested suites and/or tests. + */ + context.suite = function (title, fn) { + return common$1.suite.create({ + title, + file, + fn + }); + }; + + /** + * Pending suite. + */ + context.suite.skip = function (title, fn) { + return common$1.suite.skip({ + title, + file, + fn + }); + }; + + /** + * Exclusive test-case. + */ + context.suite.only = function (title, fn) { + return common$1.suite.only({ + title, + file, + fn + }); + }; + + /** + * Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. + */ + context.test = function (title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } + var test = new Test$2(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function (title, fn) { + return common$1.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common$1.test.skip; + }); + }; + + tdd.exports.description = + 'traditional "suite"/"test" instead of BDD\'s "describe"/"it"'; + + var qunit = {exports: {}}; + + var Test$1 = test; + var EVENT_FILE_PRE_REQUIRE = + suite.exports.constants.EVENT_FILE_PRE_REQUIRE; + + /** + * QUnit-style interface: + * + * suite('Array'); + * + * test('#length', function() { + * var arr = [1,2,3]; + * ok(arr.length == 3); + * }); + * + * test('#indexOf()', function() { + * var arr = [1,2,3]; + * ok(arr.indexOf(1) == 0); + * ok(arr.indexOf(2) == 1); + * ok(arr.indexOf(3) == 2); + * }); + * + * suite('String'); + * + * test('#length', function() { + * ok('foo'.length == 3); + * }); + * + * @param {Suite} suite Root suite. + */ + qunit.exports = function qUnitInterface(suite) { + var suites = [suite]; + + suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) { + var common$1 = common(suites, context, mocha); + + context.before = common$1.before; + context.after = common$1.after; + context.beforeEach = common$1.beforeEach; + context.afterEach = common$1.afterEach; + context.run = mocha.options.delay && common$1.runWithSuite(suite); + /** + * Describe a "suite" with the given `title`. + */ + + context.suite = function (title) { + if (suites.length > 1) { + suites.shift(); + } + return common$1.suite.create({ + title, + file, + fn: false + }); + }; + + /** + * Exclusive Suite. + */ + + context.suite.only = function (title) { + if (suites.length > 1) { + suites.shift(); + } + return common$1.suite.only({ + title, + file, + fn: false + }); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function (title, fn) { + var test = new Test$1(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function (title, fn) { + return common$1.test.only(mocha, context.test(title, fn)); + }; + + context.test.skip = common$1.test.skip; + }); + }; + + qunit.exports.description = 'QUnit style'; + + var exports$1 = {exports: {}}; + + var Suite = suite.exports; + var Test = test; + + /** + * Exports-style (as Node.js module) interface: + * + * exports.Array = { + * '#indexOf()': { + * 'should return -1 when the value is not present': function() { + * + * }, + * + * 'should return the correct index when the value is present': function() { + * + * } + * } + * }; + * + * @param {Suite} suite Root suite. + */ + exports$1.exports = function (suite) { + var suites = [suite]; + + suite.on(Suite.constants.EVENT_FILE_REQUIRE, visit); + + function visit(obj, file) { + var suite; + for (var key in obj) { + if (typeof obj[key] === 'function') { + var fn = obj[key]; + switch (key) { + case 'before': + suites[0].beforeAll(fn); + break; + case 'after': + suites[0].afterAll(fn); + break; + case 'beforeEach': + suites[0].beforeEach(fn); + break; + case 'afterEach': + suites[0].afterEach(fn); + break; + default: + var test = new Test(key, fn); + test.file = file; + suites[0].addTest(test); + } + } else { + suite = Suite.create(suites[0], key); + suites.unshift(suite); + visit(obj[key], file); + suites.shift(); + } + } + } + }; + + exports$1.exports.description = 'Node.js module ("exports") style'; + + interfaces.bdd = bdd.exports; + interfaces.tdd = tdd.exports; + interfaces.qunit = qunit.exports; + interfaces.exports = exports$1.exports; + + /** + * @module Context + */ + /** + * Expose `Context`. + */ + + var context = Context; + + /** + * Initialize a new `Context`. + * + * @private + */ + function Context() {} + + /** + * Set or get the context `Runnable` to `runnable`. + * + * @private + * @param {Runnable} runnable + * @return {Context} context + */ + Context.prototype.runnable = function (runnable) { + if (!arguments.length) { + return this._runnable; + } + this.test = this._runnable = runnable; + return this; + }; + + /** + * Set or get test timeout `ms`. + * + * @private + * @param {number} ms + * @return {Context} self + */ + Context.prototype.timeout = function (ms) { + if (!arguments.length) { + return this.runnable().timeout(); + } + this.runnable().timeout(ms); + return this; + }; + + /** + * Set or get test slowness threshold `ms`. + * + * @private + * @param {number} ms + * @return {Context} self + */ + Context.prototype.slow = function (ms) { + if (!arguments.length) { + return this.runnable().slow(); + } + this.runnable().slow(ms); + return this; + }; + + /** + * Mark a test as skipped. + * + * @private + * @throws Pending + */ + Context.prototype.skip = function () { + this.runnable().skip(); + }; + + /** + * Set or get a number of allowed retries on failed tests + * + * @private + * @param {number} n + * @return {Context} self + */ + Context.prototype.retries = function (n) { + if (!arguments.length) { + return this.runnable().retries(); + } + this.runnable().retries(n); + return this; + }; + + var name = "mocha"; + var version = "10.4.0"; + var homepage = "https://mochajs.org/"; + var notifyLogo = "https://ibin.co/4QuRuGjXvl36.png"; + var require$$17 = { + name: name, + version: version, + homepage: homepage, + notifyLogo: notifyLogo + }; + + (function (module, exports) { + + /*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + + var escapeRe = escapeStringRegexp; + var path = require$$1; + var builtinReporters = reporters; + var utils = utils$3; + var mocharc = require$$4; + var Suite = suite.exports; + var esmUtils = require$$18; + var createStatsCollector = statsCollector; + const { + createInvalidReporterError, + createInvalidInterfaceError, + createMochaInstanceAlreadyDisposedError, + createMochaInstanceAlreadyRunningError, + createUnsupportedError + } = errors$2; + const {EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE} = + Suite.constants; + var debug = browser.exports('mocha:mocha'); + + exports = module.exports = Mocha; + + /** + * A Mocha instance is a finite state machine. + * These are the states it can be in. + * @private + */ + var mochaStates = utils.defineConstants({ + /** + * Initial state of the mocha instance + * @private + */ + INIT: 'init', + /** + * Mocha instance is running tests + * @private + */ + RUNNING: 'running', + /** + * Mocha instance is done running tests and references to test functions and hooks are cleaned. + * You can reset this state by unloading the test files. + * @private + */ + REFERENCES_CLEANED: 'referencesCleaned', + /** + * Mocha instance is disposed and can no longer be used. + * @private + */ + DISPOSED: 'disposed' + }); + + /** + * To require local UIs and reporters when running in node. + */ + + if (!utils.isBrowser() && typeof module.paths !== 'undefined') { + var cwd = utils.cwd(); + module.paths.push(cwd, path.join(cwd, 'node_modules')); + } + + /** + * Expose internals. + * @private + */ + + exports.utils = utils; + exports.interfaces = interfaces; + /** + * @public + * @memberof Mocha + */ + exports.reporters = builtinReporters; + exports.Runnable = runnable; + exports.Context = context; + /** + * + * @memberof Mocha + */ + exports.Runner = runner; + exports.Suite = Suite; + exports.Hook = hook; + exports.Test = test; + + let currentContext; + exports.afterEach = function (...args) { + return (currentContext.afterEach || currentContext.teardown).apply( + this, + args + ); + }; + exports.after = function (...args) { + return (currentContext.after || currentContext.suiteTeardown).apply( + this, + args + ); + }; + exports.beforeEach = function (...args) { + return (currentContext.beforeEach || currentContext.setup).apply(this, args); + }; + exports.before = function (...args) { + return (currentContext.before || currentContext.suiteSetup).apply(this, args); + }; + exports.describe = function (...args) { + return (currentContext.describe || currentContext.suite).apply(this, args); + }; + exports.describe.only = function (...args) { + return (currentContext.describe || currentContext.suite).only.apply( + this, + args + ); + }; + exports.describe.skip = function (...args) { + return (currentContext.describe || currentContext.suite).skip.apply( + this, + args + ); + }; + exports.it = function (...args) { + return (currentContext.it || currentContext.test).apply(this, args); + }; + exports.it.only = function (...args) { + return (currentContext.it || currentContext.test).only.apply(this, args); + }; + exports.it.skip = function (...args) { + return (currentContext.it || currentContext.test).skip.apply(this, args); + }; + exports.xdescribe = exports.describe.skip; + exports.xit = exports.it.skip; + exports.setup = exports.beforeEach; + exports.suiteSetup = exports.before; + exports.suiteTeardown = exports.after; + exports.suite = exports.describe; + exports.teardown = exports.afterEach; + exports.test = exports.it; + exports.run = function (...args) { + return currentContext.run.apply(this, args); + }; + + /** + * Constructs a new Mocha instance with `options`. + * + * @public + * @class Mocha + * @param {Object} [options] - Settings object. + * @param {boolean} [options.allowUncaught] - Propagate uncaught errors? + * @param {boolean} [options.asyncOnly] - Force `done` callback or promise? + * @param {boolean} [options.bail] - Bail after first test failure? + * @param {boolean} [options.checkLeaks] - Check for global variable leaks? + * @param {boolean} [options.color] - Color TTY output from reporter? + * @param {boolean} [options.delay] - Delay root suite execution? + * @param {boolean} [options.diff] - Show diff on failure? + * @param {boolean} [options.dryRun] - Report tests without running them? + * @param {boolean} [options.failZero] - Fail test run if zero tests? + * @param {string} [options.fgrep] - Test filter given string. + * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite? + * @param {boolean} [options.forbidPending] - Pending tests fail the suite? + * @param {boolean} [options.fullTrace] - Full stacktrace upon failure? + * @param {string[]} [options.global] - Variables expected in global scope. + * @param {RegExp|string} [options.grep] - Test filter given regular expression. + * @param {boolean} [options.inlineDiffs] - Display inline diffs? + * @param {boolean} [options.invert] - Invert test filter matches? + * @param {boolean} [options.noHighlighting] - Disable syntax highlighting? + * @param {string|constructor} [options.reporter] - Reporter name or constructor. + * @param {Object} [options.reporterOption] - Reporter settings object. + * @param {number} [options.retries] - Number of times to retry failed tests. + * @param {number} [options.slow] - Slow threshold value. + * @param {number|string} [options.timeout] - Timeout threshold value. + * @param {string} [options.ui] - Interface name. + * @param {boolean} [options.parallel] - Run jobs in parallel. + * @param {number} [options.jobs] - Max number of worker processes for parallel runs. + * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with. + * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs. + * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process. + */ + function Mocha(options = {}) { + options = {...mocharc, ...options}; + this.files = []; + this.options = options; + // root suite + this.suite = new exports.Suite('', new exports.Context(), true); + this._cleanReferencesAfterRun = true; + this._state = mochaStates.INIT; + + this.grep(options.grep) + .fgrep(options.fgrep) + .ui(options.ui) + .reporter( + options.reporter, + options.reporterOption || options.reporterOptions // for backwards compatibility + ) + .slow(options.slow) + .global(options.global); + + // this guard exists because Suite#timeout does not consider `undefined` to be valid input + if (typeof options.timeout !== 'undefined') { + this.timeout(options.timeout === false ? 0 : options.timeout); + } + + if ('retries' in options) { + this.retries(options.retries); + } + + [ + 'allowUncaught', + 'asyncOnly', + 'bail', + 'checkLeaks', + 'color', + 'delay', + 'diff', + 'dryRun', + 'failZero', + 'forbidOnly', + 'forbidPending', + 'fullTrace', + 'inlineDiffs', + 'invert' + ].forEach(function (opt) { + if (options[opt]) { + this[opt](); + } + }, this); + + if (options.rootHooks) { + this.rootHooks(options.rootHooks); + } + + /** + * The class which we'll instantiate in {@link Mocha#run}. Defaults to + * {@link Runner} in serial mode; changes in parallel mode. + * @memberof Mocha + * @private + */ + this._runnerClass = exports.Runner; + + /** + * Whether or not to call {@link Mocha#loadFiles} implicitly when calling + * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call + * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}. + * @private + * @memberof Mocha + */ + this._lazyLoadFiles = false; + + /** + * It's useful for a Mocha instance to know if it's running in a worker process. + * We could derive this via other means, but it's helpful to have a flag to refer to. + * @memberof Mocha + * @private + */ + this.isWorker = Boolean(options.isWorker); + + this.globalSetup(options.globalSetup) + .globalTeardown(options.globalTeardown) + .enableGlobalSetup(options.enableGlobalSetup) + .enableGlobalTeardown(options.enableGlobalTeardown); + + if ( + options.parallel && + (typeof options.jobs === 'undefined' || options.jobs > 1) + ) { + debug('attempting to enable parallel mode'); + this.parallelMode(true); + } + } + + /** + * Enables or disables bailing on the first failure. + * + * @public + * @see [CLI option](../#-bail-b) + * @param {boolean} [bail=true] - Whether to bail on first error. + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.bail = function (bail) { + this.suite.bail(bail !== false); + return this; + }; + + /** + * @summary + * Adds `file` to be loaded for execution. + * + * @description + * Useful for generic setup code that must be included within test suite. + * + * @public + * @see [CLI option](../#-file-filedirectoryglob) + * @param {string} file - Pathname of file to be loaded. + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.addFile = function (file) { + this.files.push(file); + return this; + }; + + /** + * Sets reporter to `reporter`, defaults to "spec". + * + * @public + * @see [CLI option](../#-reporter-name-r-name) + * @see [Reporters](../#reporters) + * @param {String|Function} reporterName - Reporter name or constructor. + * @param {Object} [reporterOptions] - Options used to configure the reporter. + * @returns {Mocha} this + * @chainable + * @throws {Error} if requested reporter cannot be loaded + * @example + * + * // Use XUnit reporter and direct its output to file + * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' }); + */ + Mocha.prototype.reporter = function (reporterName, reporterOptions) { + if (typeof reporterName === 'function') { + this._reporter = reporterName; + } else { + reporterName = reporterName || 'spec'; + var reporter; + // Try to load a built-in reporter. + if (builtinReporters[reporterName]) { + reporter = builtinReporters[reporterName]; + } + // Try to load reporters from process.cwd() and node_modules + if (!reporter) { + let foundReporter; + try { + foundReporter = require.resolve(reporterName); + reporter = commonjsRequire(foundReporter); + } catch (err) { + if (foundReporter) { + throw createInvalidReporterError(err.message, foundReporter); + } + // Try to load reporters from a cwd-relative path + try { + reporter = commonjsRequire(path.resolve(reporterName)); + } catch (e) { + throw createInvalidReporterError(e.message, reporterName); + } + } + } + this._reporter = reporter; + } + this.options.reporterOption = reporterOptions; + // alias option name is used in built-in reporters xunit/tap/progress + this.options.reporterOptions = reporterOptions; + return this; + }; + + /** + * Sets test UI `name`, defaults to "bdd". + * + * @public + * @see [CLI option](../#-ui-name-u-name) + * @see [Interface DSLs](../#interfaces) + * @param {string|Function} [ui=bdd] - Interface name or class. + * @returns {Mocha} this + * @chainable + * @throws {Error} if requested interface cannot be loaded + */ + Mocha.prototype.ui = function (ui) { + var bindInterface; + if (typeof ui === 'function') { + bindInterface = ui; + } else { + ui = ui || 'bdd'; + bindInterface = exports.interfaces[ui]; + if (!bindInterface) { + try { + bindInterface = commonjsRequire(ui); + } catch (err) { + throw createInvalidInterfaceError(`invalid interface '${ui}'`, ui); + } + } + } + bindInterface(this.suite); + + this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) { + currentContext = context; + }); + + return this; + }; + + /** + * Loads `files` prior to execution. Does not support ES Modules. + * + * @description + * The implementation relies on Node's `require` to execute + * the test interface functions and will be subject to its cache. + * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync. + * + * @private + * @see {@link Mocha#addFile} + * @see {@link Mocha#run} + * @see {@link Mocha#unloadFiles} + * @see {@link Mocha#loadFilesAsync} + * @param {Function} [fn] - Callback invoked upon completion. + */ + Mocha.prototype.loadFiles = function (fn) { + var self = this; + var suite = this.suite; + this.files.forEach(function (file) { + file = path.resolve(file); + suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self); + suite.emit(EVENT_FILE_REQUIRE, commonjsRequire(file), file, self); + suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self); + }); + fn && fn(); + }; + + /** + * Loads `files` prior to execution. Supports Node ES Modules. + * + * @description + * The implementation relies on Node's `require` and `import` to execute + * the test interface functions and will be subject to its cache. + * Supports both CJS and ESM modules. + * + * @public + * @see {@link Mocha#addFile} + * @see {@link Mocha#run} + * @see {@link Mocha#unloadFiles} + * @param {Object} [options] - Settings object. + * @param {Function} [options.esmDecorator] - Function invoked on esm module name right before importing it. By default will passthrough as is. + * @returns {Promise} + * @example + * + * // loads ESM (and CJS) test files asynchronously, then runs root suite + * mocha.loadFilesAsync() + * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0)) + * .catch(() => process.exitCode = 1); + */ + Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) { + var self = this; + var suite = this.suite; + this.lazyLoadFiles(true); + + return esmUtils.loadFilesAsync( + this.files, + function (file) { + suite.emit(EVENT_FILE_PRE_REQUIRE, commonjsGlobal, file, self); + }, + function (file, resultModule) { + suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self); + suite.emit(EVENT_FILE_POST_REQUIRE, commonjsGlobal, file, self); + }, + esmDecorator + ); + }; + + /** + * Removes a previously loaded file from Node's `require` cache. + * + * @private + * @static + * @see {@link Mocha#unloadFiles} + * @param {string} file - Pathname of file to be unloaded. + */ + Mocha.unloadFile = function (file) { + if (utils.isBrowser()) { + throw createUnsupportedError( + 'unloadFile() is only supported in a Node.js environment' + ); + } + return require$$18.unloadFile(file); + }; + + /** + * Unloads `files` from Node's `require` cache. + * + * @description + * This allows required files to be "freshly" reloaded, providing the ability + * to reuse a Mocha instance programmatically. + * Note: does not clear ESM module files from the cache + * + * Intended for consumers — not used internally + * + * @public + * @see {@link Mocha#run} + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.unloadFiles = function () { + if (this._state === mochaStates.DISPOSED) { + throw createMochaInstanceAlreadyDisposedError( + 'Mocha instance is already disposed, it cannot be used again.', + this._cleanReferencesAfterRun, + this + ); + } + + this.files.forEach(function (file) { + Mocha.unloadFile(file); + }); + this._state = mochaStates.INIT; + return this; + }; + + /** + * Sets `grep` filter after escaping RegExp special characters. + * + * @public + * @see {@link Mocha#grep} + * @param {string} str - Value to be converted to a regexp. + * @returns {Mocha} this + * @chainable + * @example + * + * // Select tests whose full title begins with `"foo"` followed by a period + * mocha.fgrep('foo.'); + */ + Mocha.prototype.fgrep = function (str) { + if (!str) { + return this; + } + return this.grep(new RegExp(escapeRe(str))); + }; + + /** + * @summary + * Sets `grep` filter used to select specific tests for execution. + * + * @description + * If `re` is a regexp-like string, it will be converted to regexp. + * The regexp is tested against the full title of each test (i.e., the + * name of the test preceded by titles of each its ancestral suites). + * As such, using an exact-match fixed pattern against the + * test name itself will not yield any matches. + *
        + * Previous filter value will be overwritten on each call! + * + * @public + * @see [CLI option](../#-grep-regexp-g-regexp) + * @see {@link Mocha#fgrep} + * @see {@link Mocha#invert} + * @param {RegExp|String} re - Regular expression used to select tests. + * @return {Mocha} this + * @chainable + * @example + * + * // Select tests whose full title contains `"match"`, ignoring case + * mocha.grep(/match/i); + * @example + * + * // Same as above but with regexp-like string argument + * mocha.grep('/match/i'); + * @example + * + * // ## Anti-example + * // Given embedded test `it('only-this-test')`... + * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this! + */ + Mocha.prototype.grep = function (re) { + if (utils.isString(re)) { + // extract args if it's regex-like, i.e: [string, pattern, flag] + var arg = re.match(/^\/(.*)\/([gimy]{0,4})$|.*/); + this.options.grep = new RegExp(arg[1] || arg[0], arg[2]); + } else { + this.options.grep = re; + } + return this; + }; + + /** + * Inverts `grep` matches. + * + * @public + * @see {@link Mocha#grep} + * @return {Mocha} this + * @chainable + * @example + * + * // Select tests whose full title does *not* contain `"match"`, ignoring case + * mocha.grep(/match/i).invert(); + */ + Mocha.prototype.invert = function () { + this.options.invert = true; + return this; + }; + + /** + * Enables or disables checking for global variables leaked while running tests. + * + * @public + * @see [CLI option](../#-check-leaks) + * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.checkLeaks = function (checkLeaks) { + this.options.checkLeaks = checkLeaks !== false; + return this; + }; + + /** + * Enables or disables whether or not to dispose after each test run. + * Disable this to ensure you can run the test suite multiple times. + * If disabled, be sure to dispose mocha when you're done to prevent memory leaks. + * @public + * @see {@link Mocha#dispose} + * @param {boolean} cleanReferencesAfterRun + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) { + this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false; + return this; + }; + + /** + * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests. + * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector. + * @public + */ + Mocha.prototype.dispose = function () { + if (this._state === mochaStates.RUNNING) { + throw createMochaInstanceAlreadyRunningError( + 'Cannot dispose while the mocha instance is still running tests.' + ); + } + this.unloadFiles(); + this._previousRunner && this._previousRunner.dispose(); + this.suite.dispose(); + this._state = mochaStates.DISPOSED; + }; + + /** + * Displays full stack trace upon test failure. + * + * @public + * @see [CLI option](../#-full-trace) + * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.fullTrace = function (fullTrace) { + this.options.fullTrace = fullTrace !== false; + return this; + }; + + /** + * Specifies whitelist of variable names to be expected in global scope. + * + * @public + * @see [CLI option](../#-global-variable-name) + * @see {@link Mocha#checkLeaks} + * @param {String[]|String} global - Accepted global variable name(s). + * @return {Mocha} this + * @chainable + * @example + * + * // Specify variables to be expected in global scope + * mocha.global(['jQuery', 'MyLib']); + */ + Mocha.prototype.global = function (global) { + this.options.global = (this.options.global || []) + .concat(global) + .filter(Boolean) + .filter(function (elt, idx, arr) { + return arr.indexOf(elt) === idx; + }); + return this; + }; + // for backwards compatibility, 'globals' is an alias of 'global' + Mocha.prototype.globals = Mocha.prototype.global; + + /** + * Enables or disables TTY color output by screen-oriented reporters. + * + * @public + * @see [CLI option](../#-color-c-colors) + * @param {boolean} [color=true] - Whether to enable color output. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.color = function (color) { + this.options.color = color !== false; + return this; + }; + + /** + * Enables or disables reporter to use inline diffs (rather than +/-) + * in test failure output. + * + * @public + * @see [CLI option](../#-inline-diffs) + * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.inlineDiffs = function (inlineDiffs) { + this.options.inlineDiffs = inlineDiffs !== false; + return this; + }; + + /** + * Enables or disables reporter to include diff in test failure output. + * + * @public + * @see [CLI option](../#-diff) + * @param {boolean} [diff=true] - Whether to show diff on failure. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.diff = function (diff) { + this.options.diff = diff !== false; + return this; + }; + + /** + * @summary + * Sets timeout threshold value. + * + * @description + * A string argument can use shorthand (such as "2s") and will be converted. + * If the value is `0`, timeouts will be disabled. + * + * @public + * @see [CLI option](../#-timeout-ms-t-ms) + * @see [Timeouts](../#timeouts) + * @param {number|string} msecs - Timeout threshold value. + * @return {Mocha} this + * @chainable + * @example + * + * // Sets timeout to one second + * mocha.timeout(1000); + * @example + * + * // Same as above but using string argument + * mocha.timeout('1s'); + */ + Mocha.prototype.timeout = function (msecs) { + this.suite.timeout(msecs); + return this; + }; + + /** + * Sets the number of times to retry failed tests. + * + * @public + * @see [CLI option](../#-retries-n) + * @see [Retry Tests](../#retry-tests) + * @param {number} retry - Number of times to retry failed tests. + * @return {Mocha} this + * @chainable + * @example + * + * // Allow any failed test to retry one more time + * mocha.retries(1); + */ + Mocha.prototype.retries = function (retry) { + this.suite.retries(retry); + return this; + }; + + /** + * Sets slowness threshold value. + * + * @public + * @see [CLI option](../#-slow-ms-s-ms) + * @param {number} msecs - Slowness threshold value. + * @return {Mocha} this + * @chainable + * @example + * + * // Sets "slow" threshold to half a second + * mocha.slow(500); + * @example + * + * // Same as above but using string argument + * mocha.slow('0.5s'); + */ + Mocha.prototype.slow = function (msecs) { + this.suite.slow(msecs); + return this; + }; + + /** + * Forces all tests to either accept a `done` callback or return a promise. + * + * @public + * @see [CLI option](../#-async-only-a) + * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.asyncOnly = function (asyncOnly) { + this.options.asyncOnly = asyncOnly !== false; + return this; + }; + + /** + * Disables syntax highlighting (in browser). + * + * @public + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.noHighlighting = function () { + this.options.noHighlighting = true; + return this; + }; + + /** + * Enables or disables uncaught errors to propagate. + * + * @public + * @see [CLI option](../#-allow-uncaught) + * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.allowUncaught = function (allowUncaught) { + this.options.allowUncaught = allowUncaught !== false; + return this; + }; + + /** + * @summary + * Delays root suite execution. + * + * @description + * Used to perform async operations before any suites are run. + * + * @public + * @see [delayed root suite](../#delayed-root-suite) + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.delay = function delay() { + this.options.delay = true; + return this; + }; + + /** + * Enables or disables running tests in dry-run mode. + * + * @public + * @see [CLI option](../#-dry-run) + * @param {boolean} [dryRun=true] - Whether to activate dry-run mode. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.dryRun = function (dryRun) { + this.options.dryRun = dryRun !== false; + return this; + }; + + /** + * Fails test run if no tests encountered with exit-code 1. + * + * @public + * @see [CLI option](../#-fail-zero) + * @param {boolean} [failZero=true] - Whether to fail test run. + * @return {Mocha} this + * @chainable + */ + Mocha.prototype.failZero = function (failZero) { + this.options.failZero = failZero !== false; + return this; + }; + + /** + * Causes tests marked `only` to fail the suite. + * + * @public + * @see [CLI option](../#-forbid-only) + * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite. + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.forbidOnly = function (forbidOnly) { + this.options.forbidOnly = forbidOnly !== false; + return this; + }; + + /** + * Causes pending tests and tests marked `skip` to fail the suite. + * + * @public + * @see [CLI option](../#-forbid-pending) + * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite. + * @returns {Mocha} this + * @chainable + */ + Mocha.prototype.forbidPending = function (forbidPending) { + this.options.forbidPending = forbidPending !== false; + return this; + }; + + /** + * Throws an error if mocha is in the wrong state to be able to transition to a "running" state. + * @private + */ + Mocha.prototype._guardRunningStateTransition = function () { + if (this._state === mochaStates.RUNNING) { + throw createMochaInstanceAlreadyRunningError( + 'Mocha instance is currently running tests, cannot start a next test run until this one is done', + this + ); + } + if ( + this._state === mochaStates.DISPOSED || + this._state === mochaStates.REFERENCES_CLEANED + ) { + throw createMochaInstanceAlreadyDisposedError( + 'Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.', + this._cleanReferencesAfterRun, + this + ); + } + }; + + /** + * Mocha version as specified by "package.json". + * + * @name Mocha#version + * @type string + * @readonly + */ + Object.defineProperty(Mocha.prototype, 'version', { + value: require$$17.version, + configurable: false, + enumerable: true, + writable: false + }); + + /** + * Callback to be invoked when test execution is complete. + * + * @private + * @callback DoneCB + * @param {number} failures - Number of failures that occurred. + */ + + /** + * Runs root suite and invokes `fn()` when complete. + * + * @description + * To run tests multiple times (or to run tests in files that are + * already in the `require` cache), make sure to clear them from + * the cache first! + * + * @public + * @see {@link Mocha#unloadFiles} + * @see {@link Runner#run} + * @param {DoneCB} [fn] - Callback invoked when test execution completed. + * @returns {Runner} runner instance + * @example + * + * // exit with non-zero status if there were test failures + * mocha.run(failures => process.exitCode = failures ? 1 : 0); + */ + Mocha.prototype.run = function (fn) { + this._guardRunningStateTransition(); + this._state = mochaStates.RUNNING; + if (this._previousRunner) { + this._previousRunner.dispose(); + this.suite.reset(); + } + if (this.files.length && !this._lazyLoadFiles) { + this.loadFiles(); + } + var suite = this.suite; + var options = this.options; + options.files = this.files; + const runner = new this._runnerClass(suite, { + cleanReferencesAfterRun: this._cleanReferencesAfterRun, + delay: options.delay, + dryRun: options.dryRun, + failZero: options.failZero + }); + createStatsCollector(runner); + var reporter = new this._reporter(runner, options); + runner.checkLeaks = options.checkLeaks === true; + runner.fullStackTrace = options.fullTrace; + runner.asyncOnly = options.asyncOnly; + runner.allowUncaught = options.allowUncaught; + runner.forbidOnly = options.forbidOnly; + runner.forbidPending = options.forbidPending; + if (options.grep) { + runner.grep(options.grep, options.invert); + } + if (options.global) { + runner.globals(options.global); + } + if (options.color !== undefined) { + exports.reporters.Base.useColors = options.color; + } + exports.reporters.Base.inlineDiffs = options.inlineDiffs; + exports.reporters.Base.hideDiff = !options.diff; + + const done = failures => { + this._previousRunner = runner; + this._state = this._cleanReferencesAfterRun + ? mochaStates.REFERENCES_CLEANED + : mochaStates.INIT; + fn = fn || utils.noop; + if (typeof reporter.done === 'function') { + reporter.done(failures, fn); + } else { + fn(failures); + } + }; + + const runAsync = async runner => { + const context = + this.options.enableGlobalSetup && this.hasGlobalSetupFixtures() + ? await this.runGlobalSetup(runner) + : {}; + const failureCount = await runner.runAsync({ + files: this.files, + options + }); + if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) { + await this.runGlobalTeardown(runner, {context}); + } + return failureCount; + }; + + // no "catch" here is intentional. errors coming out of + // Runner#run are considered uncaught/unhandled and caught + // by the `process` event listeners. + // also: returning anything other than `runner` would be a breaking + // change + runAsync(runner).then(done); + + return runner; + }; + + /** + * Assigns hooks to the root suite + * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite + * @chainable + */ + Mocha.prototype.rootHooks = function rootHooks({ + beforeAll = [], + beforeEach = [], + afterAll = [], + afterEach = [] + } = {}) { + beforeAll = utils.castArray(beforeAll); + beforeEach = utils.castArray(beforeEach); + afterAll = utils.castArray(afterAll); + afterEach = utils.castArray(afterEach); + beforeAll.forEach(hook => { + this.suite.beforeAll(hook); + }); + beforeEach.forEach(hook => { + this.suite.beforeEach(hook); + }); + afterAll.forEach(hook => { + this.suite.afterAll(hook); + }); + afterEach.forEach(hook => { + this.suite.afterEach(hook); + }); + return this; + }; + + /** + * Toggles parallel mode. + * + * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to + * use; also enables lazy file loading if not already done so. + * + * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel + * mode, but parallel mode is _not_ a prerequisite for lazy loading! + * @param {boolean} [enable] - If `true`, enable; otherwise disable. + * @throws If run in browser + * @throws If Mocha not in `INIT` state + * @returns {Mocha} + * @chainable + * @public + */ + Mocha.prototype.parallelMode = function parallelMode(enable = true) { + if (utils.isBrowser()) { + throw createUnsupportedError('parallel mode is only supported in Node.js'); + } + const parallel = Boolean(enable); + if ( + parallel === this.options.parallel && + this._lazyLoadFiles && + this._runnerClass !== exports.Runner + ) { + return this; + } + if (this._state !== mochaStates.INIT) { + throw createUnsupportedError( + 'cannot change parallel mode after having called run()' + ); + } + this.options.parallel = parallel; + + // swap Runner class + this._runnerClass = parallel + ? require$$18 + : exports.Runner; + + // lazyLoadFiles may have been set `true` otherwise (for ESM loading), + // so keep `true` if so. + return this.lazyLoadFiles(this._lazyLoadFiles || parallel); + }; + + /** + * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This + * setting is used by watch mode, parallel mode, and for loading ESM files. + * @todo This should throw if we've already loaded files; such behavior + * necessitates adding a new state. + * @param {boolean} [enable] - If `true`, disable eager loading of files in + * {@link Mocha#run} + * @chainable + * @public + */ + Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) { + this._lazyLoadFiles = enable === true; + debug('set lazy load to %s', enable); + return this; + }; + + /** + * Configures one or more global setup fixtures. + * + * If given no parameters, _unsets_ any previously-set fixtures. + * @chainable + * @public + * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s) + * @returns {Mocha} + */ + Mocha.prototype.globalSetup = function globalSetup(setupFns = []) { + setupFns = utils.castArray(setupFns); + this.options.globalSetup = setupFns; + debug('configured %d global setup functions', setupFns.length); + return this; + }; + + /** + * Configures one or more global teardown fixtures. + * + * If given no parameters, _unsets_ any previously-set fixtures. + * @chainable + * @public + * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s) + * @returns {Mocha} + */ + Mocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) { + teardownFns = utils.castArray(teardownFns); + this.options.globalTeardown = teardownFns; + debug('configured %d global teardown functions', teardownFns.length); + return this; + }; + + /** + * Run any global setup fixtures sequentially, if any. + * + * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}. + * + * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}. + * @param {object} [context] - Context object if already have one + * @public + * @returns {Promise} Context object + */ + Mocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) { + const {globalSetup} = this.options; + if (globalSetup && globalSetup.length) { + debug('run(): global setup starting'); + await this._runGlobalFixtures(globalSetup, context); + debug('run(): global setup complete'); + } + return context; + }; + + /** + * Run any global teardown fixtures sequentially, if any. + * + * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}. + * + * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable. + * @param {object} [context] - Context object if already have one + * @public + * @returns {Promise} Context object + */ + Mocha.prototype.runGlobalTeardown = async function runGlobalTeardown( + context = {} + ) { + const {globalTeardown} = this.options; + if (globalTeardown && globalTeardown.length) { + debug('run(): global teardown starting'); + await this._runGlobalFixtures(globalTeardown, context); + } + debug('run(): global teardown complete'); + return context; + }; + + /** + * Run global fixtures sequentially with context `context` + * @private + * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run + * @param {object} [context] - context object + * @returns {Promise} context object + */ + Mocha.prototype._runGlobalFixtures = async function _runGlobalFixtures( + fixtureFns = [], + context = {} + ) { + for await (const fixtureFn of fixtureFns) { + await fixtureFn.call(context); + } + return context; + }; + + /** + * Toggle execution of any global setup fixture(s) + * + * @chainable + * @public + * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture + * @returns {Mocha} + */ + Mocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) { + this.options.enableGlobalSetup = Boolean(enabled); + return this; + }; + + /** + * Toggle execution of any global teardown fixture(s) + * + * @chainable + * @public + * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture + * @returns {Mocha} + */ + Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown( + enabled = true + ) { + this.options.enableGlobalTeardown = Boolean(enabled); + return this; + }; + + /** + * Returns `true` if one or more global setup fixtures have been supplied. + * @public + * @returns {boolean} + */ + Mocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() { + return Boolean(this.options.globalSetup.length); + }; + + /** + * Returns `true` if one or more global teardown fixtures have been supplied. + * @public + * @returns {boolean} + */ + Mocha.prototype.hasGlobalTeardownFixtures = + function hasGlobalTeardownFixtures() { + return Boolean(this.options.globalTeardown.length); + }; + + /** + * An alternative way to define root hooks that works with parallel runs. + * @typedef {Object} MochaRootHookObject + * @property {Function|Function[]} [beforeAll] - "Before all" hook(s) + * @property {Function|Function[]} [beforeEach] - "Before each" hook(s) + * @property {Function|Function[]} [afterAll] - "After all" hook(s) + * @property {Function|Function[]} [afterEach] - "After each" hook(s) + */ + + /** + * An function that returns a {@link MochaRootHookObject}, either sync or async. + @callback MochaRootHookFunction + * @returns {MochaRootHookObject|Promise} + */ + + /** + * A function that's invoked _once_ which is either sync or async. + * Can be a "teardown" or "setup". These will all share the same context. + * @callback MochaGlobalFixture + * @returns {void|Promise} + */ + + /** + * An object making up all necessary parts of a plugin loader and aggregator + * @typedef {Object} PluginDefinition + * @property {string} exportName - Named export to use + * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted) + * @property {PluginValidator} [validate] - Validator function + * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function + */ + + /** + * A (sync) function to assert a user-supplied plugin implementation is valid. + * + * Defined in a {@link PluginDefinition}. + + * @callback PluginValidator + * @param {*} value - Value to check + * @this {PluginDefinition} + * @returns {void} + */ + + /** + * A function to finalize plugins impls of a particular ilk + * @callback PluginFinalizer + * @param {Array<*>} impls - User-supplied implementations + * @returns {Promise<*>|*} + */ + }(mocha$1, mocha$1.exports)); + + /* eslint no-unused-vars: off */ + /* eslint-env commonjs */ + + /** + * Shim process.stdout. + */ + + process.stdout = browserStdout({label: false}); + + var parseQuery = parseQuery$1; + var highlightTags = highlightTags$1; + var Mocha = mocha$1.exports; + + /** + * Create a Mocha instance. + * + * @return {undefined} + */ + + var mocha = new Mocha({reporter: 'html'}); + + /** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + + var Date$1 = commonjsGlobal.Date; + var setTimeout$1 = commonjsGlobal.setTimeout; + commonjsGlobal.setInterval; + commonjsGlobal.clearTimeout; + commonjsGlobal.clearInterval; + + var uncaughtExceptionHandlers = []; + + var originalOnerrorHandler = commonjsGlobal.onerror; + + /** + * Remove uncaughtException listener. + * Revert to original onerror handler if previously defined. + */ + + process.removeListener = function (e, fn) { + if (e === 'uncaughtException') { + if (originalOnerrorHandler) { + commonjsGlobal.onerror = originalOnerrorHandler; + } else { + commonjsGlobal.onerror = function () {}; + } + var i = uncaughtExceptionHandlers.indexOf(fn); + if (i !== -1) { + uncaughtExceptionHandlers.splice(i, 1); + } + } + }; + + /** + * Implements listenerCount for 'uncaughtException'. + */ + + process.listenerCount = function (name) { + if (name === 'uncaughtException') { + return uncaughtExceptionHandlers.length; + } + return 0; + }; + + /** + * Implements uncaughtException listener. + */ + + process.on = function (e, fn) { + if (e === 'uncaughtException') { + commonjsGlobal.onerror = function (err, url, line) { + fn(new Error(err + ' (' + url + ':' + line + ')')); + return !mocha.options.allowUncaught; + }; + uncaughtExceptionHandlers.push(fn); + } + }; + + process.listeners = function (e) { + if (e === 'uncaughtException') { + return uncaughtExceptionHandlers; + } + return []; + }; + + // The BDD UI is registered by default, but no UI will be functional in the + // browser without an explicit call to the overridden `mocha.ui` (see below). + // Ensure that this default UI does not expose its methods to the global scope. + mocha.suite.removeAllListeners('pre-require'); + + var immediateQueue = []; + var immediateTimeout; + + function timeslice() { + var immediateStart = new Date$1().getTime(); + while (immediateQueue.length && new Date$1().getTime() - immediateStart < 100) { + immediateQueue.shift()(); + } + if (immediateQueue.length) { + immediateTimeout = setTimeout$1(timeslice, 0); + } else { + immediateTimeout = null; + } + } + + /** + * High-performance override of Runner.immediately. + */ + + Mocha.Runner.immediately = function (callback) { + immediateQueue.push(callback); + if (!immediateTimeout) { + immediateTimeout = setTimeout$1(timeslice, 0); + } + }; + + /** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + */ + mocha.throwError = function (err) { + uncaughtExceptionHandlers.forEach(function (fn) { + fn(err); + }); + throw err; + }; + + /** + * Override ui to ensure that the ui functions are initialized. + * Normally this would happen in Mocha.prototype.loadFiles. + */ + + mocha.ui = function (ui) { + Mocha.prototype.ui.call(this, ui); + this.suite.emit('pre-require', commonjsGlobal, null, this); + return this; + }; + + /** + * Setup mocha with the given setting options. + */ + + mocha.setup = function (opts) { + if (typeof opts === 'string') { + opts = {ui: opts}; + } + if (opts.delay === true) { + this.delay(); + } + var self = this; + Object.keys(opts) + .filter(function (opt) { + return opt !== 'delay'; + }) + .forEach(function (opt) { + if (Object.prototype.hasOwnProperty.call(opts, opt)) { + self[opt](opts[opt]); + } + }); + return this; + }; + + /** + * Run mocha, returning the Runner. + */ + + mocha.run = function (fn) { + var options = mocha.options; + mocha.globals('location'); + + var query = parseQuery(commonjsGlobal.location.search || ''); + if (query.grep) { + mocha.grep(query.grep); + } + if (query.fgrep) { + mocha.fgrep(query.fgrep); + } + if (query.invert) { + mocha.invert(); + } + + return Mocha.prototype.run.call(mocha, function (err) { + // The DOM Document is not available in Web Workers. + var document = commonjsGlobal.document; + if ( + document && + document.getElementById('mocha') && + options.noHighlighting !== true + ) { + highlightTags('code'); + } + if (fn) { + fn(err); + } + }); + }; + + /** + * Expose the process shim. + * https://github.com/mochajs/mocha/pull/916 + */ + + Mocha.process = process; + + /** + * Expose mocha. + */ + commonjsGlobal.Mocha = Mocha; + commonjsGlobal.mocha = mocha; + + // for bundlers: enable `import {describe, it} from 'mocha'` + // `bdd` interface only + // prettier-ignore + [ + 'describe', 'context', 'it', 'specify', + 'xdescribe', 'xcontext', 'xit', 'xspecify', + 'before', 'beforeEach', 'afterEach', 'after' + ].forEach(function(key) { + mocha[key] = commonjsGlobal[key]; + }); + + var browserEntry = mocha; + + return browserEntry; + +})); //# sourceMappingURL=mocha.js.map diff --git a/node_modules/mocha/mocha.js.map b/node_modules/mocha/mocha.js.map index 8d72f45..c1bd445 100644 --- a/node_modules/mocha/mocha.js.map +++ b/node_modules/mocha/mocha.js.map @@ -1 +1 @@ -{"version":3,"file":"mocha.js","sources":["node_modules/core-js/internals/global.js","node_modules/core-js/internals/fails.js","node_modules/core-js/internals/descriptors.js","node_modules/core-js/internals/object-property-is-enumerable.js","node_modules/core-js/internals/create-property-descriptor.js","node_modules/core-js/internals/classof-raw.js","node_modules/core-js/internals/indexed-object.js","node_modules/core-js/internals/require-object-coercible.js","node_modules/core-js/internals/to-indexed-object.js","node_modules/core-js/internals/is-object.js","node_modules/core-js/internals/to-primitive.js","node_modules/core-js/internals/has.js","node_modules/core-js/internals/document-create-element.js","node_modules/core-js/internals/ie8-dom-define.js","node_modules/core-js/internals/object-get-own-property-descriptor.js","node_modules/core-js/internals/an-object.js","node_modules/core-js/internals/object-define-property.js","node_modules/core-js/internals/create-non-enumerable-property.js","node_modules/core-js/internals/set-global.js","node_modules/core-js/internals/shared-store.js","node_modules/core-js/internals/inspect-source.js","node_modules/core-js/internals/native-weak-map.js","node_modules/core-js/internals/shared.js","node_modules/core-js/internals/uid.js","node_modules/core-js/internals/shared-key.js","node_modules/core-js/internals/hidden-keys.js","node_modules/core-js/internals/internal-state.js","node_modules/core-js/internals/redefine.js","node_modules/core-js/internals/path.js","node_modules/core-js/internals/get-built-in.js","node_modules/core-js/internals/to-integer.js","node_modules/core-js/internals/to-length.js","node_modules/core-js/internals/to-absolute-index.js","node_modules/core-js/internals/array-includes.js","node_modules/core-js/internals/object-keys-internal.js","node_modules/core-js/internals/enum-bug-keys.js","node_modules/core-js/internals/object-get-own-property-names.js","node_modules/core-js/internals/object-get-own-property-symbols.js","node_modules/core-js/internals/own-keys.js","node_modules/core-js/internals/copy-constructor-properties.js","node_modules/core-js/internals/is-forced.js","node_modules/core-js/internals/export.js","node_modules/core-js/internals/a-function.js","node_modules/core-js/internals/function-bind-context.js","node_modules/core-js/internals/to-object.js","node_modules/core-js/internals/is-array.js","node_modules/core-js/internals/native-symbol.js","node_modules/core-js/internals/use-symbol-as-uid.js","node_modules/core-js/internals/well-known-symbol.js","node_modules/core-js/internals/array-species-create.js","node_modules/core-js/internals/array-iteration.js","node_modules/core-js/internals/engine-user-agent.js","node_modules/core-js/internals/engine-v8-version.js","node_modules/core-js/internals/array-method-has-species-support.js","node_modules/core-js/internals/array-method-uses-to-length.js","node_modules/core-js/modules/es.array.filter.js","node_modules/core-js/internals/create-property.js","node_modules/core-js/modules/es.array.splice.js","node_modules/core-js/internals/object-keys.js","node_modules/core-js/internals/object-assign.js","node_modules/core-js/modules/es.object.assign.js","node_modules/core-js/modules/es.object.keys.js","node_modules/core-js/internals/regexp-flags.js","node_modules/core-js/internals/regexp-sticky-helpers.js","node_modules/core-js/internals/regexp-exec.js","node_modules/core-js/modules/es.regexp.exec.js","node_modules/core-js/internals/fix-regexp-well-known-symbol-logic.js","node_modules/core-js/internals/same-value.js","node_modules/core-js/internals/regexp-exec-abstract.js","node_modules/core-js/modules/es.string.search.js","node_modules/core-js/internals/dom-iterables.js","node_modules/core-js/internals/array-method-is-strict.js","node_modules/core-js/internals/array-for-each.js","node_modules/core-js/modules/web.dom-collections.for-each.js","node_modules/core-js/modules/es.array.concat.js","node_modules/rollup-plugin-node-polyfills/polyfills/global.js","node_modules/rollup-plugin-node-globals/src/global.js","node_modules/process-es6/browser.js","node_modules/core-js/internals/to-string-tag-support.js","node_modules/core-js/internals/classof.js","node_modules/core-js/internals/object-to-string.js","node_modules/core-js/modules/es.object.to-string.js","node_modules/core-js/modules/es.regexp.to-string.js","node_modules/core-js/modules/es.function.name.js","node_modules/core-js/internals/correct-prototype-getter.js","node_modules/core-js/internals/object-get-prototype-of.js","node_modules/core-js/modules/es.object.get-prototype-of.js","node_modules/core-js/modules/es.reflect.own-keys.js","node_modules/rollup-plugin-node-polyfills/polyfills/events.js","node_modules/core-js/modules/es.array.join.js","node_modules/core-js/modules/es.array.map.js","node_modules/core-js/internals/a-possible-prototype.js","node_modules/core-js/internals/object-set-prototype-of.js","node_modules/core-js/internals/inherit-if-required.js","node_modules/core-js/internals/object-define-properties.js","node_modules/core-js/internals/html.js","node_modules/core-js/internals/object-create.js","node_modules/core-js/internals/whitespaces.js","node_modules/core-js/internals/string-trim.js","node_modules/core-js/modules/es.number.constructor.js","node_modules/core-js/modules/es.object.get-own-property-descriptor.js","node_modules/core-js/internals/object-get-own-property-names-external.js","node_modules/core-js/modules/es.object.get-own-property-names.js","node_modules/core-js/internals/is-regexp.js","node_modules/core-js/internals/set-species.js","node_modules/core-js/modules/es.regexp.constructor.js","node_modules/core-js/internals/string-multibyte.js","node_modules/core-js/internals/advance-string-index.js","node_modules/core-js/modules/es.string.match.js","node_modules/core-js/internals/get-substitution.js","node_modules/core-js/modules/es.string.replace.js","node_modules/core-js/internals/species-constructor.js","node_modules/core-js/modules/es.string.split.js","node_modules/core-js/internals/well-known-symbol-wrapped.js","node_modules/core-js/internals/define-well-known-symbol.js","node_modules/core-js/internals/set-to-string-tag.js","node_modules/core-js/modules/es.symbol.js","node_modules/core-js/modules/es.symbol.description.js","node_modules/core-js/modules/es.symbol.species.js","node_modules/core-js/internals/array-fill.js","node_modules/core-js/internals/add-to-unscopables.js","node_modules/core-js/modules/es.array.fill.js","node_modules/core-js/modules/es.array.includes.js","node_modules/core-js/internals/iterators.js","node_modules/core-js/internals/iterators-core.js","node_modules/core-js/internals/create-iterator-constructor.js","node_modules/core-js/internals/define-iterator.js","node_modules/core-js/modules/es.array.iterator.js","node_modules/core-js/modules/es.array.slice.js","node_modules/core-js/modules/es.array.species.js","node_modules/core-js/internals/array-buffer-native.js","node_modules/core-js/internals/redefine-all.js","node_modules/core-js/internals/an-instance.js","node_modules/core-js/internals/to-index.js","node_modules/core-js/internals/ieee754.js","node_modules/core-js/internals/array-buffer.js","node_modules/core-js/modules/es.array-buffer.constructor.js","node_modules/core-js/internals/not-a-regexp.js","node_modules/core-js/internals/correct-is-regexp-logic.js","node_modules/core-js/modules/es.string.includes.js","node_modules/core-js/internals/string-trim-forced.js","node_modules/core-js/modules/es.string.trim.js","node_modules/core-js/internals/check-correctness-of-iteration.js","node_modules/core-js/internals/array-buffer-view-core.js","node_modules/core-js/internals/typed-array-constructors-require-wrappers.js","node_modules/core-js/internals/to-positive-integer.js","node_modules/core-js/internals/to-offset.js","node_modules/core-js/internals/get-iterator-method.js","node_modules/core-js/internals/is-array-iterator-method.js","node_modules/core-js/internals/typed-array-from.js","node_modules/core-js/internals/typed-array-constructor.js","node_modules/core-js/modules/es.typed-array.uint8-array.js","node_modules/core-js/internals/array-copy-within.js","node_modules/core-js/modules/es.typed-array.copy-within.js","node_modules/core-js/modules/es.typed-array.every.js","node_modules/core-js/modules/es.typed-array.fill.js","node_modules/core-js/modules/es.typed-array.filter.js","node_modules/core-js/modules/es.typed-array.find.js","node_modules/core-js/modules/es.typed-array.find-index.js","node_modules/core-js/modules/es.typed-array.for-each.js","node_modules/core-js/modules/es.typed-array.includes.js","node_modules/core-js/modules/es.typed-array.index-of.js","node_modules/core-js/modules/es.typed-array.iterator.js","node_modules/core-js/modules/es.typed-array.join.js","node_modules/core-js/internals/array-last-index-of.js","node_modules/core-js/modules/es.typed-array.last-index-of.js","node_modules/core-js/modules/es.typed-array.map.js","node_modules/core-js/internals/array-reduce.js","node_modules/core-js/modules/es.typed-array.reduce.js","node_modules/core-js/modules/es.typed-array.reduce-right.js","node_modules/core-js/modules/es.typed-array.reverse.js","node_modules/core-js/modules/es.typed-array.set.js","node_modules/core-js/modules/es.typed-array.slice.js","node_modules/core-js/modules/es.typed-array.some.js","node_modules/core-js/modules/es.typed-array.sort.js","node_modules/core-js/modules/es.typed-array.subarray.js","node_modules/core-js/modules/es.typed-array.to-locale-string.js","node_modules/core-js/modules/es.typed-array.to-string.js","node_modules/core-js/modules/web.url.to-json.js","node_modules/buffer-es6/base64.js","node_modules/buffer-es6/ieee754.js","node_modules/buffer-es6/isArray.js","node_modules/buffer-es6/index.js","node_modules/rollup-plugin-node-polyfills/polyfills/process-es6.js","node_modules/rollup-plugin-node-polyfills/polyfills/inherits.js","node_modules/rollup-plugin-node-polyfills/polyfills/util.js","node_modules/rollup-plugin-node-polyfills/polyfills/buffer-es6.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/buffer-list.js","node_modules/rollup-plugin-node-polyfills/polyfills/string-decoder.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/readable.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/writable.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/duplex.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/transform.js","node_modules/rollup-plugin-node-polyfills/polyfills/readable-stream/passthrough.js","node_modules/rollup-plugin-node-polyfills/polyfills/stream.js","node_modules/browser-stdout/index.js","lib/browser/parse-query.js","lib/browser/highlight-tags.js","node_modules/core-js/internals/native-promise-constructor.js","node_modules/core-js/internals/iterator-close.js","node_modules/core-js/internals/iterate.js","node_modules/core-js/internals/engine-is-ios.js","node_modules/core-js/internals/engine-is-node.js","node_modules/core-js/internals/task.js","node_modules/core-js/internals/engine-is-webos-webkit.js","node_modules/core-js/internals/microtask.js","node_modules/core-js/internals/new-promise-capability.js","node_modules/core-js/internals/promise-resolve.js","node_modules/core-js/internals/host-report-errors.js","node_modules/core-js/internals/perform.js","node_modules/core-js/modules/es.promise.js","node_modules/core-js/modules/es.symbol.async-iterator.js","node_modules/core-js/modules/es.symbol.iterator.js","node_modules/core-js/modules/es.symbol.to-string-tag.js","node_modules/core-js/modules/es.json.to-string-tag.js","node_modules/core-js/modules/es.math.to-string-tag.js","node_modules/core-js/modules/es.string.iterator.js","node_modules/core-js/modules/web.dom-collections.iterator.js","node_modules/regenerator-runtime/runtime.js","node_modules/escape-string-regexp/index.js","node_modules/rollup-plugin-node-polyfills/polyfills/path.js","node_modules/core-js/internals/call-with-safe-iteration-closing.js","node_modules/core-js/internals/array-from.js","node_modules/core-js/modules/es.array.from.js","node_modules/diff/dist/diff.js","node_modules/ms/index.js","node_modules/core-js/internals/freezing.js","node_modules/core-js/internals/internal-metadata.js","node_modules/core-js/modules/es.object.freeze.js","node_modules/core-js/internals/collection.js","node_modules/core-js/internals/collection-strong.js","node_modules/core-js/modules/es.set.js","node_modules/rollup-plugin-node-globals/src/browser.js","node_modules/nanoid/non-secure/index.js","node_modules/he/he.js","node_modules/core-js/internals/object-to-array.js","node_modules/core-js/modules/es.object.values.js","lib/errors.js","lib/utils.js","node_modules/core-js/modules/es.map.js","lib/pending.js","node_modules/debug/node_modules/ms/index.js","node_modules/debug/src/common.js","node_modules/debug/src/browser.js","lib/runnable.js","lib/hook.js","lib/suite.js","lib/runner.js","lib/reporters/base.js","lib/reporters/dot.js","lib/reporters/doc.js","lib/reporters/tap.js","lib/reporters/json.js","node_modules/core-js/internals/this-number-value.js","node_modules/core-js/internals/string-repeat.js","node_modules/core-js/modules/es.number.to-fixed.js","lib/browser/progress.js","lib/reporters/html.js","lib/reporters/list.js","lib/reporters/min.js","lib/reporters/spec.js","lib/reporters/nyan.js","node_modules/rollup-plugin-node-polyfills/polyfills/empty.js","lib/reporters/xunit.js","lib/reporters/markdown.js","lib/reporters/progress.js","lib/reporters/landing.js","lib/reporters/json-stream.js","lib/reporters/index.js","lib/browser/growl.js","lib/stats-collector.js","lib/test.js","lib/interfaces/common.js","lib/interfaces/bdd.js","lib/interfaces/tdd.js","lib/interfaces/qunit.js","lib/interfaces/exports.js","lib/interfaces/index.js","lib/context.js","lib/mocha.js","browser-entry.js"],"sourcesContent":["var check = function (it) {\n return it && it.Math == Math && it;\n};\n\n// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028\nmodule.exports =\n // eslint-disable-next-line no-undef\n check(typeof globalThis == 'object' && globalThis) ||\n check(typeof window == 'object' && window) ||\n check(typeof self == 'object' && self) ||\n check(typeof global == 'object' && global) ||\n // eslint-disable-next-line no-new-func\n (function () { return this; })() || Function('return this')();\n","module.exports = function (exec) {\n try {\n return !!exec();\n } catch (error) {\n return true;\n }\n};\n","var fails = require('../internals/fails');\n\n// Detect IE8's incomplete defineProperty implementation\nmodule.exports = !fails(function () {\n return Object.defineProperty({}, 1, { get: function () { return 7; } })[1] != 7;\n});\n","'use strict';\nvar nativePropertyIsEnumerable = {}.propertyIsEnumerable;\nvar getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// Nashorn ~ JDK8 bug\nvar NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);\n\n// `Object.prototype.propertyIsEnumerable` method implementation\n// https://tc39.es/ecma262/#sec-object.prototype.propertyisenumerable\nexports.f = NASHORN_BUG ? function propertyIsEnumerable(V) {\n var descriptor = getOwnPropertyDescriptor(this, V);\n return !!descriptor && descriptor.enumerable;\n} : nativePropertyIsEnumerable;\n","module.exports = function (bitmap, value) {\n return {\n enumerable: !(bitmap & 1),\n configurable: !(bitmap & 2),\n writable: !(bitmap & 4),\n value: value\n };\n};\n","var toString = {}.toString;\n\nmodule.exports = function (it) {\n return toString.call(it).slice(8, -1);\n};\n","var fails = require('../internals/fails');\nvar classof = require('../internals/classof-raw');\n\nvar split = ''.split;\n\n// fallback for non-array-like ES3 and non-enumerable old V8 strings\nmodule.exports = fails(function () {\n // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346\n // eslint-disable-next-line no-prototype-builtins\n return !Object('z').propertyIsEnumerable(0);\n}) ? function (it) {\n return classof(it) == 'String' ? split.call(it, '') : Object(it);\n} : Object;\n","// `RequireObjectCoercible` abstract operation\n// https://tc39.es/ecma262/#sec-requireobjectcoercible\nmodule.exports = function (it) {\n if (it == undefined) throw TypeError(\"Can't call method on \" + it);\n return it;\n};\n","// toObject with fallback for non-array-like ES3 strings\nvar IndexedObject = require('../internals/indexed-object');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\nmodule.exports = function (it) {\n return IndexedObject(requireObjectCoercible(it));\n};\n","module.exports = function (it) {\n return typeof it === 'object' ? it !== null : typeof it === 'function';\n};\n","var isObject = require('../internals/is-object');\n\n// `ToPrimitive` abstract operation\n// https://tc39.es/ecma262/#sec-toprimitive\n// instead of the ES6 spec version, we didn't implement @@toPrimitive case\n// and the second argument - flag - preferred type is a string\nmodule.exports = function (input, PREFERRED_STRING) {\n if (!isObject(input)) return input;\n var fn, val;\n if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;\n if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;\n throw TypeError(\"Can't convert object to primitive value\");\n};\n","var hasOwnProperty = {}.hasOwnProperty;\n\nmodule.exports = function (it, key) {\n return hasOwnProperty.call(it, key);\n};\n","var global = require('../internals/global');\nvar isObject = require('../internals/is-object');\n\nvar document = global.document;\n// typeof document.createElement is 'object' in old IE\nvar EXISTS = isObject(document) && isObject(document.createElement);\n\nmodule.exports = function (it) {\n return EXISTS ? document.createElement(it) : {};\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar createElement = require('../internals/document-create-element');\n\n// Thank's IE8 for his funny defineProperty\nmodule.exports = !DESCRIPTORS && !fails(function () {\n return Object.defineProperty(createElement('div'), 'a', {\n get: function () { return 7; }\n }).a != 7;\n});\n","var DESCRIPTORS = require('../internals/descriptors');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar has = require('../internals/has');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\n\nvar nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor\nexports.f = DESCRIPTORS ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {\n O = toIndexedObject(O);\n P = toPrimitive(P, true);\n if (IE8_DOM_DEFINE) try {\n return nativeGetOwnPropertyDescriptor(O, P);\n } catch (error) { /* empty */ }\n if (has(O, P)) return createPropertyDescriptor(!propertyIsEnumerableModule.f.call(O, P), O[P]);\n};\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it)) {\n throw TypeError(String(it) + ' is not an object');\n } return it;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar IE8_DOM_DEFINE = require('../internals/ie8-dom-define');\nvar anObject = require('../internals/an-object');\nvar toPrimitive = require('../internals/to-primitive');\n\nvar nativeDefineProperty = Object.defineProperty;\n\n// `Object.defineProperty` method\n// https://tc39.es/ecma262/#sec-object.defineproperty\nexports.f = DESCRIPTORS ? nativeDefineProperty : function defineProperty(O, P, Attributes) {\n anObject(O);\n P = toPrimitive(P, true);\n anObject(Attributes);\n if (IE8_DOM_DEFINE) try {\n return nativeDefineProperty(O, P, Attributes);\n } catch (error) { /* empty */ }\n if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');\n if ('value' in Attributes) O[P] = Attributes.value;\n return O;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = DESCRIPTORS ? function (object, key, value) {\n return definePropertyModule.f(object, key, createPropertyDescriptor(1, value));\n} : function (object, key, value) {\n object[key] = value;\n return object;\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nmodule.exports = function (key, value) {\n try {\n createNonEnumerableProperty(global, key, value);\n } catch (error) {\n global[key] = value;\n } return value;\n};\n","var global = require('../internals/global');\nvar setGlobal = require('../internals/set-global');\n\nvar SHARED = '__core-js_shared__';\nvar store = global[SHARED] || setGlobal(SHARED, {});\n\nmodule.exports = store;\n","var store = require('../internals/shared-store');\n\nvar functionToString = Function.toString;\n\n// this helper broken in `3.4.1-3.4.4`, so we can't use `shared` helper\nif (typeof store.inspectSource != 'function') {\n store.inspectSource = function (it) {\n return functionToString.call(it);\n };\n}\n\nmodule.exports = store.inspectSource;\n","var global = require('../internals/global');\nvar inspectSource = require('../internals/inspect-source');\n\nvar WeakMap = global.WeakMap;\n\nmodule.exports = typeof WeakMap === 'function' && /native code/.test(inspectSource(WeakMap));\n","var IS_PURE = require('../internals/is-pure');\nvar store = require('../internals/shared-store');\n\n(module.exports = function (key, value) {\n return store[key] || (store[key] = value !== undefined ? value : {});\n})('versions', []).push({\n version: '3.8.3',\n mode: IS_PURE ? 'pure' : 'global',\n copyright: '© 2021 Denis Pushkarev (zloirock.ru)'\n});\n","var id = 0;\nvar postfix = Math.random();\n\nmodule.exports = function (key) {\n return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);\n};\n","var shared = require('../internals/shared');\nvar uid = require('../internals/uid');\n\nvar keys = shared('keys');\n\nmodule.exports = function (key) {\n return keys[key] || (keys[key] = uid(key));\n};\n","module.exports = {};\n","var NATIVE_WEAK_MAP = require('../internals/native-weak-map');\nvar global = require('../internals/global');\nvar isObject = require('../internals/is-object');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar objectHas = require('../internals/has');\nvar shared = require('../internals/shared-store');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\n\nvar WeakMap = global.WeakMap;\nvar set, get, has;\n\nvar enforce = function (it) {\n return has(it) ? get(it) : set(it, {});\n};\n\nvar getterFor = function (TYPE) {\n return function (it) {\n var state;\n if (!isObject(it) || (state = get(it)).type !== TYPE) {\n throw TypeError('Incompatible receiver, ' + TYPE + ' required');\n } return state;\n };\n};\n\nif (NATIVE_WEAK_MAP) {\n var store = shared.state || (shared.state = new WeakMap());\n var wmget = store.get;\n var wmhas = store.has;\n var wmset = store.set;\n set = function (it, metadata) {\n metadata.facade = it;\n wmset.call(store, it, metadata);\n return metadata;\n };\n get = function (it) {\n return wmget.call(store, it) || {};\n };\n has = function (it) {\n return wmhas.call(store, it);\n };\n} else {\n var STATE = sharedKey('state');\n hiddenKeys[STATE] = true;\n set = function (it, metadata) {\n metadata.facade = it;\n createNonEnumerableProperty(it, STATE, metadata);\n return metadata;\n };\n get = function (it) {\n return objectHas(it, STATE) ? it[STATE] : {};\n };\n has = function (it) {\n return objectHas(it, STATE);\n };\n}\n\nmodule.exports = {\n set: set,\n get: get,\n has: has,\n enforce: enforce,\n getterFor: getterFor\n};\n","var global = require('../internals/global');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar setGlobal = require('../internals/set-global');\nvar inspectSource = require('../internals/inspect-source');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar getInternalState = InternalStateModule.get;\nvar enforceInternalState = InternalStateModule.enforce;\nvar TEMPLATE = String(String).split('String');\n\n(module.exports = function (O, key, value, options) {\n var unsafe = options ? !!options.unsafe : false;\n var simple = options ? !!options.enumerable : false;\n var noTargetGet = options ? !!options.noTargetGet : false;\n var state;\n if (typeof value == 'function') {\n if (typeof key == 'string' && !has(value, 'name')) {\n createNonEnumerableProperty(value, 'name', key);\n }\n state = enforceInternalState(value);\n if (!state.source) {\n state.source = TEMPLATE.join(typeof key == 'string' ? key : '');\n }\n }\n if (O === global) {\n if (simple) O[key] = value;\n else setGlobal(key, value);\n return;\n } else if (!unsafe) {\n delete O[key];\n } else if (!noTargetGet && O[key]) {\n simple = true;\n }\n if (simple) O[key] = value;\n else createNonEnumerableProperty(O, key, value);\n// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative\n})(Function.prototype, 'toString', function toString() {\n return typeof this == 'function' && getInternalState(this).source || inspectSource(this);\n});\n","var global = require('../internals/global');\n\nmodule.exports = global;\n","var path = require('../internals/path');\nvar global = require('../internals/global');\n\nvar aFunction = function (variable) {\n return typeof variable == 'function' ? variable : undefined;\n};\n\nmodule.exports = function (namespace, method) {\n return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global[namespace])\n : path[namespace] && path[namespace][method] || global[namespace] && global[namespace][method];\n};\n","var ceil = Math.ceil;\nvar floor = Math.floor;\n\n// `ToInteger` abstract operation\n// https://tc39.es/ecma262/#sec-tointeger\nmodule.exports = function (argument) {\n return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);\n};\n","var toInteger = require('../internals/to-integer');\n\nvar min = Math.min;\n\n// `ToLength` abstract operation\n// https://tc39.es/ecma262/#sec-tolength\nmodule.exports = function (argument) {\n return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991\n};\n","var toInteger = require('../internals/to-integer');\n\nvar max = Math.max;\nvar min = Math.min;\n\n// Helper for a popular repeating case of the spec:\n// Let integer be ? ToInteger(index).\n// If integer < 0, let result be max((length + integer), 0); else let result be min(integer, length).\nmodule.exports = function (index, length) {\n var integer = toInteger(index);\n return integer < 0 ? max(integer + length, 0) : min(integer, length);\n};\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar toLength = require('../internals/to-length');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\n\n// `Array.prototype.{ indexOf, includes }` methods implementation\nvar createMethod = function (IS_INCLUDES) {\n return function ($this, el, fromIndex) {\n var O = toIndexedObject($this);\n var length = toLength(O.length);\n var index = toAbsoluteIndex(fromIndex, length);\n var value;\n // Array#includes uses SameValueZero equality algorithm\n // eslint-disable-next-line no-self-compare\n if (IS_INCLUDES && el != el) while (length > index) {\n value = O[index++];\n // eslint-disable-next-line no-self-compare\n if (value != value) return true;\n // Array#indexOf ignores holes, Array#includes - not\n } else for (;length > index; index++) {\n if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;\n } return !IS_INCLUDES && -1;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.includes` method\n // https://tc39.es/ecma262/#sec-array.prototype.includes\n includes: createMethod(true),\n // `Array.prototype.indexOf` method\n // https://tc39.es/ecma262/#sec-array.prototype.indexof\n indexOf: createMethod(false)\n};\n","var has = require('../internals/has');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar indexOf = require('../internals/array-includes').indexOf;\nvar hiddenKeys = require('../internals/hidden-keys');\n\nmodule.exports = function (object, names) {\n var O = toIndexedObject(object);\n var i = 0;\n var result = [];\n var key;\n for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);\n // Don't enum bug & hidden keys\n while (names.length > i) if (has(O, key = names[i++])) {\n ~indexOf(result, key) || result.push(key);\n }\n return result;\n};\n","// IE8- don't enum bug keys\nmodule.exports = [\n 'constructor',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'toLocaleString',\n 'toString',\n 'valueOf'\n];\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\nvar hiddenKeys = enumBugKeys.concat('length', 'prototype');\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.es/ecma262/#sec-object.getownpropertynames\nexports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {\n return internalObjectKeys(O, hiddenKeys);\n};\n","exports.f = Object.getOwnPropertySymbols;\n","var getBuiltIn = require('../internals/get-built-in');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar anObject = require('../internals/an-object');\n\n// all object keys, includes non-enumerable and symbols\nmodule.exports = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {\n var keys = getOwnPropertyNamesModule.f(anObject(it));\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;\n};\n","var has = require('../internals/has');\nvar ownKeys = require('../internals/own-keys');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\n\nmodule.exports = function (target, source) {\n var keys = ownKeys(source);\n var defineProperty = definePropertyModule.f;\n var getOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\n for (var i = 0; i < keys.length; i++) {\n var key = keys[i];\n if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));\n }\n};\n","var fails = require('../internals/fails');\n\nvar replacement = /#|\\.prototype\\./;\n\nvar isForced = function (feature, detection) {\n var value = data[normalize(feature)];\n return value == POLYFILL ? true\n : value == NATIVE ? false\n : typeof detection == 'function' ? fails(detection)\n : !!detection;\n};\n\nvar normalize = isForced.normalize = function (string) {\n return String(string).replace(replacement, '.').toLowerCase();\n};\n\nvar data = isForced.data = {};\nvar NATIVE = isForced.NATIVE = 'N';\nvar POLYFILL = isForced.POLYFILL = 'P';\n\nmodule.exports = isForced;\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar setGlobal = require('../internals/set-global');\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\nvar isForced = require('../internals/is-forced');\n\n/*\n options.target - name of the target object\n options.global - target is the global object\n options.stat - export as static methods of target\n options.proto - export as prototype methods of target\n options.real - real prototype method for the `pure` version\n options.forced - export even if the native feature is available\n options.bind - bind methods to the target, required for the `pure` version\n options.wrap - wrap constructors to preventing global pollution, required for the `pure` version\n options.unsafe - use the simple assignment of property instead of delete + defineProperty\n options.sham - add a flag to not completely full polyfills\n options.enumerable - export as enumerable property\n options.noTargetGet - prevent calling a getter on target\n*/\nmodule.exports = function (options, source) {\n var TARGET = options.target;\n var GLOBAL = options.global;\n var STATIC = options.stat;\n var FORCED, target, key, targetProperty, sourceProperty, descriptor;\n if (GLOBAL) {\n target = global;\n } else if (STATIC) {\n target = global[TARGET] || setGlobal(TARGET, {});\n } else {\n target = (global[TARGET] || {}).prototype;\n }\n if (target) for (key in source) {\n sourceProperty = source[key];\n if (options.noTargetGet) {\n descriptor = getOwnPropertyDescriptor(target, key);\n targetProperty = descriptor && descriptor.value;\n } else targetProperty = target[key];\n FORCED = isForced(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);\n // contained in target\n if (!FORCED && targetProperty !== undefined) {\n if (typeof sourceProperty === typeof targetProperty) continue;\n copyConstructorProperties(sourceProperty, targetProperty);\n }\n // add a flag to not completely full polyfills\n if (options.sham || (targetProperty && targetProperty.sham)) {\n createNonEnumerableProperty(sourceProperty, 'sham', true);\n }\n // extend global\n redefine(target, key, sourceProperty, options);\n }\n};\n","module.exports = function (it) {\n if (typeof it != 'function') {\n throw TypeError(String(it) + ' is not a function');\n } return it;\n};\n","var aFunction = require('../internals/a-function');\n\n// optional / simple context binding\nmodule.exports = function (fn, that, length) {\n aFunction(fn);\n if (that === undefined) return fn;\n switch (length) {\n case 0: return function () {\n return fn.call(that);\n };\n case 1: return function (a) {\n return fn.call(that, a);\n };\n case 2: return function (a, b) {\n return fn.call(that, a, b);\n };\n case 3: return function (a, b, c) {\n return fn.call(that, a, b, c);\n };\n }\n return function (/* ...args */) {\n return fn.apply(that, arguments);\n };\n};\n","var requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `ToObject` abstract operation\n// https://tc39.es/ecma262/#sec-toobject\nmodule.exports = function (argument) {\n return Object(requireObjectCoercible(argument));\n};\n","var classof = require('../internals/classof-raw');\n\n// `IsArray` abstract operation\n// https://tc39.es/ecma262/#sec-isarray\nmodule.exports = Array.isArray || function isArray(arg) {\n return classof(arg) == 'Array';\n};\n","var fails = require('../internals/fails');\n\nmodule.exports = !!Object.getOwnPropertySymbols && !fails(function () {\n // Chrome 38 Symbol has incorrect toString conversion\n // eslint-disable-next-line no-undef\n return !String(Symbol());\n});\n","var NATIVE_SYMBOL = require('../internals/native-symbol');\n\nmodule.exports = NATIVE_SYMBOL\n // eslint-disable-next-line no-undef\n && !Symbol.sham\n // eslint-disable-next-line no-undef\n && typeof Symbol.iterator == 'symbol';\n","var global = require('../internals/global');\nvar shared = require('../internals/shared');\nvar has = require('../internals/has');\nvar uid = require('../internals/uid');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\n\nvar WellKnownSymbolsStore = shared('wks');\nvar Symbol = global.Symbol;\nvar createWellKnownSymbol = USE_SYMBOL_AS_UID ? Symbol : Symbol && Symbol.withoutSetter || uid;\n\nmodule.exports = function (name) {\n if (!has(WellKnownSymbolsStore, name)) {\n if (NATIVE_SYMBOL && has(Symbol, name)) WellKnownSymbolsStore[name] = Symbol[name];\n else WellKnownSymbolsStore[name] = createWellKnownSymbol('Symbol.' + name);\n } return WellKnownSymbolsStore[name];\n};\n","var isObject = require('../internals/is-object');\nvar isArray = require('../internals/is-array');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `ArraySpeciesCreate` abstract operation\n// https://tc39.es/ecma262/#sec-arrayspeciescreate\nmodule.exports = function (originalArray, length) {\n var C;\n if (isArray(originalArray)) {\n C = originalArray.constructor;\n // cross-realm fallback\n if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;\n else if (isObject(C)) {\n C = C[SPECIES];\n if (C === null) C = undefined;\n }\n } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);\n};\n","var bind = require('../internals/function-bind-context');\nvar IndexedObject = require('../internals/indexed-object');\nvar toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar arraySpeciesCreate = require('../internals/array-species-create');\n\nvar push = [].push;\n\n// `Array.prototype.{ forEach, map, filter, some, every, find, findIndex, filterOut }` methods implementation\nvar createMethod = function (TYPE) {\n var IS_MAP = TYPE == 1;\n var IS_FILTER = TYPE == 2;\n var IS_SOME = TYPE == 3;\n var IS_EVERY = TYPE == 4;\n var IS_FIND_INDEX = TYPE == 6;\n var IS_FILTER_OUT = TYPE == 7;\n var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;\n return function ($this, callbackfn, that, specificCreate) {\n var O = toObject($this);\n var self = IndexedObject(O);\n var boundFunction = bind(callbackfn, that, 3);\n var length = toLength(self.length);\n var index = 0;\n var create = specificCreate || arraySpeciesCreate;\n var target = IS_MAP ? create($this, length) : IS_FILTER || IS_FILTER_OUT ? create($this, 0) : undefined;\n var value, result;\n for (;length > index; index++) if (NO_HOLES || index in self) {\n value = self[index];\n result = boundFunction(value, index, O);\n if (TYPE) {\n if (IS_MAP) target[index] = result; // map\n else if (result) switch (TYPE) {\n case 3: return true; // some\n case 5: return value; // find\n case 6: return index; // findIndex\n case 2: push.call(target, value); // filter\n } else switch (TYPE) {\n case 4: return false; // every\n case 7: push.call(target, value); // filterOut\n }\n }\n }\n return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.forEach` method\n // https://tc39.es/ecma262/#sec-array.prototype.foreach\n forEach: createMethod(0),\n // `Array.prototype.map` method\n // https://tc39.es/ecma262/#sec-array.prototype.map\n map: createMethod(1),\n // `Array.prototype.filter` method\n // https://tc39.es/ecma262/#sec-array.prototype.filter\n filter: createMethod(2),\n // `Array.prototype.some` method\n // https://tc39.es/ecma262/#sec-array.prototype.some\n some: createMethod(3),\n // `Array.prototype.every` method\n // https://tc39.es/ecma262/#sec-array.prototype.every\n every: createMethod(4),\n // `Array.prototype.find` method\n // https://tc39.es/ecma262/#sec-array.prototype.find\n find: createMethod(5),\n // `Array.prototype.findIndex` method\n // https://tc39.es/ecma262/#sec-array.prototype.findIndex\n findIndex: createMethod(6),\n // `Array.prototype.filterOut` method\n // https://github.com/tc39/proposal-array-filtering\n filterOut: createMethod(7)\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('navigator', 'userAgent') || '';\n","var global = require('../internals/global');\nvar userAgent = require('../internals/engine-user-agent');\n\nvar process = global.process;\nvar versions = process && process.versions;\nvar v8 = versions && versions.v8;\nvar match, version;\n\nif (v8) {\n match = v8.split('.');\n version = match[0] + match[1];\n} else if (userAgent) {\n match = userAgent.match(/Edge\\/(\\d+)/);\n if (!match || match[1] >= 74) {\n match = userAgent.match(/Chrome\\/(\\d+)/);\n if (match) version = match[1];\n }\n}\n\nmodule.exports = version && +version;\n","var fails = require('../internals/fails');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (METHOD_NAME) {\n // We can't use this feature detection in V8 since it causes\n // deoptimization and serious performance degradation\n // https://github.com/zloirock/core-js/issues/677\n return V8_VERSION >= 51 || !fails(function () {\n var array = [];\n var constructor = array.constructor = {};\n constructor[SPECIES] = function () {\n return { foo: 1 };\n };\n return array[METHOD_NAME](Boolean).foo !== 1;\n });\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\n\nvar defineProperty = Object.defineProperty;\nvar cache = {};\n\nvar thrower = function (it) { throw it; };\n\nmodule.exports = function (METHOD_NAME, options) {\n if (has(cache, METHOD_NAME)) return cache[METHOD_NAME];\n if (!options) options = {};\n var method = [][METHOD_NAME];\n var ACCESSORS = has(options, 'ACCESSORS') ? options.ACCESSORS : false;\n var argument0 = has(options, 0) ? options[0] : thrower;\n var argument1 = has(options, 1) ? options[1] : undefined;\n\n return cache[METHOD_NAME] = !!method && !fails(function () {\n if (ACCESSORS && !DESCRIPTORS) return true;\n var O = { length: -1 };\n\n if (ACCESSORS) defineProperty(O, 1, { enumerable: true, get: thrower });\n else O[1] = 1;\n\n method.call(O, argument0, argument1);\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $filter = require('../internals/array-iteration').filter;\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('filter');\n// Edge 14- issue\nvar USES_TO_LENGTH = arrayMethodUsesToLength('filter');\n\n// `Array.prototype.filter` method\n// https://tc39.es/ecma262/#sec-array.prototype.filter\n// with adding support of @@species\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n filter: function filter(callbackfn /* , thisArg */) {\n return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","'use strict';\nvar toPrimitive = require('../internals/to-primitive');\nvar definePropertyModule = require('../internals/object-define-property');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\n\nmodule.exports = function (object, key, value) {\n var propertyKey = toPrimitive(key);\n if (propertyKey in object) definePropertyModule.f(object, propertyKey, createPropertyDescriptor(0, value));\n else object[propertyKey] = value;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toInteger = require('../internals/to-integer');\nvar toLength = require('../internals/to-length');\nvar toObject = require('../internals/to-object');\nvar arraySpeciesCreate = require('../internals/array-species-create');\nvar createProperty = require('../internals/create-property');\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('splice');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('splice', { ACCESSORS: true, 0: 0, 1: 2 });\n\nvar max = Math.max;\nvar min = Math.min;\nvar MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;\nvar MAXIMUM_ALLOWED_LENGTH_EXCEEDED = 'Maximum allowed length exceeded';\n\n// `Array.prototype.splice` method\n// https://tc39.es/ecma262/#sec-array.prototype.splice\n// with adding support of @@species\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n splice: function splice(start, deleteCount /* , ...items */) {\n var O = toObject(this);\n var len = toLength(O.length);\n var actualStart = toAbsoluteIndex(start, len);\n var argumentsLength = arguments.length;\n var insertCount, actualDeleteCount, A, k, from, to;\n if (argumentsLength === 0) {\n insertCount = actualDeleteCount = 0;\n } else if (argumentsLength === 1) {\n insertCount = 0;\n actualDeleteCount = len - actualStart;\n } else {\n insertCount = argumentsLength - 2;\n actualDeleteCount = min(max(toInteger(deleteCount), 0), len - actualStart);\n }\n if (len + insertCount - actualDeleteCount > MAX_SAFE_INTEGER) {\n throw TypeError(MAXIMUM_ALLOWED_LENGTH_EXCEEDED);\n }\n A = arraySpeciesCreate(O, actualDeleteCount);\n for (k = 0; k < actualDeleteCount; k++) {\n from = actualStart + k;\n if (from in O) createProperty(A, k, O[from]);\n }\n A.length = actualDeleteCount;\n if (insertCount < actualDeleteCount) {\n for (k = actualStart; k < len - actualDeleteCount; k++) {\n from = k + actualDeleteCount;\n to = k + insertCount;\n if (from in O) O[to] = O[from];\n else delete O[to];\n }\n for (k = len; k > len - actualDeleteCount + insertCount; k--) delete O[k - 1];\n } else if (insertCount > actualDeleteCount) {\n for (k = len - actualDeleteCount; k > actualStart; k--) {\n from = k + actualDeleteCount - 1;\n to = k + insertCount - 1;\n if (from in O) O[to] = O[from];\n else delete O[to];\n }\n }\n for (k = 0; k < insertCount; k++) {\n O[k + actualStart] = arguments[k + 2];\n }\n O.length = len - actualDeleteCount + insertCount;\n return A;\n }\n});\n","var internalObjectKeys = require('../internals/object-keys-internal');\nvar enumBugKeys = require('../internals/enum-bug-keys');\n\n// `Object.keys` method\n// https://tc39.es/ecma262/#sec-object.keys\nmodule.exports = Object.keys || function keys(O) {\n return internalObjectKeys(O, enumBugKeys);\n};\n","'use strict';\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fails = require('../internals/fails');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar toObject = require('../internals/to-object');\nvar IndexedObject = require('../internals/indexed-object');\n\nvar nativeAssign = Object.assign;\nvar defineProperty = Object.defineProperty;\n\n// `Object.assign` method\n// https://tc39.es/ecma262/#sec-object.assign\nmodule.exports = !nativeAssign || fails(function () {\n // should have correct order of operations (Edge bug)\n if (DESCRIPTORS && nativeAssign({ b: 1 }, nativeAssign(defineProperty({}, 'a', {\n enumerable: true,\n get: function () {\n defineProperty(this, 'b', {\n value: 3,\n enumerable: false\n });\n }\n }), { b: 2 })).b !== 1) return true;\n // should work with symbols and should have deterministic property order (V8 bug)\n var A = {};\n var B = {};\n // eslint-disable-next-line no-undef\n var symbol = Symbol();\n var alphabet = 'abcdefghijklmnopqrst';\n A[symbol] = 7;\n alphabet.split('').forEach(function (chr) { B[chr] = chr; });\n return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;\n}) ? function assign(target, source) { // eslint-disable-line no-unused-vars\n var T = toObject(target);\n var argumentsLength = arguments.length;\n var index = 1;\n var getOwnPropertySymbols = getOwnPropertySymbolsModule.f;\n var propertyIsEnumerable = propertyIsEnumerableModule.f;\n while (argumentsLength > index) {\n var S = IndexedObject(arguments[index++]);\n var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);\n var length = keys.length;\n var j = 0;\n var key;\n while (length > j) {\n key = keys[j++];\n if (!DESCRIPTORS || propertyIsEnumerable.call(S, key)) T[key] = S[key];\n }\n } return T;\n} : nativeAssign;\n","var $ = require('../internals/export');\nvar assign = require('../internals/object-assign');\n\n// `Object.assign` method\n// https://tc39.es/ecma262/#sec-object.assign\n$({ target: 'Object', stat: true, forced: Object.assign !== assign }, {\n assign: assign\n});\n","var $ = require('../internals/export');\nvar toObject = require('../internals/to-object');\nvar nativeKeys = require('../internals/object-keys');\nvar fails = require('../internals/fails');\n\nvar FAILS_ON_PRIMITIVES = fails(function () { nativeKeys(1); });\n\n// `Object.keys` method\n// https://tc39.es/ecma262/#sec-object.keys\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {\n keys: function keys(it) {\n return nativeKeys(toObject(it));\n }\n});\n","'use strict';\nvar anObject = require('../internals/an-object');\n\n// `RegExp.prototype.flags` getter implementation\n// https://tc39.es/ecma262/#sec-get-regexp.prototype.flags\nmodule.exports = function () {\n var that = anObject(this);\n var result = '';\n if (that.global) result += 'g';\n if (that.ignoreCase) result += 'i';\n if (that.multiline) result += 'm';\n if (that.dotAll) result += 's';\n if (that.unicode) result += 'u';\n if (that.sticky) result += 'y';\n return result;\n};\n","'use strict';\n\nvar fails = require('./fails');\n\n// babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError,\n// so we use an intermediate function.\nfunction RE(s, f) {\n return RegExp(s, f);\n}\n\nexports.UNSUPPORTED_Y = fails(function () {\n // babel-minify transpiles RegExp('a', 'y') -> /a/y and it causes SyntaxError\n var re = RE('a', 'y');\n re.lastIndex = 2;\n return re.exec('abcd') != null;\n});\n\nexports.BROKEN_CARET = fails(function () {\n // https://bugzilla.mozilla.org/show_bug.cgi?id=773687\n var re = RE('^r', 'gy');\n re.lastIndex = 2;\n return re.exec('str') != null;\n});\n","'use strict';\nvar regexpFlags = require('./regexp-flags');\nvar stickyHelpers = require('./regexp-sticky-helpers');\n\nvar nativeExec = RegExp.prototype.exec;\n// This always refers to the native implementation, because the\n// String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,\n// which loads this file before patching the method.\nvar nativeReplace = String.prototype.replace;\n\nvar patchedExec = nativeExec;\n\nvar UPDATES_LAST_INDEX_WRONG = (function () {\n var re1 = /a/;\n var re2 = /b*/g;\n nativeExec.call(re1, 'a');\n nativeExec.call(re2, 'a');\n return re1.lastIndex !== 0 || re2.lastIndex !== 0;\n})();\n\nvar UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y || stickyHelpers.BROKEN_CARET;\n\n// nonparticipating capturing group, copied from es5-shim's String#split patch.\nvar NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;\n\nvar PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED || UNSUPPORTED_Y;\n\nif (PATCH) {\n patchedExec = function exec(str) {\n var re = this;\n var lastIndex, reCopy, match, i;\n var sticky = UNSUPPORTED_Y && re.sticky;\n var flags = regexpFlags.call(re);\n var source = re.source;\n var charsAdded = 0;\n var strCopy = str;\n\n if (sticky) {\n flags = flags.replace('y', '');\n if (flags.indexOf('g') === -1) {\n flags += 'g';\n }\n\n strCopy = String(str).slice(re.lastIndex);\n // Support anchored sticky behavior.\n if (re.lastIndex > 0 && (!re.multiline || re.multiline && str[re.lastIndex - 1] !== '\\n')) {\n source = '(?: ' + source + ')';\n strCopy = ' ' + strCopy;\n charsAdded++;\n }\n // ^(? + rx + ) is needed, in combination with some str slicing, to\n // simulate the 'y' flag.\n reCopy = new RegExp('^(?:' + source + ')', flags);\n }\n\n if (NPCG_INCLUDED) {\n reCopy = new RegExp('^' + source + '$(?!\\\\s)', flags);\n }\n if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;\n\n match = nativeExec.call(sticky ? reCopy : re, strCopy);\n\n if (sticky) {\n if (match) {\n match.input = match.input.slice(charsAdded);\n match[0] = match[0].slice(charsAdded);\n match.index = re.lastIndex;\n re.lastIndex += match[0].length;\n } else re.lastIndex = 0;\n } else if (UPDATES_LAST_INDEX_WRONG && match) {\n re.lastIndex = re.global ? match.index + match[0].length : lastIndex;\n }\n if (NPCG_INCLUDED && match && match.length > 1) {\n // Fix browsers whose `exec` methods don't consistently return `undefined`\n // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/\n nativeReplace.call(match[0], reCopy, function () {\n for (i = 1; i < arguments.length - 2; i++) {\n if (arguments[i] === undefined) match[i] = undefined;\n }\n });\n }\n\n return match;\n };\n}\n\nmodule.exports = patchedExec;\n","'use strict';\nvar $ = require('../internals/export');\nvar exec = require('../internals/regexp-exec');\n\n// `RegExp.prototype.exec` method\n// https://tc39.es/ecma262/#sec-regexp.prototype.exec\n$({ target: 'RegExp', proto: true, forced: /./.exec !== exec }, {\n exec: exec\n});\n","'use strict';\n// TODO: Remove from `core-js@4` since it's moved to entry points\nrequire('../modules/es.regexp.exec');\nvar redefine = require('../internals/redefine');\nvar fails = require('../internals/fails');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar regexpExec = require('../internals/regexp-exec');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nvar SPECIES = wellKnownSymbol('species');\n\nvar REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {\n // #replace needs built-in support for named groups.\n // #match works fine because it just return the exec results, even if it has\n // a \"grops\" property.\n var re = /./;\n re.exec = function () {\n var result = [];\n result.groups = { a: '7' };\n return result;\n };\n return ''.replace(re, '$') !== '7';\n});\n\n// IE <= 11 replaces $0 with the whole match, as if it was $&\n// https://stackoverflow.com/questions/6024666/getting-ie-to-replace-a-regex-with-the-literal-string-0\nvar REPLACE_KEEPS_$0 = (function () {\n return 'a'.replace(/./, '$0') === '$0';\n})();\n\nvar REPLACE = wellKnownSymbol('replace');\n// Safari <= 13.0.3(?) substitutes nth capture where n>m with an empty string\nvar REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = (function () {\n if (/./[REPLACE]) {\n return /./[REPLACE]('a', '$0') === '';\n }\n return false;\n})();\n\n// Chrome 51 has a buggy \"split\" implementation when RegExp#exec !== nativeExec\n// Weex JS has frozen built-in prototypes, so use try / catch wrapper\nvar SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {\n var re = /(?:)/;\n var originalExec = re.exec;\n re.exec = function () { return originalExec.apply(this, arguments); };\n var result = 'ab'.split(re);\n return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';\n});\n\nmodule.exports = function (KEY, length, exec, sham) {\n var SYMBOL = wellKnownSymbol(KEY);\n\n var DELEGATES_TO_SYMBOL = !fails(function () {\n // String methods call symbol-named RegEp methods\n var O = {};\n O[SYMBOL] = function () { return 7; };\n return ''[KEY](O) != 7;\n });\n\n var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {\n // Symbol-named RegExp methods call .exec\n var execCalled = false;\n var re = /a/;\n\n if (KEY === 'split') {\n // We can't use real regex here since it causes deoptimization\n // and serious performance degradation in V8\n // https://github.com/zloirock/core-js/issues/306\n re = {};\n // RegExp[@@split] doesn't call the regex's exec method, but first creates\n // a new one. We need to return the patched regex when creating the new one.\n re.constructor = {};\n re.constructor[SPECIES] = function () { return re; };\n re.flags = '';\n re[SYMBOL] = /./[SYMBOL];\n }\n\n re.exec = function () { execCalled = true; return null; };\n\n re[SYMBOL]('');\n return !execCalled;\n });\n\n if (\n !DELEGATES_TO_SYMBOL ||\n !DELEGATES_TO_EXEC ||\n (KEY === 'replace' && !(\n REPLACE_SUPPORTS_NAMED_GROUPS &&\n REPLACE_KEEPS_$0 &&\n !REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE\n )) ||\n (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)\n ) {\n var nativeRegExpMethod = /./[SYMBOL];\n var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {\n if (regexp.exec === regexpExec) {\n if (DELEGATES_TO_SYMBOL && !forceStringMethod) {\n // The native String method already delegates to @@method (this\n // polyfilled function), leasing to infinite recursion.\n // We avoid it by directly calling the native @@method method.\n return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };\n }\n return { done: true, value: nativeMethod.call(str, regexp, arg2) };\n }\n return { done: false };\n }, {\n REPLACE_KEEPS_$0: REPLACE_KEEPS_$0,\n REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE: REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE\n });\n var stringMethod = methods[0];\n var regexMethod = methods[1];\n\n redefine(String.prototype, KEY, stringMethod);\n redefine(RegExp.prototype, SYMBOL, length == 2\n // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)\n // 21.2.5.11 RegExp.prototype[@@split](string, limit)\n ? function (string, arg) { return regexMethod.call(string, this, arg); }\n // 21.2.5.6 RegExp.prototype[@@match](string)\n // 21.2.5.9 RegExp.prototype[@@search](string)\n : function (string) { return regexMethod.call(string, this); }\n );\n }\n\n if (sham) createNonEnumerableProperty(RegExp.prototype[SYMBOL], 'sham', true);\n};\n","// `SameValue` abstract operation\n// https://tc39.es/ecma262/#sec-samevalue\nmodule.exports = Object.is || function is(x, y) {\n // eslint-disable-next-line no-self-compare\n return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;\n};\n","var classof = require('./classof-raw');\nvar regexpExec = require('./regexp-exec');\n\n// `RegExpExec` abstract operation\n// https://tc39.es/ecma262/#sec-regexpexec\nmodule.exports = function (R, S) {\n var exec = R.exec;\n if (typeof exec === 'function') {\n var result = exec.call(R, S);\n if (typeof result !== 'object') {\n throw TypeError('RegExp exec method returned something other than an Object or null');\n }\n return result;\n }\n\n if (classof(R) !== 'RegExp') {\n throw TypeError('RegExp#exec called on incompatible receiver');\n }\n\n return regexpExec.call(R, S);\n};\n\n","'use strict';\nvar fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');\nvar anObject = require('../internals/an-object');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar sameValue = require('../internals/same-value');\nvar regExpExec = require('../internals/regexp-exec-abstract');\n\n// @@search logic\nfixRegExpWellKnownSymbolLogic('search', 1, function (SEARCH, nativeSearch, maybeCallNative) {\n return [\n // `String.prototype.search` method\n // https://tc39.es/ecma262/#sec-string.prototype.search\n function search(regexp) {\n var O = requireObjectCoercible(this);\n var searcher = regexp == undefined ? undefined : regexp[SEARCH];\n return searcher !== undefined ? searcher.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));\n },\n // `RegExp.prototype[@@search]` method\n // https://tc39.es/ecma262/#sec-regexp.prototype-@@search\n function (regexp) {\n var res = maybeCallNative(nativeSearch, regexp, this);\n if (res.done) return res.value;\n\n var rx = anObject(regexp);\n var S = String(this);\n\n var previousLastIndex = rx.lastIndex;\n if (!sameValue(previousLastIndex, 0)) rx.lastIndex = 0;\n var result = regExpExec(rx, S);\n if (!sameValue(rx.lastIndex, previousLastIndex)) rx.lastIndex = previousLastIndex;\n return result === null ? -1 : result.index;\n }\n ];\n});\n","// iterable DOM collections\n// flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods\nmodule.exports = {\n CSSRuleList: 0,\n CSSStyleDeclaration: 0,\n CSSValueList: 0,\n ClientRectList: 0,\n DOMRectList: 0,\n DOMStringList: 0,\n DOMTokenList: 1,\n DataTransferItemList: 0,\n FileList: 0,\n HTMLAllCollection: 0,\n HTMLCollection: 0,\n HTMLFormElement: 0,\n HTMLSelectElement: 0,\n MediaList: 0,\n MimeTypeArray: 0,\n NamedNodeMap: 0,\n NodeList: 1,\n PaintRequestList: 0,\n Plugin: 0,\n PluginArray: 0,\n SVGLengthList: 0,\n SVGNumberList: 0,\n SVGPathSegList: 0,\n SVGPointList: 0,\n SVGStringList: 0,\n SVGTransformList: 0,\n SourceBufferList: 0,\n StyleSheetList: 0,\n TextTrackCueList: 0,\n TextTrackList: 0,\n TouchList: 0\n};\n","'use strict';\nvar fails = require('../internals/fails');\n\nmodule.exports = function (METHOD_NAME, argument) {\n var method = [][METHOD_NAME];\n return !!method && fails(function () {\n // eslint-disable-next-line no-useless-call,no-throw-literal\n method.call(null, argument || function () { throw 1; }, 1);\n });\n};\n","'use strict';\nvar $forEach = require('../internals/array-iteration').forEach;\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar STRICT_METHOD = arrayMethodIsStrict('forEach');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('forEach');\n\n// `Array.prototype.forEach` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.foreach\nmodule.exports = (!STRICT_METHOD || !USES_TO_LENGTH) ? function forEach(callbackfn /* , thisArg */) {\n return $forEach(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n} : [].forEach;\n","var global = require('../internals/global');\nvar DOMIterables = require('../internals/dom-iterables');\nvar forEach = require('../internals/array-for-each');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\n\nfor (var COLLECTION_NAME in DOMIterables) {\n var Collection = global[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype && CollectionPrototype.forEach !== forEach) try {\n createNonEnumerableProperty(CollectionPrototype, 'forEach', forEach);\n } catch (error) {\n CollectionPrototype.forEach = forEach;\n }\n}\n","'use strict';\nvar $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar isArray = require('../internals/is-array');\nvar isObject = require('../internals/is-object');\nvar toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar createProperty = require('../internals/create-property');\nvar arraySpeciesCreate = require('../internals/array-species-create');\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');\nvar MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;\nvar MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';\n\n// We can't use this feature detection in V8 since it causes\n// deoptimization and serious performance degradation\n// https://github.com/zloirock/core-js/issues/679\nvar IS_CONCAT_SPREADABLE_SUPPORT = V8_VERSION >= 51 || !fails(function () {\n var array = [];\n array[IS_CONCAT_SPREADABLE] = false;\n return array.concat()[0] !== array;\n});\n\nvar SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');\n\nvar isConcatSpreadable = function (O) {\n if (!isObject(O)) return false;\n var spreadable = O[IS_CONCAT_SPREADABLE];\n return spreadable !== undefined ? !!spreadable : isArray(O);\n};\n\nvar FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;\n\n// `Array.prototype.concat` method\n// https://tc39.es/ecma262/#sec-array.prototype.concat\n// with adding support of @@isConcatSpreadable and @@species\n$({ target: 'Array', proto: true, forced: FORCED }, {\n concat: function concat(arg) { // eslint-disable-line no-unused-vars\n var O = toObject(this);\n var A = arraySpeciesCreate(O, 0);\n var n = 0;\n var i, k, length, len, E;\n for (i = -1, length = arguments.length; i < length; i++) {\n E = i === -1 ? O : arguments[i];\n if (isConcatSpreadable(E)) {\n len = toLength(E.length);\n if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);\n for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);\n } else {\n if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);\n createProperty(A, n++, E);\n }\n }\n A.length = n;\n return A;\n }\n});\n","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});","export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nif (typeof global.setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n}\nif (typeof global.clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n}\n\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nexport function nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nexport var title = 'browser';\nexport var platform = 'browser';\nexport var browser = true;\nexport var env = {};\nexport var argv = [];\nexport var version = ''; // empty string to avoid regexp issues\nexport var versions = {};\nexport var release = {};\nexport var config = {};\n\nfunction noop() {}\n\nexport var on = noop;\nexport var addListener = noop;\nexport var once = noop;\nexport var off = noop;\nexport var removeListener = noop;\nexport var removeAllListeners = noop;\nexport var emit = noop;\n\nexport function binding(name) {\n throw new Error('process.binding is not supported');\n}\n\nexport function cwd () { return '/' }\nexport function chdir (dir) {\n throw new Error('process.chdir is not supported');\n};\nexport function umask() { return 0; }\n\n// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js\nvar performance = global.performance || {}\nvar performanceNow =\n performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function(){ return (new Date()).getTime() }\n\n// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nexport function hrtime(previousTimestamp){\n var clocktime = performanceNow.call(performance)*1e-3\n var seconds = Math.floor(clocktime)\n var nanoseconds = Math.floor((clocktime%1)*1e9)\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0]\n nanoseconds = nanoseconds - previousTimestamp[1]\n if (nanoseconds<0) {\n seconds--\n nanoseconds += 1e9\n }\n }\n return [seconds,nanoseconds]\n}\n\nvar startTime = new Date();\nexport function uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1000;\n}\n\nexport default {\n nextTick: nextTick,\n title: title,\n browser: browser,\n env: env,\n argv: argv,\n version: version,\n versions: versions,\n on: on,\n addListener: addListener,\n once: once,\n off: off,\n removeListener: removeListener,\n removeAllListeners: removeAllListeners,\n emit: emit,\n binding: binding,\n cwd: cwd,\n chdir: chdir,\n umask: umask,\n hrtime: hrtime,\n platform: platform,\n release: release,\n config: config,\n uptime: uptime\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar test = {};\n\ntest[TO_STRING_TAG] = 'z';\n\nmodule.exports = String(test) === '[object z]';\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classofRaw = require('../internals/classof-raw');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n// ES3 wrong here\nvar CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';\n\n// fallback for IE11 Script Access Denied error\nvar tryGet = function (it, key) {\n try {\n return it[key];\n } catch (error) { /* empty */ }\n};\n\n// getting tag from ES6+ `Object.prototype.toString`\nmodule.exports = TO_STRING_TAG_SUPPORT ? classofRaw : function (it) {\n var O, tag, result;\n return it === undefined ? 'Undefined' : it === null ? 'Null'\n // @@toStringTag case\n : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG)) == 'string' ? tag\n // builtinTag case\n : CORRECT_ARGUMENTS ? classofRaw(O)\n // ES3 arguments fallback\n : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;\n};\n","'use strict';\nvar TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar classof = require('../internals/classof');\n\n// `Object.prototype.toString` method implementation\n// https://tc39.es/ecma262/#sec-object.prototype.tostring\nmodule.exports = TO_STRING_TAG_SUPPORT ? {}.toString : function toString() {\n return '[object ' + classof(this) + ']';\n};\n","var TO_STRING_TAG_SUPPORT = require('../internals/to-string-tag-support');\nvar redefine = require('../internals/redefine');\nvar toString = require('../internals/object-to-string');\n\n// `Object.prototype.toString` method\n// https://tc39.es/ecma262/#sec-object.prototype.tostring\nif (!TO_STRING_TAG_SUPPORT) {\n redefine(Object.prototype, 'toString', toString, { unsafe: true });\n}\n","'use strict';\nvar redefine = require('../internals/redefine');\nvar anObject = require('../internals/an-object');\nvar fails = require('../internals/fails');\nvar flags = require('../internals/regexp-flags');\n\nvar TO_STRING = 'toString';\nvar RegExpPrototype = RegExp.prototype;\nvar nativeToString = RegExpPrototype[TO_STRING];\n\nvar NOT_GENERIC = fails(function () { return nativeToString.call({ source: 'a', flags: 'b' }) != '/a/b'; });\n// FF44- RegExp#toString has a wrong name\nvar INCORRECT_NAME = nativeToString.name != TO_STRING;\n\n// `RegExp.prototype.toString` method\n// https://tc39.es/ecma262/#sec-regexp.prototype.tostring\nif (NOT_GENERIC || INCORRECT_NAME) {\n redefine(RegExp.prototype, TO_STRING, function toString() {\n var R = anObject(this);\n var p = String(R.source);\n var rf = R.flags;\n var f = String(rf === undefined && R instanceof RegExp && !('flags' in RegExpPrototype) ? flags.call(R) : rf);\n return '/' + p + '/' + f;\n }, { unsafe: true });\n}\n","var DESCRIPTORS = require('../internals/descriptors');\nvar defineProperty = require('../internals/object-define-property').f;\n\nvar FunctionPrototype = Function.prototype;\nvar FunctionPrototypeToString = FunctionPrototype.toString;\nvar nameRE = /^\\s*function ([^ (]*)/;\nvar NAME = 'name';\n\n// Function instances `.name` property\n// https://tc39.es/ecma262/#sec-function-instances-name\nif (DESCRIPTORS && !(NAME in FunctionPrototype)) {\n defineProperty(FunctionPrototype, NAME, {\n configurable: true,\n get: function () {\n try {\n return FunctionPrototypeToString.call(this).match(nameRE)[1];\n } catch (error) {\n return '';\n }\n }\n });\n}\n","var fails = require('../internals/fails');\n\nmodule.exports = !fails(function () {\n function F() { /* empty */ }\n F.prototype.constructor = null;\n return Object.getPrototypeOf(new F()) !== F.prototype;\n});\n","var has = require('../internals/has');\nvar toObject = require('../internals/to-object');\nvar sharedKey = require('../internals/shared-key');\nvar CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');\n\nvar IE_PROTO = sharedKey('IE_PROTO');\nvar ObjectPrototype = Object.prototype;\n\n// `Object.getPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.getprototypeof\nmodule.exports = CORRECT_PROTOTYPE_GETTER ? Object.getPrototypeOf : function (O) {\n O = toObject(O);\n if (has(O, IE_PROTO)) return O[IE_PROTO];\n if (typeof O.constructor == 'function' && O instanceof O.constructor) {\n return O.constructor.prototype;\n } return O instanceof Object ? ObjectPrototype : null;\n};\n","var $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar toObject = require('../internals/to-object');\nvar nativeGetPrototypeOf = require('../internals/object-get-prototype-of');\nvar CORRECT_PROTOTYPE_GETTER = require('../internals/correct-prototype-getter');\n\nvar FAILS_ON_PRIMITIVES = fails(function () { nativeGetPrototypeOf(1); });\n\n// `Object.getPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.getprototypeof\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !CORRECT_PROTOTYPE_GETTER }, {\n getPrototypeOf: function getPrototypeOf(it) {\n return nativeGetPrototypeOf(toObject(it));\n }\n});\n\n","var $ = require('../internals/export');\nvar ownKeys = require('../internals/own-keys');\n\n// `Reflect.ownKeys` method\n// https://tc39.es/ecma262/#sec-reflect.ownkeys\n$({ target: 'Reflect', stat: true }, {\n ownKeys: ownKeys\n});\n","'use strict';\n\nvar domain;\n\n// This constructor is used to store event handlers. Instantiating this is\n// faster than explicitly calling `Object.create(null)` to get a \"clean\" empty\n// object (tested with v8 v4.9).\nfunction EventHandlers() {}\nEventHandlers.prototype = Object.create(null);\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nexport default EventEmitter;\nexport {EventEmitter};\n\n// nodejs oddity\n// require('events') === require('events').EventEmitter\nEventEmitter.EventEmitter = EventEmitter\n\nEventEmitter.usingDomains = false;\n\nEventEmitter.prototype.domain = undefined;\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nEventEmitter.defaultMaxListeners = 10;\n\nEventEmitter.init = function() {\n this.domain = null;\n if (EventEmitter.usingDomains) {\n // if there is an active domain, then attach to it.\n if (domain.active && !(this instanceof domain.Domain)) {\n this.domain = domain.active;\n }\n }\n\n if (!this._events || this._events === Object.getPrototypeOf(this)._events) {\n this._events = new EventHandlers();\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || isNaN(n))\n throw new TypeError('\"n\" argument must be a positive number');\n this._maxListeners = n;\n return this;\n};\n\nfunction $getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return $getMaxListeners(this);\n};\n\n// These standalone emit* functions are used to optimize calling of event\n// handlers for fast cases because emit() itself often has a variable number of\n// arguments and can be deoptimized because of that. These functions always have\n// the same number of arguments and thus do not get deoptimized, so the code\n// inside them can execute faster.\nfunction emitNone(handler, isFn, self) {\n if (isFn)\n handler.call(self);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self);\n }\n}\nfunction emitOne(handler, isFn, self, arg1) {\n if (isFn)\n handler.call(self, arg1);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1);\n }\n}\nfunction emitTwo(handler, isFn, self, arg1, arg2) {\n if (isFn)\n handler.call(self, arg1, arg2);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1, arg2);\n }\n}\nfunction emitThree(handler, isFn, self, arg1, arg2, arg3) {\n if (isFn)\n handler.call(self, arg1, arg2, arg3);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].call(self, arg1, arg2, arg3);\n }\n}\n\nfunction emitMany(handler, isFn, self, args) {\n if (isFn)\n handler.apply(self, args);\n else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n listeners[i].apply(self, args);\n }\n}\n\nEventEmitter.prototype.emit = function emit(type) {\n var er, handler, len, args, i, events, domain;\n var needDomainExit = false;\n var doError = (type === 'error');\n\n events = this._events;\n if (events)\n doError = (doError && events.error == null);\n else if (!doError)\n return false;\n\n domain = this.domain;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n er = arguments[1];\n if (domain) {\n if (!er)\n er = new Error('Uncaught, unspecified \"error\" event');\n er.domainEmitter = this;\n er.domain = domain;\n er.domainThrown = false;\n domain.emit('error', er);\n } else if (er instanceof Error) {\n throw er; // Unhandled 'error' event\n } else {\n // At least give some kind of context to the user\n var err = new Error('Uncaught, unspecified \"error\" event. (' + er + ')');\n err.context = er;\n throw err;\n }\n return false;\n }\n\n handler = events[type];\n\n if (!handler)\n return false;\n\n var isFn = typeof handler === 'function';\n len = arguments.length;\n switch (len) {\n // fast cases\n case 1:\n emitNone(handler, isFn, this);\n break;\n case 2:\n emitOne(handler, isFn, this, arguments[1]);\n break;\n case 3:\n emitTwo(handler, isFn, this, arguments[1], arguments[2]);\n break;\n case 4:\n emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);\n break;\n // slower\n default:\n args = new Array(len - 1);\n for (i = 1; i < len; i++)\n args[i - 1] = arguments[i];\n emitMany(handler, isFn, this, args);\n }\n\n if (needDomainExit)\n domain.exit();\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n\n events = target._events;\n if (!events) {\n events = target._events = new EventHandlers();\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (!existing) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] = prepend ? [listener, existing] :\n [existing, listener];\n } else {\n // If we've already got an array, just append.\n if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n }\n\n // Check for listener leak\n if (!existing.warned) {\n m = $getMaxListeners(target);\n if (m && m > 0 && existing.length > m) {\n existing.warned = true;\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + type + ' listeners added. ' +\n 'Use emitter.setMaxListeners() to increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n emitWarning(w);\n }\n }\n }\n\n return target;\n}\nfunction emitWarning(e) {\n typeof console.warn === 'function' ? console.warn(e) : console.log(e);\n}\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction _onceWrap(target, type, listener) {\n var fired = false;\n function g() {\n target.removeListener(type, g);\n if (!fired) {\n fired = true;\n listener.apply(target, arguments);\n }\n }\n g.listener = listener;\n return g;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// emits a 'removeListener' event iff the listener was removed\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n if (typeof listener !== 'function')\n throw new TypeError('\"listener\" argument must be a function');\n\n events = this._events;\n if (!events)\n return this;\n\n list = events[type];\n if (!list)\n return this;\n\n if (list === listener || (list.listener && list.listener === listener)) {\n if (--this._eventsCount === 0)\n this._events = new EventHandlers();\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length; i-- > 0;) {\n if (list[i] === listener ||\n (list[i].listener && list[i].listener === listener)) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (list.length === 1) {\n list[0] = undefined;\n if (--this._eventsCount === 0) {\n this._events = new EventHandlers();\n return this;\n } else {\n delete events[type];\n }\n } else {\n spliceOne(list, position);\n }\n\n if (events.removeListener)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events;\n\n events = this._events;\n if (!events)\n return this;\n\n // not listening for removeListener, no need to emit\n if (!events.removeListener) {\n if (arguments.length === 0) {\n this._events = new EventHandlers();\n this._eventsCount = 0;\n } else if (events[type]) {\n if (--this._eventsCount === 0)\n this._events = new EventHandlers();\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n for (var i = 0, key; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = new EventHandlers();\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners) {\n // LIFO order\n do {\n this.removeListener(type, listeners[listeners.length - 1]);\n } while (listeners[0]);\n }\n\n return this;\n };\n\nEventEmitter.prototype.listeners = function listeners(type) {\n var evlistener;\n var ret;\n var events = this._events;\n\n if (!events)\n ret = [];\n else {\n evlistener = events[type];\n if (!evlistener)\n ret = [];\n else if (typeof evlistener === 'function')\n ret = [evlistener.listener || evlistener];\n else\n ret = unwrapListeners(evlistener);\n }\n\n return ret;\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];\n};\n\n// About 1.5x faster than the two-arg version of Array#splice().\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)\n list[i] = list[k];\n list.pop();\n}\n\nfunction arrayClone(arr, i) {\n var copy = new Array(i);\n while (i--)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n","'use strict';\nvar $ = require('../internals/export');\nvar IndexedObject = require('../internals/indexed-object');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\n\nvar nativeJoin = [].join;\n\nvar ES3_STRINGS = IndexedObject != Object;\nvar STRICT_METHOD = arrayMethodIsStrict('join', ',');\n\n// `Array.prototype.join` method\n// https://tc39.es/ecma262/#sec-array.prototype.join\n$({ target: 'Array', proto: true, forced: ES3_STRINGS || !STRICT_METHOD }, {\n join: function join(separator) {\n return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar $map = require('../internals/array-iteration').map;\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('map');\n// FF49- issue\nvar USES_TO_LENGTH = arrayMethodUsesToLength('map');\n\n// `Array.prototype.map` method\n// https://tc39.es/ecma262/#sec-array.prototype.map\n// with adding support of @@species\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n map: function map(callbackfn /* , thisArg */) {\n return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","var isObject = require('../internals/is-object');\n\nmodule.exports = function (it) {\n if (!isObject(it) && it !== null) {\n throw TypeError(\"Can't set \" + String(it) + ' as a prototype');\n } return it;\n};\n","var anObject = require('../internals/an-object');\nvar aPossiblePrototype = require('../internals/a-possible-prototype');\n\n// `Object.setPrototypeOf` method\n// https://tc39.es/ecma262/#sec-object.setprototypeof\n// Works with __proto__ only. Old v8 can't work with null proto objects.\n/* eslint-disable no-proto */\nmodule.exports = Object.setPrototypeOf || ('__proto__' in {} ? function () {\n var CORRECT_SETTER = false;\n var test = {};\n var setter;\n try {\n setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;\n setter.call(test, []);\n CORRECT_SETTER = test instanceof Array;\n } catch (error) { /* empty */ }\n return function setPrototypeOf(O, proto) {\n anObject(O);\n aPossiblePrototype(proto);\n if (CORRECT_SETTER) setter.call(O, proto);\n else O.__proto__ = proto;\n return O;\n };\n}() : undefined);\n","var isObject = require('../internals/is-object');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\n\n// makes subclassing work correct for wrapped built-ins\nmodule.exports = function ($this, dummy, Wrapper) {\n var NewTarget, NewTargetPrototype;\n if (\n // it can work only with native `setPrototypeOf`\n setPrototypeOf &&\n // we haven't completely correct pre-ES6 way for getting `new.target`, so use this\n typeof (NewTarget = dummy.constructor) == 'function' &&\n NewTarget !== Wrapper &&\n isObject(NewTargetPrototype = NewTarget.prototype) &&\n NewTargetPrototype !== Wrapper.prototype\n ) setPrototypeOf($this, NewTargetPrototype);\n return $this;\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar definePropertyModule = require('../internals/object-define-property');\nvar anObject = require('../internals/an-object');\nvar objectKeys = require('../internals/object-keys');\n\n// `Object.defineProperties` method\n// https://tc39.es/ecma262/#sec-object.defineproperties\nmodule.exports = DESCRIPTORS ? Object.defineProperties : function defineProperties(O, Properties) {\n anObject(O);\n var keys = objectKeys(Properties);\n var length = keys.length;\n var index = 0;\n var key;\n while (length > index) definePropertyModule.f(O, key = keys[index++], Properties[key]);\n return O;\n};\n","var getBuiltIn = require('../internals/get-built-in');\n\nmodule.exports = getBuiltIn('document', 'documentElement');\n","var anObject = require('../internals/an-object');\nvar defineProperties = require('../internals/object-define-properties');\nvar enumBugKeys = require('../internals/enum-bug-keys');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar html = require('../internals/html');\nvar documentCreateElement = require('../internals/document-create-element');\nvar sharedKey = require('../internals/shared-key');\n\nvar GT = '>';\nvar LT = '<';\nvar PROTOTYPE = 'prototype';\nvar SCRIPT = 'script';\nvar IE_PROTO = sharedKey('IE_PROTO');\n\nvar EmptyConstructor = function () { /* empty */ };\n\nvar scriptTag = function (content) {\n return LT + SCRIPT + GT + content + LT + '/' + SCRIPT + GT;\n};\n\n// Create object with fake `null` prototype: use ActiveX Object with cleared prototype\nvar NullProtoObjectViaActiveX = function (activeXDocument) {\n activeXDocument.write(scriptTag(''));\n activeXDocument.close();\n var temp = activeXDocument.parentWindow.Object;\n activeXDocument = null; // avoid memory leak\n return temp;\n};\n\n// Create object with fake `null` prototype: use iframe Object with cleared prototype\nvar NullProtoObjectViaIFrame = function () {\n // Thrash, waste and sodomy: IE GC bug\n var iframe = documentCreateElement('iframe');\n var JS = 'java' + SCRIPT + ':';\n var iframeDocument;\n iframe.style.display = 'none';\n html.appendChild(iframe);\n // https://github.com/zloirock/core-js/issues/475\n iframe.src = String(JS);\n iframeDocument = iframe.contentWindow.document;\n iframeDocument.open();\n iframeDocument.write(scriptTag('document.F=Object'));\n iframeDocument.close();\n return iframeDocument.F;\n};\n\n// Check for document.domain and active x support\n// No need to use active x approach when document.domain is not set\n// see https://github.com/es-shims/es5-shim/issues/150\n// variation of https://github.com/kitcambridge/es5-shim/commit/4f738ac066346\n// avoid IE GC bug\nvar activeXDocument;\nvar NullProtoObject = function () {\n try {\n /* global ActiveXObject */\n activeXDocument = document.domain && new ActiveXObject('htmlfile');\n } catch (error) { /* ignore */ }\n NullProtoObject = activeXDocument ? NullProtoObjectViaActiveX(activeXDocument) : NullProtoObjectViaIFrame();\n var length = enumBugKeys.length;\n while (length--) delete NullProtoObject[PROTOTYPE][enumBugKeys[length]];\n return NullProtoObject();\n};\n\nhiddenKeys[IE_PROTO] = true;\n\n// `Object.create` method\n// https://tc39.es/ecma262/#sec-object.create\nmodule.exports = Object.create || function create(O, Properties) {\n var result;\n if (O !== null) {\n EmptyConstructor[PROTOTYPE] = anObject(O);\n result = new EmptyConstructor();\n EmptyConstructor[PROTOTYPE] = null;\n // add \"__proto__\" for Object.getPrototypeOf polyfill\n result[IE_PROTO] = O;\n } else result = NullProtoObject();\n return Properties === undefined ? result : defineProperties(result, Properties);\n};\n","// a string of all valid unicode whitespaces\n// eslint-disable-next-line max-len\nmodule.exports = '\\u0009\\u000A\\u000B\\u000C\\u000D\\u0020\\u00A0\\u1680\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000\\u2028\\u2029\\uFEFF';\n","var requireObjectCoercible = require('../internals/require-object-coercible');\nvar whitespaces = require('../internals/whitespaces');\n\nvar whitespace = '[' + whitespaces + ']';\nvar ltrim = RegExp('^' + whitespace + whitespace + '*');\nvar rtrim = RegExp(whitespace + whitespace + '*$');\n\n// `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation\nvar createMethod = function (TYPE) {\n return function ($this) {\n var string = String(requireObjectCoercible($this));\n if (TYPE & 1) string = string.replace(ltrim, '');\n if (TYPE & 2) string = string.replace(rtrim, '');\n return string;\n };\n};\n\nmodule.exports = {\n // `String.prototype.{ trimLeft, trimStart }` methods\n // https://tc39.es/ecma262/#sec-string.prototype.trimstart\n start: createMethod(1),\n // `String.prototype.{ trimRight, trimEnd }` methods\n // https://tc39.es/ecma262/#sec-string.prototype.trimend\n end: createMethod(2),\n // `String.prototype.trim` method\n // https://tc39.es/ecma262/#sec-string.prototype.trim\n trim: createMethod(3)\n};\n","'use strict';\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar isForced = require('../internals/is-forced');\nvar redefine = require('../internals/redefine');\nvar has = require('../internals/has');\nvar classof = require('../internals/classof-raw');\nvar inheritIfRequired = require('../internals/inherit-if-required');\nvar toPrimitive = require('../internals/to-primitive');\nvar fails = require('../internals/fails');\nvar create = require('../internals/object-create');\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names').f;\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar defineProperty = require('../internals/object-define-property').f;\nvar trim = require('../internals/string-trim').trim;\n\nvar NUMBER = 'Number';\nvar NativeNumber = global[NUMBER];\nvar NumberPrototype = NativeNumber.prototype;\n\n// Opera ~12 has broken Object#toString\nvar BROKEN_CLASSOF = classof(create(NumberPrototype)) == NUMBER;\n\n// `ToNumber` abstract operation\n// https://tc39.es/ecma262/#sec-tonumber\nvar toNumber = function (argument) {\n var it = toPrimitive(argument, false);\n var first, third, radix, maxCode, digits, length, index, code;\n if (typeof it == 'string' && it.length > 2) {\n it = trim(it);\n first = it.charCodeAt(0);\n if (first === 43 || first === 45) {\n third = it.charCodeAt(2);\n if (third === 88 || third === 120) return NaN; // Number('+0x1') should be NaN, old V8 fix\n } else if (first === 48) {\n switch (it.charCodeAt(1)) {\n case 66: case 98: radix = 2; maxCode = 49; break; // fast equal of /^0b[01]+$/i\n case 79: case 111: radix = 8; maxCode = 55; break; // fast equal of /^0o[0-7]+$/i\n default: return +it;\n }\n digits = it.slice(2);\n length = digits.length;\n for (index = 0; index < length; index++) {\n code = digits.charCodeAt(index);\n // parseInt parses a string to a first unavailable symbol\n // but ToNumber should return NaN if a string contains unavailable symbols\n if (code < 48 || code > maxCode) return NaN;\n } return parseInt(digits, radix);\n }\n } return +it;\n};\n\n// `Number` constructor\n// https://tc39.es/ecma262/#sec-number-constructor\nif (isForced(NUMBER, !NativeNumber(' 0o1') || !NativeNumber('0b1') || NativeNumber('+0x1'))) {\n var NumberWrapper = function Number(value) {\n var it = arguments.length < 1 ? 0 : value;\n var dummy = this;\n return dummy instanceof NumberWrapper\n // check on 1..constructor(foo) case\n && (BROKEN_CLASSOF ? fails(function () { NumberPrototype.valueOf.call(dummy); }) : classof(dummy) != NUMBER)\n ? inheritIfRequired(new NativeNumber(toNumber(it)), dummy, NumberWrapper) : toNumber(it);\n };\n for (var keys = DESCRIPTORS ? getOwnPropertyNames(NativeNumber) : (\n // ES3:\n 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +\n // ES2015 (in case, if modules with ES2015 Number statics required before):\n 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +\n 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,' +\n // ESNext\n 'fromString,range'\n ).split(','), j = 0, key; keys.length > j; j++) {\n if (has(NativeNumber, key = keys[j]) && !has(NumberWrapper, key)) {\n defineProperty(NumberWrapper, key, getOwnPropertyDescriptor(NativeNumber, key));\n }\n }\n NumberWrapper.prototype = NumberPrototype;\n NumberPrototype.constructor = NumberWrapper;\n redefine(global, NUMBER, NumberWrapper);\n}\n","var $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar nativeGetOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar DESCRIPTORS = require('../internals/descriptors');\n\nvar FAILS_ON_PRIMITIVES = fails(function () { nativeGetOwnPropertyDescriptor(1); });\nvar FORCED = !DESCRIPTORS || FAILS_ON_PRIMITIVES;\n\n// `Object.getOwnPropertyDescriptor` method\n// https://tc39.es/ecma262/#sec-object.getownpropertydescriptor\n$({ target: 'Object', stat: true, forced: FORCED, sham: !DESCRIPTORS }, {\n getOwnPropertyDescriptor: function getOwnPropertyDescriptor(it, key) {\n return nativeGetOwnPropertyDescriptor(toIndexedObject(it), key);\n }\n});\n","var toIndexedObject = require('../internals/to-indexed-object');\nvar nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names').f;\n\nvar toString = {}.toString;\n\nvar windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames\n ? Object.getOwnPropertyNames(window) : [];\n\nvar getWindowNames = function (it) {\n try {\n return nativeGetOwnPropertyNames(it);\n } catch (error) {\n return windowNames.slice();\n }\n};\n\n// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window\nmodule.exports.f = function getOwnPropertyNames(it) {\n return windowNames && toString.call(it) == '[object Window]'\n ? getWindowNames(it)\n : nativeGetOwnPropertyNames(toIndexedObject(it));\n};\n","var $ = require('../internals/export');\nvar fails = require('../internals/fails');\nvar nativeGetOwnPropertyNames = require('../internals/object-get-own-property-names-external').f;\n\nvar FAILS_ON_PRIMITIVES = fails(function () { return !Object.getOwnPropertyNames(1); });\n\n// `Object.getOwnPropertyNames` method\n// https://tc39.es/ecma262/#sec-object.getownpropertynames\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {\n getOwnPropertyNames: nativeGetOwnPropertyNames\n});\n","var isObject = require('../internals/is-object');\nvar classof = require('../internals/classof-raw');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar MATCH = wellKnownSymbol('match');\n\n// `IsRegExp` abstract operation\n// https://tc39.es/ecma262/#sec-isregexp\nmodule.exports = function (it) {\n var isRegExp;\n return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classof(it) == 'RegExp');\n};\n","'use strict';\nvar getBuiltIn = require('../internals/get-built-in');\nvar definePropertyModule = require('../internals/object-define-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar DESCRIPTORS = require('../internals/descriptors');\n\nvar SPECIES = wellKnownSymbol('species');\n\nmodule.exports = function (CONSTRUCTOR_NAME) {\n var Constructor = getBuiltIn(CONSTRUCTOR_NAME);\n var defineProperty = definePropertyModule.f;\n\n if (DESCRIPTORS && Constructor && !Constructor[SPECIES]) {\n defineProperty(Constructor, SPECIES, {\n configurable: true,\n get: function () { return this; }\n });\n }\n};\n","var DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar isForced = require('../internals/is-forced');\nvar inheritIfRequired = require('../internals/inherit-if-required');\nvar defineProperty = require('../internals/object-define-property').f;\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names').f;\nvar isRegExp = require('../internals/is-regexp');\nvar getFlags = require('../internals/regexp-flags');\nvar stickyHelpers = require('../internals/regexp-sticky-helpers');\nvar redefine = require('../internals/redefine');\nvar fails = require('../internals/fails');\nvar setInternalState = require('../internals/internal-state').set;\nvar setSpecies = require('../internals/set-species');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar MATCH = wellKnownSymbol('match');\nvar NativeRegExp = global.RegExp;\nvar RegExpPrototype = NativeRegExp.prototype;\nvar re1 = /a/g;\nvar re2 = /a/g;\n\n// \"new\" should create a new object, old webkit bug\nvar CORRECT_NEW = new NativeRegExp(re1) !== re1;\n\nvar UNSUPPORTED_Y = stickyHelpers.UNSUPPORTED_Y;\n\nvar FORCED = DESCRIPTORS && isForced('RegExp', (!CORRECT_NEW || UNSUPPORTED_Y || fails(function () {\n re2[MATCH] = false;\n // RegExp constructor can alter flags and IsRegExp works correct with @@match\n return NativeRegExp(re1) != re1 || NativeRegExp(re2) == re2 || NativeRegExp(re1, 'i') != '/a/i';\n})));\n\n// `RegExp` constructor\n// https://tc39.es/ecma262/#sec-regexp-constructor\nif (FORCED) {\n var RegExpWrapper = function RegExp(pattern, flags) {\n var thisIsRegExp = this instanceof RegExpWrapper;\n var patternIsRegExp = isRegExp(pattern);\n var flagsAreUndefined = flags === undefined;\n var sticky;\n\n if (!thisIsRegExp && patternIsRegExp && pattern.constructor === RegExpWrapper && flagsAreUndefined) {\n return pattern;\n }\n\n if (CORRECT_NEW) {\n if (patternIsRegExp && !flagsAreUndefined) pattern = pattern.source;\n } else if (pattern instanceof RegExpWrapper) {\n if (flagsAreUndefined) flags = getFlags.call(pattern);\n pattern = pattern.source;\n }\n\n if (UNSUPPORTED_Y) {\n sticky = !!flags && flags.indexOf('y') > -1;\n if (sticky) flags = flags.replace(/y/g, '');\n }\n\n var result = inheritIfRequired(\n CORRECT_NEW ? new NativeRegExp(pattern, flags) : NativeRegExp(pattern, flags),\n thisIsRegExp ? this : RegExpPrototype,\n RegExpWrapper\n );\n\n if (UNSUPPORTED_Y && sticky) setInternalState(result, { sticky: sticky });\n\n return result;\n };\n var proxy = function (key) {\n key in RegExpWrapper || defineProperty(RegExpWrapper, key, {\n configurable: true,\n get: function () { return NativeRegExp[key]; },\n set: function (it) { NativeRegExp[key] = it; }\n });\n };\n var keys = getOwnPropertyNames(NativeRegExp);\n var index = 0;\n while (keys.length > index) proxy(keys[index++]);\n RegExpPrototype.constructor = RegExpWrapper;\n RegExpWrapper.prototype = RegExpPrototype;\n redefine(global, 'RegExp', RegExpWrapper);\n}\n\n// https://tc39.es/ecma262/#sec-get-regexp-@@species\nsetSpecies('RegExp');\n","var toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `String.prototype.{ codePointAt, at }` methods implementation\nvar createMethod = function (CONVERT_TO_STRING) {\n return function ($this, pos) {\n var S = String(requireObjectCoercible($this));\n var position = toInteger(pos);\n var size = S.length;\n var first, second;\n if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;\n first = S.charCodeAt(position);\n return first < 0xD800 || first > 0xDBFF || position + 1 === size\n || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF\n ? CONVERT_TO_STRING ? S.charAt(position) : first\n : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;\n };\n};\n\nmodule.exports = {\n // `String.prototype.codePointAt` method\n // https://tc39.es/ecma262/#sec-string.prototype.codepointat\n codeAt: createMethod(false),\n // `String.prototype.at` method\n // https://github.com/mathiasbynens/String.prototype.at\n charAt: createMethod(true)\n};\n","'use strict';\nvar charAt = require('../internals/string-multibyte').charAt;\n\n// `AdvanceStringIndex` abstract operation\n// https://tc39.es/ecma262/#sec-advancestringindex\nmodule.exports = function (S, index, unicode) {\n return index + (unicode ? charAt(S, index).length : 1);\n};\n","'use strict';\nvar fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');\nvar anObject = require('../internals/an-object');\nvar toLength = require('../internals/to-length');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar advanceStringIndex = require('../internals/advance-string-index');\nvar regExpExec = require('../internals/regexp-exec-abstract');\n\n// @@match logic\nfixRegExpWellKnownSymbolLogic('match', 1, function (MATCH, nativeMatch, maybeCallNative) {\n return [\n // `String.prototype.match` method\n // https://tc39.es/ecma262/#sec-string.prototype.match\n function match(regexp) {\n var O = requireObjectCoercible(this);\n var matcher = regexp == undefined ? undefined : regexp[MATCH];\n return matcher !== undefined ? matcher.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));\n },\n // `RegExp.prototype[@@match]` method\n // https://tc39.es/ecma262/#sec-regexp.prototype-@@match\n function (regexp) {\n var res = maybeCallNative(nativeMatch, regexp, this);\n if (res.done) return res.value;\n\n var rx = anObject(regexp);\n var S = String(this);\n\n if (!rx.global) return regExpExec(rx, S);\n\n var fullUnicode = rx.unicode;\n rx.lastIndex = 0;\n var A = [];\n var n = 0;\n var result;\n while ((result = regExpExec(rx, S)) !== null) {\n var matchStr = String(result[0]);\n A[n] = matchStr;\n if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);\n n++;\n }\n return n === 0 ? null : A;\n }\n ];\n});\n","var toObject = require('../internals/to-object');\n\nvar floor = Math.floor;\nvar replace = ''.replace;\nvar SUBSTITUTION_SYMBOLS = /\\$([$&'`]|\\d\\d?|<[^>]*>)/g;\nvar SUBSTITUTION_SYMBOLS_NO_NAMED = /\\$([$&'`]|\\d\\d?)/g;\n\n// https://tc39.es/ecma262/#sec-getsubstitution\nmodule.exports = function (matched, str, position, captures, namedCaptures, replacement) {\n var tailPos = position + matched.length;\n var m = captures.length;\n var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;\n if (namedCaptures !== undefined) {\n namedCaptures = toObject(namedCaptures);\n symbols = SUBSTITUTION_SYMBOLS;\n }\n return replace.call(replacement, symbols, function (match, ch) {\n var capture;\n switch (ch.charAt(0)) {\n case '$': return '$';\n case '&': return matched;\n case '`': return str.slice(0, position);\n case \"'\": return str.slice(tailPos);\n case '<':\n capture = namedCaptures[ch.slice(1, -1)];\n break;\n default: // \\d\\d?\n var n = +ch;\n if (n === 0) return match;\n if (n > m) {\n var f = floor(n / 10);\n if (f === 0) return match;\n if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);\n return match;\n }\n capture = captures[n - 1];\n }\n return capture === undefined ? '' : capture;\n });\n};\n","'use strict';\nvar fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');\nvar anObject = require('../internals/an-object');\nvar toLength = require('../internals/to-length');\nvar toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar advanceStringIndex = require('../internals/advance-string-index');\nvar getSubstitution = require('../internals/get-substitution');\nvar regExpExec = require('../internals/regexp-exec-abstract');\n\nvar max = Math.max;\nvar min = Math.min;\n\nvar maybeToString = function (it) {\n return it === undefined ? it : String(it);\n};\n\n// @@replace logic\nfixRegExpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative, reason) {\n var REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE = reason.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE;\n var REPLACE_KEEPS_$0 = reason.REPLACE_KEEPS_$0;\n var UNSAFE_SUBSTITUTE = REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE ? '$' : '$0';\n\n return [\n // `String.prototype.replace` method\n // https://tc39.es/ecma262/#sec-string.prototype.replace\n function replace(searchValue, replaceValue) {\n var O = requireObjectCoercible(this);\n var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];\n return replacer !== undefined\n ? replacer.call(searchValue, O, replaceValue)\n : nativeReplace.call(String(O), searchValue, replaceValue);\n },\n // `RegExp.prototype[@@replace]` method\n // https://tc39.es/ecma262/#sec-regexp.prototype-@@replace\n function (regexp, replaceValue) {\n if (\n (!REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE && REPLACE_KEEPS_$0) ||\n (typeof replaceValue === 'string' && replaceValue.indexOf(UNSAFE_SUBSTITUTE) === -1)\n ) {\n var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);\n if (res.done) return res.value;\n }\n\n var rx = anObject(regexp);\n var S = String(this);\n\n var functionalReplace = typeof replaceValue === 'function';\n if (!functionalReplace) replaceValue = String(replaceValue);\n\n var global = rx.global;\n if (global) {\n var fullUnicode = rx.unicode;\n rx.lastIndex = 0;\n }\n var results = [];\n while (true) {\n var result = regExpExec(rx, S);\n if (result === null) break;\n\n results.push(result);\n if (!global) break;\n\n var matchStr = String(result[0]);\n if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);\n }\n\n var accumulatedResult = '';\n var nextSourcePosition = 0;\n for (var i = 0; i < results.length; i++) {\n result = results[i];\n\n var matched = String(result[0]);\n var position = max(min(toInteger(result.index), S.length), 0);\n var captures = [];\n // NOTE: This is equivalent to\n // captures = result.slice(1).map(maybeToString)\n // but for some reason `nativeSlice.call(result, 1, result.length)` (called in\n // the slice polyfill when slicing native arrays) \"doesn't work\" in safari 9 and\n // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.\n for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));\n var namedCaptures = result.groups;\n if (functionalReplace) {\n var replacerArgs = [matched].concat(captures, position, S);\n if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);\n var replacement = String(replaceValue.apply(undefined, replacerArgs));\n } else {\n replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);\n }\n if (position >= nextSourcePosition) {\n accumulatedResult += S.slice(nextSourcePosition, position) + replacement;\n nextSourcePosition = position + matched.length;\n }\n }\n return accumulatedResult + S.slice(nextSourcePosition);\n }\n ];\n});\n","var anObject = require('../internals/an-object');\nvar aFunction = require('../internals/a-function');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar SPECIES = wellKnownSymbol('species');\n\n// `SpeciesConstructor` abstract operation\n// https://tc39.es/ecma262/#sec-speciesconstructor\nmodule.exports = function (O, defaultConstructor) {\n var C = anObject(O).constructor;\n var S;\n return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? defaultConstructor : aFunction(S);\n};\n","'use strict';\nvar fixRegExpWellKnownSymbolLogic = require('../internals/fix-regexp-well-known-symbol-logic');\nvar isRegExp = require('../internals/is-regexp');\nvar anObject = require('../internals/an-object');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar speciesConstructor = require('../internals/species-constructor');\nvar advanceStringIndex = require('../internals/advance-string-index');\nvar toLength = require('../internals/to-length');\nvar callRegExpExec = require('../internals/regexp-exec-abstract');\nvar regexpExec = require('../internals/regexp-exec');\nvar fails = require('../internals/fails');\n\nvar arrayPush = [].push;\nvar min = Math.min;\nvar MAX_UINT32 = 0xFFFFFFFF;\n\n// babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError\nvar SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });\n\n// @@split logic\nfixRegExpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {\n var internalSplit;\n if (\n 'abbc'.split(/(b)*/)[1] == 'c' ||\n 'test'.split(/(?:)/, -1).length != 4 ||\n 'ab'.split(/(?:ab)*/).length != 2 ||\n '.'.split(/(.?)(.?)/).length != 4 ||\n '.'.split(/()()/).length > 1 ||\n ''.split(/.?/).length\n ) {\n // based on es5-shim implementation, need to rework it\n internalSplit = function (separator, limit) {\n var string = String(requireObjectCoercible(this));\n var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;\n if (lim === 0) return [];\n if (separator === undefined) return [string];\n // If `separator` is not a regex, use native split\n if (!isRegExp(separator)) {\n return nativeSplit.call(string, separator, lim);\n }\n var output = [];\n var flags = (separator.ignoreCase ? 'i' : '') +\n (separator.multiline ? 'm' : '') +\n (separator.unicode ? 'u' : '') +\n (separator.sticky ? 'y' : '');\n var lastLastIndex = 0;\n // Make `global` and avoid `lastIndex` issues by working with a copy\n var separatorCopy = new RegExp(separator.source, flags + 'g');\n var match, lastIndex, lastLength;\n while (match = regexpExec.call(separatorCopy, string)) {\n lastIndex = separatorCopy.lastIndex;\n if (lastIndex > lastLastIndex) {\n output.push(string.slice(lastLastIndex, match.index));\n if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));\n lastLength = match[0].length;\n lastLastIndex = lastIndex;\n if (output.length >= lim) break;\n }\n if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop\n }\n if (lastLastIndex === string.length) {\n if (lastLength || !separatorCopy.test('')) output.push('');\n } else output.push(string.slice(lastLastIndex));\n return output.length > lim ? output.slice(0, lim) : output;\n };\n // Chakra, V8\n } else if ('0'.split(undefined, 0).length) {\n internalSplit = function (separator, limit) {\n return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);\n };\n } else internalSplit = nativeSplit;\n\n return [\n // `String.prototype.split` method\n // https://tc39.es/ecma262/#sec-string.prototype.split\n function split(separator, limit) {\n var O = requireObjectCoercible(this);\n var splitter = separator == undefined ? undefined : separator[SPLIT];\n return splitter !== undefined\n ? splitter.call(separator, O, limit)\n : internalSplit.call(String(O), separator, limit);\n },\n // `RegExp.prototype[@@split]` method\n // https://tc39.es/ecma262/#sec-regexp.prototype-@@split\n //\n // NOTE: This cannot be properly polyfilled in engines that don't support\n // the 'y' flag.\n function (regexp, limit) {\n var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);\n if (res.done) return res.value;\n\n var rx = anObject(regexp);\n var S = String(this);\n var C = speciesConstructor(rx, RegExp);\n\n var unicodeMatching = rx.unicode;\n var flags = (rx.ignoreCase ? 'i' : '') +\n (rx.multiline ? 'm' : '') +\n (rx.unicode ? 'u' : '') +\n (SUPPORTS_Y ? 'y' : 'g');\n\n // ^(? + rx + ) is needed, in combination with some S slicing, to\n // simulate the 'y' flag.\n var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);\n var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;\n if (lim === 0) return [];\n if (S.length === 0) return callRegExpExec(splitter, S) === null ? [S] : [];\n var p = 0;\n var q = 0;\n var A = [];\n while (q < S.length) {\n splitter.lastIndex = SUPPORTS_Y ? q : 0;\n var z = callRegExpExec(splitter, SUPPORTS_Y ? S : S.slice(q));\n var e;\n if (\n z === null ||\n (e = min(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p\n ) {\n q = advanceStringIndex(S, q, unicodeMatching);\n } else {\n A.push(S.slice(p, q));\n if (A.length === lim) return A;\n for (var i = 1; i <= z.length - 1; i++) {\n A.push(z[i]);\n if (A.length === lim) return A;\n }\n q = p = e;\n }\n }\n A.push(S.slice(p));\n return A;\n }\n ];\n}, !SUPPORTS_Y);\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nexports.f = wellKnownSymbol;\n","var path = require('../internals/path');\nvar has = require('../internals/has');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineProperty = require('../internals/object-define-property').f;\n\nmodule.exports = function (NAME) {\n var Symbol = path.Symbol || (path.Symbol = {});\n if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {\n value: wrappedWellKnownSymbolModule.f(NAME)\n });\n};\n","var defineProperty = require('../internals/object-define-property').f;\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\n\nmodule.exports = function (it, TAG, STATIC) {\n if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {\n defineProperty(it, TO_STRING_TAG, { configurable: true, value: TAG });\n }\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar IS_PURE = require('../internals/is-pure');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar NATIVE_SYMBOL = require('../internals/native-symbol');\nvar USE_SYMBOL_AS_UID = require('../internals/use-symbol-as-uid');\nvar fails = require('../internals/fails');\nvar has = require('../internals/has');\nvar isArray = require('../internals/is-array');\nvar isObject = require('../internals/is-object');\nvar anObject = require('../internals/an-object');\nvar toObject = require('../internals/to-object');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toPrimitive = require('../internals/to-primitive');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar nativeObjectCreate = require('../internals/object-create');\nvar objectKeys = require('../internals/object-keys');\nvar getOwnPropertyNamesModule = require('../internals/object-get-own-property-names');\nvar getOwnPropertyNamesExternal = require('../internals/object-get-own-property-names-external');\nvar getOwnPropertySymbolsModule = require('../internals/object-get-own-property-symbols');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar definePropertyModule = require('../internals/object-define-property');\nvar propertyIsEnumerableModule = require('../internals/object-property-is-enumerable');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar shared = require('../internals/shared');\nvar sharedKey = require('../internals/shared-key');\nvar hiddenKeys = require('../internals/hidden-keys');\nvar uid = require('../internals/uid');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar wrappedWellKnownSymbolModule = require('../internals/well-known-symbol-wrapped');\nvar defineWellKnownSymbol = require('../internals/define-well-known-symbol');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar InternalStateModule = require('../internals/internal-state');\nvar $forEach = require('../internals/array-iteration').forEach;\n\nvar HIDDEN = sharedKey('hidden');\nvar SYMBOL = 'Symbol';\nvar PROTOTYPE = 'prototype';\nvar TO_PRIMITIVE = wellKnownSymbol('toPrimitive');\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(SYMBOL);\nvar ObjectPrototype = Object[PROTOTYPE];\nvar $Symbol = global.Symbol;\nvar $stringify = getBuiltIn('JSON', 'stringify');\nvar nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\nvar nativeDefineProperty = definePropertyModule.f;\nvar nativeGetOwnPropertyNames = getOwnPropertyNamesExternal.f;\nvar nativePropertyIsEnumerable = propertyIsEnumerableModule.f;\nvar AllSymbols = shared('symbols');\nvar ObjectPrototypeSymbols = shared('op-symbols');\nvar StringToSymbolRegistry = shared('string-to-symbol-registry');\nvar SymbolToStringRegistry = shared('symbol-to-string-registry');\nvar WellKnownSymbolsStore = shared('wks');\nvar QObject = global.QObject;\n// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173\nvar USE_SETTER = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;\n\n// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687\nvar setSymbolDescriptor = DESCRIPTORS && fails(function () {\n return nativeObjectCreate(nativeDefineProperty({}, 'a', {\n get: function () { return nativeDefineProperty(this, 'a', { value: 7 }).a; }\n })).a != 7;\n}) ? function (O, P, Attributes) {\n var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor(ObjectPrototype, P);\n if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];\n nativeDefineProperty(O, P, Attributes);\n if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {\n nativeDefineProperty(ObjectPrototype, P, ObjectPrototypeDescriptor);\n }\n} : nativeDefineProperty;\n\nvar wrap = function (tag, description) {\n var symbol = AllSymbols[tag] = nativeObjectCreate($Symbol[PROTOTYPE]);\n setInternalState(symbol, {\n type: SYMBOL,\n tag: tag,\n description: description\n });\n if (!DESCRIPTORS) symbol.description = description;\n return symbol;\n};\n\nvar isSymbol = USE_SYMBOL_AS_UID ? function (it) {\n return typeof it == 'symbol';\n} : function (it) {\n return Object(it) instanceof $Symbol;\n};\n\nvar $defineProperty = function defineProperty(O, P, Attributes) {\n if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);\n anObject(O);\n var key = toPrimitive(P, true);\n anObject(Attributes);\n if (has(AllSymbols, key)) {\n if (!Attributes.enumerable) {\n if (!has(O, HIDDEN)) nativeDefineProperty(O, HIDDEN, createPropertyDescriptor(1, {}));\n O[HIDDEN][key] = true;\n } else {\n if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;\n Attributes = nativeObjectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });\n } return setSymbolDescriptor(O, key, Attributes);\n } return nativeDefineProperty(O, key, Attributes);\n};\n\nvar $defineProperties = function defineProperties(O, Properties) {\n anObject(O);\n var properties = toIndexedObject(Properties);\n var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));\n $forEach(keys, function (key) {\n if (!DESCRIPTORS || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);\n });\n return O;\n};\n\nvar $create = function create(O, Properties) {\n return Properties === undefined ? nativeObjectCreate(O) : $defineProperties(nativeObjectCreate(O), Properties);\n};\n\nvar $propertyIsEnumerable = function propertyIsEnumerable(V) {\n var P = toPrimitive(V, true);\n var enumerable = nativePropertyIsEnumerable.call(this, P);\n if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;\n return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;\n};\n\nvar $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {\n var it = toIndexedObject(O);\n var key = toPrimitive(P, true);\n if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;\n var descriptor = nativeGetOwnPropertyDescriptor(it, key);\n if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {\n descriptor.enumerable = true;\n }\n return descriptor;\n};\n\nvar $getOwnPropertyNames = function getOwnPropertyNames(O) {\n var names = nativeGetOwnPropertyNames(toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);\n });\n return result;\n};\n\nvar $getOwnPropertySymbols = function getOwnPropertySymbols(O) {\n var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;\n var names = nativeGetOwnPropertyNames(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));\n var result = [];\n $forEach(names, function (key) {\n if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {\n result.push(AllSymbols[key]);\n }\n });\n return result;\n};\n\n// `Symbol` constructor\n// https://tc39.es/ecma262/#sec-symbol-constructor\nif (!NATIVE_SYMBOL) {\n $Symbol = function Symbol() {\n if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');\n var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);\n var tag = uid(description);\n var setter = function (value) {\n if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);\n if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;\n setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));\n };\n if (DESCRIPTORS && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });\n return wrap(tag, description);\n };\n\n redefine($Symbol[PROTOTYPE], 'toString', function toString() {\n return getInternalState(this).tag;\n });\n\n redefine($Symbol, 'withoutSetter', function (description) {\n return wrap(uid(description), description);\n });\n\n propertyIsEnumerableModule.f = $propertyIsEnumerable;\n definePropertyModule.f = $defineProperty;\n getOwnPropertyDescriptorModule.f = $getOwnPropertyDescriptor;\n getOwnPropertyNamesModule.f = getOwnPropertyNamesExternal.f = $getOwnPropertyNames;\n getOwnPropertySymbolsModule.f = $getOwnPropertySymbols;\n\n wrappedWellKnownSymbolModule.f = function (name) {\n return wrap(wellKnownSymbol(name), name);\n };\n\n if (DESCRIPTORS) {\n // https://github.com/tc39/proposal-Symbol-description\n nativeDefineProperty($Symbol[PROTOTYPE], 'description', {\n configurable: true,\n get: function description() {\n return getInternalState(this).description;\n }\n });\n if (!IS_PURE) {\n redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });\n }\n }\n}\n\n$({ global: true, wrap: true, forced: !NATIVE_SYMBOL, sham: !NATIVE_SYMBOL }, {\n Symbol: $Symbol\n});\n\n$forEach(objectKeys(WellKnownSymbolsStore), function (name) {\n defineWellKnownSymbol(name);\n});\n\n$({ target: SYMBOL, stat: true, forced: !NATIVE_SYMBOL }, {\n // `Symbol.for` method\n // https://tc39.es/ecma262/#sec-symbol.for\n 'for': function (key) {\n var string = String(key);\n if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];\n var symbol = $Symbol(string);\n StringToSymbolRegistry[string] = symbol;\n SymbolToStringRegistry[symbol] = string;\n return symbol;\n },\n // `Symbol.keyFor` method\n // https://tc39.es/ecma262/#sec-symbol.keyfor\n keyFor: function keyFor(sym) {\n if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');\n if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];\n },\n useSetter: function () { USE_SETTER = true; },\n useSimple: function () { USE_SETTER = false; }\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL, sham: !DESCRIPTORS }, {\n // `Object.create` method\n // https://tc39.es/ecma262/#sec-object.create\n create: $create,\n // `Object.defineProperty` method\n // https://tc39.es/ecma262/#sec-object.defineproperty\n defineProperty: $defineProperty,\n // `Object.defineProperties` method\n // https://tc39.es/ecma262/#sec-object.defineproperties\n defineProperties: $defineProperties,\n // `Object.getOwnPropertyDescriptor` method\n // https://tc39.es/ecma262/#sec-object.getownpropertydescriptors\n getOwnPropertyDescriptor: $getOwnPropertyDescriptor\n});\n\n$({ target: 'Object', stat: true, forced: !NATIVE_SYMBOL }, {\n // `Object.getOwnPropertyNames` method\n // https://tc39.es/ecma262/#sec-object.getownpropertynames\n getOwnPropertyNames: $getOwnPropertyNames,\n // `Object.getOwnPropertySymbols` method\n // https://tc39.es/ecma262/#sec-object.getownpropertysymbols\n getOwnPropertySymbols: $getOwnPropertySymbols\n});\n\n// Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives\n// https://bugs.chromium.org/p/v8/issues/detail?id=3443\n$({ target: 'Object', stat: true, forced: fails(function () { getOwnPropertySymbolsModule.f(1); }) }, {\n getOwnPropertySymbols: function getOwnPropertySymbols(it) {\n return getOwnPropertySymbolsModule.f(toObject(it));\n }\n});\n\n// `JSON.stringify` method behavior with symbols\n// https://tc39.es/ecma262/#sec-json.stringify\nif ($stringify) {\n var FORCED_JSON_STRINGIFY = !NATIVE_SYMBOL || fails(function () {\n var symbol = $Symbol();\n // MS Edge converts symbol values to JSON as {}\n return $stringify([symbol]) != '[null]'\n // WebKit converts symbol values to JSON as null\n || $stringify({ a: symbol }) != '{}'\n // V8 throws on boxed symbols\n || $stringify(Object(symbol)) != '{}';\n });\n\n $({ target: 'JSON', stat: true, forced: FORCED_JSON_STRINGIFY }, {\n // eslint-disable-next-line no-unused-vars\n stringify: function stringify(it, replacer, space) {\n var args = [it];\n var index = 1;\n var $replacer;\n while (arguments.length > index) args.push(arguments[index++]);\n $replacer = replacer;\n if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined\n if (!isArray(replacer)) replacer = function (key, value) {\n if (typeof $replacer == 'function') value = $replacer.call(this, key, value);\n if (!isSymbol(value)) return value;\n };\n args[1] = replacer;\n return $stringify.apply(null, args);\n }\n });\n}\n\n// `Symbol.prototype[@@toPrimitive]` method\n// https://tc39.es/ecma262/#sec-symbol.prototype-@@toprimitive\nif (!$Symbol[PROTOTYPE][TO_PRIMITIVE]) {\n createNonEnumerableProperty($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);\n}\n// `Symbol.prototype[@@toStringTag]` property\n// https://tc39.es/ecma262/#sec-symbol.prototype-@@tostringtag\nsetToStringTag($Symbol, SYMBOL);\n\nhiddenKeys[HIDDEN] = true;\n","// `Symbol.prototype.description` getter\n// https://tc39.es/ecma262/#sec-symbol.prototype.description\n'use strict';\nvar $ = require('../internals/export');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar has = require('../internals/has');\nvar isObject = require('../internals/is-object');\nvar defineProperty = require('../internals/object-define-property').f;\nvar copyConstructorProperties = require('../internals/copy-constructor-properties');\n\nvar NativeSymbol = global.Symbol;\n\nif (DESCRIPTORS && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||\n // Safari 12 bug\n NativeSymbol().description !== undefined\n)) {\n var EmptyStringDescriptionStore = {};\n // wrap Symbol constructor for correct work with undefined description\n var SymbolWrapper = function Symbol() {\n var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);\n var result = this instanceof SymbolWrapper\n ? new NativeSymbol(description)\n // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'\n : description === undefined ? NativeSymbol() : NativeSymbol(description);\n if (description === '') EmptyStringDescriptionStore[result] = true;\n return result;\n };\n copyConstructorProperties(SymbolWrapper, NativeSymbol);\n var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;\n symbolPrototype.constructor = SymbolWrapper;\n\n var symbolToString = symbolPrototype.toString;\n var native = String(NativeSymbol('test')) == 'Symbol(test)';\n var regexp = /^Symbol\\((.*)\\)[^)]+$/;\n defineProperty(symbolPrototype, 'description', {\n configurable: true,\n get: function description() {\n var symbol = isObject(this) ? this.valueOf() : this;\n var string = symbolToString.call(symbol);\n if (has(EmptyStringDescriptionStore, symbol)) return '';\n var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');\n return desc === '' ? undefined : desc;\n }\n });\n\n $({ global: true, forced: true }, {\n Symbol: SymbolWrapper\n });\n}\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.species` well-known symbol\n// https://tc39.es/ecma262/#sec-symbol.species\ndefineWellKnownSymbol('species');\n","'use strict';\nvar toObject = require('../internals/to-object');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\n\n// `Array.prototype.fill` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.fill\nmodule.exports = function fill(value /* , start = 0, end = @length */) {\n var O = toObject(this);\n var length = toLength(O.length);\n var argumentsLength = arguments.length;\n var index = toAbsoluteIndex(argumentsLength > 1 ? arguments[1] : undefined, length);\n var end = argumentsLength > 2 ? arguments[2] : undefined;\n var endPos = end === undefined ? length : toAbsoluteIndex(end, length);\n while (endPos > index) O[index++] = value;\n return O;\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar create = require('../internals/object-create');\nvar definePropertyModule = require('../internals/object-define-property');\n\nvar UNSCOPABLES = wellKnownSymbol('unscopables');\nvar ArrayPrototype = Array.prototype;\n\n// Array.prototype[@@unscopables]\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\nif (ArrayPrototype[UNSCOPABLES] == undefined) {\n definePropertyModule.f(ArrayPrototype, UNSCOPABLES, {\n configurable: true,\n value: create(null)\n });\n}\n\n// add a key to Array.prototype[@@unscopables]\nmodule.exports = function (key) {\n ArrayPrototype[UNSCOPABLES][key] = true;\n};\n","var $ = require('../internals/export');\nvar fill = require('../internals/array-fill');\nvar addToUnscopables = require('../internals/add-to-unscopables');\n\n// `Array.prototype.fill` method\n// https://tc39.es/ecma262/#sec-array.prototype.fill\n$({ target: 'Array', proto: true }, {\n fill: fill\n});\n\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('fill');\n","'use strict';\nvar $ = require('../internals/export');\nvar $includes = require('../internals/array-includes').includes;\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });\n\n// `Array.prototype.includes` method\n// https://tc39.es/ecma262/#sec-array.prototype.includes\n$({ target: 'Array', proto: true, forced: !USES_TO_LENGTH }, {\n includes: function includes(el /* , fromIndex = 0 */) {\n return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('includes');\n","module.exports = {};\n","'use strict';\nvar fails = require('../internals/fails');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar has = require('../internals/has');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar BUGGY_SAFARI_ITERATORS = false;\n\nvar returnThis = function () { return this; };\n\n// `%IteratorPrototype%` object\n// https://tc39.es/ecma262/#sec-%iteratorprototype%-object\nvar IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;\n\nif ([].keys) {\n arrayIterator = [].keys();\n // Safari 8 has buggy iterators w/o `next`\n if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;\n else {\n PrototypeOfArrayIteratorPrototype = getPrototypeOf(getPrototypeOf(arrayIterator));\n if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;\n }\n}\n\nvar NEW_ITERATOR_PROTOTYPE = IteratorPrototype == undefined || fails(function () {\n var test = {};\n // FF44- legacy iterators case\n return IteratorPrototype[ITERATOR].call(test) !== test;\n});\n\nif (NEW_ITERATOR_PROTOTYPE) IteratorPrototype = {};\n\n// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()\nif ((!IS_PURE || NEW_ITERATOR_PROTOTYPE) && !has(IteratorPrototype, ITERATOR)) {\n createNonEnumerableProperty(IteratorPrototype, ITERATOR, returnThis);\n}\n\nmodule.exports = {\n IteratorPrototype: IteratorPrototype,\n BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS\n};\n","'use strict';\nvar IteratorPrototype = require('../internals/iterators-core').IteratorPrototype;\nvar create = require('../internals/object-create');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar Iterators = require('../internals/iterators');\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (IteratorConstructor, NAME, next) {\n var TO_STRING_TAG = NAME + ' Iterator';\n IteratorConstructor.prototype = create(IteratorPrototype, { next: createPropertyDescriptor(1, next) });\n setToStringTag(IteratorConstructor, TO_STRING_TAG, false, true);\n Iterators[TO_STRING_TAG] = returnThis;\n return IteratorConstructor;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar createIteratorConstructor = require('../internals/create-iterator-constructor');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_PURE = require('../internals/is-pure');\nvar Iterators = require('../internals/iterators');\nvar IteratorsCore = require('../internals/iterators-core');\n\nvar IteratorPrototype = IteratorsCore.IteratorPrototype;\nvar BUGGY_SAFARI_ITERATORS = IteratorsCore.BUGGY_SAFARI_ITERATORS;\nvar ITERATOR = wellKnownSymbol('iterator');\nvar KEYS = 'keys';\nvar VALUES = 'values';\nvar ENTRIES = 'entries';\n\nvar returnThis = function () { return this; };\n\nmodule.exports = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {\n createIteratorConstructor(IteratorConstructor, NAME, next);\n\n var getIterationMethod = function (KIND) {\n if (KIND === DEFAULT && defaultIterator) return defaultIterator;\n if (!BUGGY_SAFARI_ITERATORS && KIND in IterablePrototype) return IterablePrototype[KIND];\n switch (KIND) {\n case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };\n case VALUES: return function values() { return new IteratorConstructor(this, KIND); };\n case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };\n } return function () { return new IteratorConstructor(this); };\n };\n\n var TO_STRING_TAG = NAME + ' Iterator';\n var INCORRECT_VALUES_NAME = false;\n var IterablePrototype = Iterable.prototype;\n var nativeIterator = IterablePrototype[ITERATOR]\n || IterablePrototype['@@iterator']\n || DEFAULT && IterablePrototype[DEFAULT];\n var defaultIterator = !BUGGY_SAFARI_ITERATORS && nativeIterator || getIterationMethod(DEFAULT);\n var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;\n var CurrentIteratorPrototype, methods, KEY;\n\n // fix native\n if (anyNativeIterator) {\n CurrentIteratorPrototype = getPrototypeOf(anyNativeIterator.call(new Iterable()));\n if (IteratorPrototype !== Object.prototype && CurrentIteratorPrototype.next) {\n if (!IS_PURE && getPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype) {\n if (setPrototypeOf) {\n setPrototypeOf(CurrentIteratorPrototype, IteratorPrototype);\n } else if (typeof CurrentIteratorPrototype[ITERATOR] != 'function') {\n createNonEnumerableProperty(CurrentIteratorPrototype, ITERATOR, returnThis);\n }\n }\n // Set @@toStringTag to native iterators\n setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true, true);\n if (IS_PURE) Iterators[TO_STRING_TAG] = returnThis;\n }\n }\n\n // fix Array#{values, @@iterator}.name in V8 / FF\n if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {\n INCORRECT_VALUES_NAME = true;\n defaultIterator = function values() { return nativeIterator.call(this); };\n }\n\n // define iterator\n if ((!IS_PURE || FORCED) && IterablePrototype[ITERATOR] !== defaultIterator) {\n createNonEnumerableProperty(IterablePrototype, ITERATOR, defaultIterator);\n }\n Iterators[NAME] = defaultIterator;\n\n // export additional methods\n if (DEFAULT) {\n methods = {\n values: getIterationMethod(VALUES),\n keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),\n entries: getIterationMethod(ENTRIES)\n };\n if (FORCED) for (KEY in methods) {\n if (BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {\n redefine(IterablePrototype, KEY, methods[KEY]);\n }\n } else $({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS || INCORRECT_VALUES_NAME }, methods);\n }\n\n return methods;\n};\n","'use strict';\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar addToUnscopables = require('../internals/add-to-unscopables');\nvar Iterators = require('../internals/iterators');\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar ARRAY_ITERATOR = 'Array Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(ARRAY_ITERATOR);\n\n// `Array.prototype.entries` method\n// https://tc39.es/ecma262/#sec-array.prototype.entries\n// `Array.prototype.keys` method\n// https://tc39.es/ecma262/#sec-array.prototype.keys\n// `Array.prototype.values` method\n// https://tc39.es/ecma262/#sec-array.prototype.values\n// `Array.prototype[@@iterator]` method\n// https://tc39.es/ecma262/#sec-array.prototype-@@iterator\n// `CreateArrayIterator` internal method\n// https://tc39.es/ecma262/#sec-createarrayiterator\nmodule.exports = defineIterator(Array, 'Array', function (iterated, kind) {\n setInternalState(this, {\n type: ARRAY_ITERATOR,\n target: toIndexedObject(iterated), // target\n index: 0, // next index\n kind: kind // kind\n });\n// `%ArrayIteratorPrototype%.next` method\n// https://tc39.es/ecma262/#sec-%arrayiteratorprototype%.next\n}, function () {\n var state = getInternalState(this);\n var target = state.target;\n var kind = state.kind;\n var index = state.index++;\n if (!target || index >= target.length) {\n state.target = undefined;\n return { value: undefined, done: true };\n }\n if (kind == 'keys') return { value: index, done: false };\n if (kind == 'values') return { value: target[index], done: false };\n return { value: [index, target[index]], done: false };\n}, 'values');\n\n// argumentsList[@@iterator] is %ArrayProto_values%\n// https://tc39.es/ecma262/#sec-createunmappedargumentsobject\n// https://tc39.es/ecma262/#sec-createmappedargumentsobject\nIterators.Arguments = Iterators.Array;\n\n// https://tc39.es/ecma262/#sec-array.prototype-@@unscopables\naddToUnscopables('keys');\naddToUnscopables('values');\naddToUnscopables('entries');\n","'use strict';\nvar $ = require('../internals/export');\nvar isObject = require('../internals/is-object');\nvar isArray = require('../internals/is-array');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar createProperty = require('../internals/create-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar arrayMethodHasSpeciesSupport = require('../internals/array-method-has-species-support');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar HAS_SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('slice');\nvar USES_TO_LENGTH = arrayMethodUsesToLength('slice', { ACCESSORS: true, 0: 0, 1: 2 });\n\nvar SPECIES = wellKnownSymbol('species');\nvar nativeSlice = [].slice;\nvar max = Math.max;\n\n// `Array.prototype.slice` method\n// https://tc39.es/ecma262/#sec-array.prototype.slice\n// fallback for not array-like ES3 strings and DOM objects\n$({ target: 'Array', proto: true, forced: !HAS_SPECIES_SUPPORT || !USES_TO_LENGTH }, {\n slice: function slice(start, end) {\n var O = toIndexedObject(this);\n var length = toLength(O.length);\n var k = toAbsoluteIndex(start, length);\n var fin = toAbsoluteIndex(end === undefined ? length : end, length);\n // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible\n var Constructor, result, n;\n if (isArray(O)) {\n Constructor = O.constructor;\n // cross-realm fallback\n if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {\n Constructor = undefined;\n } else if (isObject(Constructor)) {\n Constructor = Constructor[SPECIES];\n if (Constructor === null) Constructor = undefined;\n }\n if (Constructor === Array || Constructor === undefined) {\n return nativeSlice.call(O, k, fin);\n }\n }\n result = new (Constructor === undefined ? Array : Constructor)(max(fin - k, 0));\n for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);\n result.length = n;\n return result;\n }\n});\n","var setSpecies = require('../internals/set-species');\n\n// `Array[@@species]` getter\n// https://tc39.es/ecma262/#sec-get-array-@@species\nsetSpecies('Array');\n","module.exports = typeof ArrayBuffer !== 'undefined' && typeof DataView !== 'undefined';\n","var redefine = require('../internals/redefine');\n\nmodule.exports = function (target, src, options) {\n for (var key in src) redefine(target, key, src[key], options);\n return target;\n};\n","module.exports = function (it, Constructor, name) {\n if (!(it instanceof Constructor)) {\n throw TypeError('Incorrect ' + (name ? name + ' ' : '') + 'invocation');\n } return it;\n};\n","var toInteger = require('../internals/to-integer');\nvar toLength = require('../internals/to-length');\n\n// `ToIndex` abstract operation\n// https://tc39.es/ecma262/#sec-toindex\nmodule.exports = function (it) {\n if (it === undefined) return 0;\n var number = toInteger(it);\n var length = toLength(number);\n if (number !== length) throw RangeError('Wrong length or index');\n return length;\n};\n","// IEEE754 conversions based on https://github.com/feross/ieee754\n// eslint-disable-next-line no-shadow-restricted-names\nvar Infinity = 1 / 0;\nvar abs = Math.abs;\nvar pow = Math.pow;\nvar floor = Math.floor;\nvar log = Math.log;\nvar LN2 = Math.LN2;\n\nvar pack = function (number, mantissaLength, bytes) {\n var buffer = new Array(bytes);\n var exponentLength = bytes * 8 - mantissaLength - 1;\n var eMax = (1 << exponentLength) - 1;\n var eBias = eMax >> 1;\n var rt = mantissaLength === 23 ? pow(2, -24) - pow(2, -77) : 0;\n var sign = number < 0 || number === 0 && 1 / number < 0 ? 1 : 0;\n var index = 0;\n var exponent, mantissa, c;\n number = abs(number);\n // eslint-disable-next-line no-self-compare\n if (number != number || number === Infinity) {\n // eslint-disable-next-line no-self-compare\n mantissa = number != number ? 1 : 0;\n exponent = eMax;\n } else {\n exponent = floor(log(number) / LN2);\n if (number * (c = pow(2, -exponent)) < 1) {\n exponent--;\n c *= 2;\n }\n if (exponent + eBias >= 1) {\n number += rt / c;\n } else {\n number += rt * pow(2, 1 - eBias);\n }\n if (number * c >= 2) {\n exponent++;\n c /= 2;\n }\n if (exponent + eBias >= eMax) {\n mantissa = 0;\n exponent = eMax;\n } else if (exponent + eBias >= 1) {\n mantissa = (number * c - 1) * pow(2, mantissaLength);\n exponent = exponent + eBias;\n } else {\n mantissa = number * pow(2, eBias - 1) * pow(2, mantissaLength);\n exponent = 0;\n }\n }\n for (; mantissaLength >= 8; buffer[index++] = mantissa & 255, mantissa /= 256, mantissaLength -= 8);\n exponent = exponent << mantissaLength | mantissa;\n exponentLength += mantissaLength;\n for (; exponentLength > 0; buffer[index++] = exponent & 255, exponent /= 256, exponentLength -= 8);\n buffer[--index] |= sign * 128;\n return buffer;\n};\n\nvar unpack = function (buffer, mantissaLength) {\n var bytes = buffer.length;\n var exponentLength = bytes * 8 - mantissaLength - 1;\n var eMax = (1 << exponentLength) - 1;\n var eBias = eMax >> 1;\n var nBits = exponentLength - 7;\n var index = bytes - 1;\n var sign = buffer[index--];\n var exponent = sign & 127;\n var mantissa;\n sign >>= 7;\n for (; nBits > 0; exponent = exponent * 256 + buffer[index], index--, nBits -= 8);\n mantissa = exponent & (1 << -nBits) - 1;\n exponent >>= -nBits;\n nBits += mantissaLength;\n for (; nBits > 0; mantissa = mantissa * 256 + buffer[index], index--, nBits -= 8);\n if (exponent === 0) {\n exponent = 1 - eBias;\n } else if (exponent === eMax) {\n return mantissa ? NaN : sign ? -Infinity : Infinity;\n } else {\n mantissa = mantissa + pow(2, mantissaLength);\n exponent = exponent - eBias;\n } return (sign ? -1 : 1) * mantissa * pow(2, exponent - mantissaLength);\n};\n\nmodule.exports = {\n pack: pack,\n unpack: unpack\n};\n","'use strict';\nvar global = require('../internals/global');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefineAll = require('../internals/redefine-all');\nvar fails = require('../internals/fails');\nvar anInstance = require('../internals/an-instance');\nvar toInteger = require('../internals/to-integer');\nvar toLength = require('../internals/to-length');\nvar toIndex = require('../internals/to-index');\nvar IEEE754 = require('../internals/ieee754');\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names').f;\nvar defineProperty = require('../internals/object-define-property').f;\nvar arrayFill = require('../internals/array-fill');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar InternalStateModule = require('../internals/internal-state');\n\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar ARRAY_BUFFER = 'ArrayBuffer';\nvar DATA_VIEW = 'DataView';\nvar PROTOTYPE = 'prototype';\nvar WRONG_LENGTH = 'Wrong length';\nvar WRONG_INDEX = 'Wrong index';\nvar NativeArrayBuffer = global[ARRAY_BUFFER];\nvar $ArrayBuffer = NativeArrayBuffer;\nvar $DataView = global[DATA_VIEW];\nvar $DataViewPrototype = $DataView && $DataView[PROTOTYPE];\nvar ObjectPrototype = Object.prototype;\nvar RangeError = global.RangeError;\n\nvar packIEEE754 = IEEE754.pack;\nvar unpackIEEE754 = IEEE754.unpack;\n\nvar packInt8 = function (number) {\n return [number & 0xFF];\n};\n\nvar packInt16 = function (number) {\n return [number & 0xFF, number >> 8 & 0xFF];\n};\n\nvar packInt32 = function (number) {\n return [number & 0xFF, number >> 8 & 0xFF, number >> 16 & 0xFF, number >> 24 & 0xFF];\n};\n\nvar unpackInt32 = function (buffer) {\n return buffer[3] << 24 | buffer[2] << 16 | buffer[1] << 8 | buffer[0];\n};\n\nvar packFloat32 = function (number) {\n return packIEEE754(number, 23, 4);\n};\n\nvar packFloat64 = function (number) {\n return packIEEE754(number, 52, 8);\n};\n\nvar addGetter = function (Constructor, key) {\n defineProperty(Constructor[PROTOTYPE], key, { get: function () { return getInternalState(this)[key]; } });\n};\n\nvar get = function (view, count, index, isLittleEndian) {\n var intIndex = toIndex(index);\n var store = getInternalState(view);\n if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);\n var bytes = getInternalState(store.buffer).bytes;\n var start = intIndex + store.byteOffset;\n var pack = bytes.slice(start, start + count);\n return isLittleEndian ? pack : pack.reverse();\n};\n\nvar set = function (view, count, index, conversion, value, isLittleEndian) {\n var intIndex = toIndex(index);\n var store = getInternalState(view);\n if (intIndex + count > store.byteLength) throw RangeError(WRONG_INDEX);\n var bytes = getInternalState(store.buffer).bytes;\n var start = intIndex + store.byteOffset;\n var pack = conversion(+value);\n for (var i = 0; i < count; i++) bytes[start + i] = pack[isLittleEndian ? i : count - i - 1];\n};\n\nif (!NATIVE_ARRAY_BUFFER) {\n $ArrayBuffer = function ArrayBuffer(length) {\n anInstance(this, $ArrayBuffer, ARRAY_BUFFER);\n var byteLength = toIndex(length);\n setInternalState(this, {\n bytes: arrayFill.call(new Array(byteLength), 0),\n byteLength: byteLength\n });\n if (!DESCRIPTORS) this.byteLength = byteLength;\n };\n\n $DataView = function DataView(buffer, byteOffset, byteLength) {\n anInstance(this, $DataView, DATA_VIEW);\n anInstance(buffer, $ArrayBuffer, DATA_VIEW);\n var bufferLength = getInternalState(buffer).byteLength;\n var offset = toInteger(byteOffset);\n if (offset < 0 || offset > bufferLength) throw RangeError('Wrong offset');\n byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);\n if (offset + byteLength > bufferLength) throw RangeError(WRONG_LENGTH);\n setInternalState(this, {\n buffer: buffer,\n byteLength: byteLength,\n byteOffset: offset\n });\n if (!DESCRIPTORS) {\n this.buffer = buffer;\n this.byteLength = byteLength;\n this.byteOffset = offset;\n }\n };\n\n if (DESCRIPTORS) {\n addGetter($ArrayBuffer, 'byteLength');\n addGetter($DataView, 'buffer');\n addGetter($DataView, 'byteLength');\n addGetter($DataView, 'byteOffset');\n }\n\n redefineAll($DataView[PROTOTYPE], {\n getInt8: function getInt8(byteOffset) {\n return get(this, 1, byteOffset)[0] << 24 >> 24;\n },\n getUint8: function getUint8(byteOffset) {\n return get(this, 1, byteOffset)[0];\n },\n getInt16: function getInt16(byteOffset /* , littleEndian */) {\n var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);\n return (bytes[1] << 8 | bytes[0]) << 16 >> 16;\n },\n getUint16: function getUint16(byteOffset /* , littleEndian */) {\n var bytes = get(this, 2, byteOffset, arguments.length > 1 ? arguments[1] : undefined);\n return bytes[1] << 8 | bytes[0];\n },\n getInt32: function getInt32(byteOffset /* , littleEndian */) {\n return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined));\n },\n getUint32: function getUint32(byteOffset /* , littleEndian */) {\n return unpackInt32(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined)) >>> 0;\n },\n getFloat32: function getFloat32(byteOffset /* , littleEndian */) {\n return unpackIEEE754(get(this, 4, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 23);\n },\n getFloat64: function getFloat64(byteOffset /* , littleEndian */) {\n return unpackIEEE754(get(this, 8, byteOffset, arguments.length > 1 ? arguments[1] : undefined), 52);\n },\n setInt8: function setInt8(byteOffset, value) {\n set(this, 1, byteOffset, packInt8, value);\n },\n setUint8: function setUint8(byteOffset, value) {\n set(this, 1, byteOffset, packInt8, value);\n },\n setInt16: function setInt16(byteOffset, value /* , littleEndian */) {\n set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);\n },\n setUint16: function setUint16(byteOffset, value /* , littleEndian */) {\n set(this, 2, byteOffset, packInt16, value, arguments.length > 2 ? arguments[2] : undefined);\n },\n setInt32: function setInt32(byteOffset, value /* , littleEndian */) {\n set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);\n },\n setUint32: function setUint32(byteOffset, value /* , littleEndian */) {\n set(this, 4, byteOffset, packInt32, value, arguments.length > 2 ? arguments[2] : undefined);\n },\n setFloat32: function setFloat32(byteOffset, value /* , littleEndian */) {\n set(this, 4, byteOffset, packFloat32, value, arguments.length > 2 ? arguments[2] : undefined);\n },\n setFloat64: function setFloat64(byteOffset, value /* , littleEndian */) {\n set(this, 8, byteOffset, packFloat64, value, arguments.length > 2 ? arguments[2] : undefined);\n }\n });\n} else {\n if (!fails(function () {\n NativeArrayBuffer(1);\n }) || !fails(function () {\n new NativeArrayBuffer(-1); // eslint-disable-line no-new\n }) || fails(function () {\n new NativeArrayBuffer(); // eslint-disable-line no-new\n new NativeArrayBuffer(1.5); // eslint-disable-line no-new\n new NativeArrayBuffer(NaN); // eslint-disable-line no-new\n return NativeArrayBuffer.name != ARRAY_BUFFER;\n })) {\n $ArrayBuffer = function ArrayBuffer(length) {\n anInstance(this, $ArrayBuffer);\n return new NativeArrayBuffer(toIndex(length));\n };\n var ArrayBufferPrototype = $ArrayBuffer[PROTOTYPE] = NativeArrayBuffer[PROTOTYPE];\n for (var keys = getOwnPropertyNames(NativeArrayBuffer), j = 0, key; keys.length > j;) {\n if (!((key = keys[j++]) in $ArrayBuffer)) {\n createNonEnumerableProperty($ArrayBuffer, key, NativeArrayBuffer[key]);\n }\n }\n ArrayBufferPrototype.constructor = $ArrayBuffer;\n }\n\n // WebKit bug - the same parent prototype for typed arrays and data view\n if (setPrototypeOf && getPrototypeOf($DataViewPrototype) !== ObjectPrototype) {\n setPrototypeOf($DataViewPrototype, ObjectPrototype);\n }\n\n // iOS Safari 7.x bug\n var testView = new $DataView(new $ArrayBuffer(2));\n var nativeSetInt8 = $DataViewPrototype.setInt8;\n testView.setInt8(0, 2147483648);\n testView.setInt8(1, 2147483649);\n if (testView.getInt8(0) || !testView.getInt8(1)) redefineAll($DataViewPrototype, {\n setInt8: function setInt8(byteOffset, value) {\n nativeSetInt8.call(this, byteOffset, value << 24 >> 24);\n },\n setUint8: function setUint8(byteOffset, value) {\n nativeSetInt8.call(this, byteOffset, value << 24 >> 24);\n }\n }, { unsafe: true });\n}\n\nsetToStringTag($ArrayBuffer, ARRAY_BUFFER);\nsetToStringTag($DataView, DATA_VIEW);\n\nmodule.exports = {\n ArrayBuffer: $ArrayBuffer,\n DataView: $DataView\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar arrayBufferModule = require('../internals/array-buffer');\nvar setSpecies = require('../internals/set-species');\n\nvar ARRAY_BUFFER = 'ArrayBuffer';\nvar ArrayBuffer = arrayBufferModule[ARRAY_BUFFER];\nvar NativeArrayBuffer = global[ARRAY_BUFFER];\n\n// `ArrayBuffer` constructor\n// https://tc39.es/ecma262/#sec-arraybuffer-constructor\n$({ global: true, forced: NativeArrayBuffer !== ArrayBuffer }, {\n ArrayBuffer: ArrayBuffer\n});\n\nsetSpecies(ARRAY_BUFFER);\n","var isRegExp = require('../internals/is-regexp');\n\nmodule.exports = function (it) {\n if (isRegExp(it)) {\n throw TypeError(\"The method doesn't accept regular expressions\");\n } return it;\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar MATCH = wellKnownSymbol('match');\n\nmodule.exports = function (METHOD_NAME) {\n var regexp = /./;\n try {\n '/./'[METHOD_NAME](regexp);\n } catch (error1) {\n try {\n regexp[MATCH] = false;\n return '/./'[METHOD_NAME](regexp);\n } catch (error2) { /* empty */ }\n } return false;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar notARegExp = require('../internals/not-a-regexp');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\nvar correctIsRegExpLogic = require('../internals/correct-is-regexp-logic');\n\n// `String.prototype.includes` method\n// https://tc39.es/ecma262/#sec-string.prototype.includes\n$({ target: 'String', proto: true, forced: !correctIsRegExpLogic('includes') }, {\n includes: function includes(searchString /* , position = 0 */) {\n return !!~String(requireObjectCoercible(this))\n .indexOf(notARegExp(searchString), arguments.length > 1 ? arguments[1] : undefined);\n }\n});\n","var fails = require('../internals/fails');\nvar whitespaces = require('../internals/whitespaces');\n\nvar non = '\\u200B\\u0085\\u180E';\n\n// check that a method works with the correct list\n// of whitespaces and has a correct name\nmodule.exports = function (METHOD_NAME) {\n return fails(function () {\n return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;\n });\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar $trim = require('../internals/string-trim').trim;\nvar forcedStringTrimMethod = require('../internals/string-trim-forced');\n\n// `String.prototype.trim` method\n// https://tc39.es/ecma262/#sec-string.prototype.trim\n$({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {\n trim: function trim() {\n return $trim(this);\n }\n});\n","var wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar SAFE_CLOSING = false;\n\ntry {\n var called = 0;\n var iteratorWithReturn = {\n next: function () {\n return { done: !!called++ };\n },\n 'return': function () {\n SAFE_CLOSING = true;\n }\n };\n iteratorWithReturn[ITERATOR] = function () {\n return this;\n };\n // eslint-disable-next-line no-throw-literal\n Array.from(iteratorWithReturn, function () { throw 2; });\n} catch (error) { /* empty */ }\n\nmodule.exports = function (exec, SKIP_CLOSING) {\n if (!SKIP_CLOSING && !SAFE_CLOSING) return false;\n var ITERATION_SUPPORT = false;\n try {\n var object = {};\n object[ITERATOR] = function () {\n return {\n next: function () {\n return { done: ITERATION_SUPPORT = true };\n }\n };\n };\n exec(object);\n } catch (error) { /* empty */ }\n return ITERATION_SUPPORT;\n};\n","'use strict';\nvar NATIVE_ARRAY_BUFFER = require('../internals/array-buffer-native');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar global = require('../internals/global');\nvar isObject = require('../internals/is-object');\nvar has = require('../internals/has');\nvar classof = require('../internals/classof');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar redefine = require('../internals/redefine');\nvar defineProperty = require('../internals/object-define-property').f;\nvar getPrototypeOf = require('../internals/object-get-prototype-of');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar uid = require('../internals/uid');\n\nvar Int8Array = global.Int8Array;\nvar Int8ArrayPrototype = Int8Array && Int8Array.prototype;\nvar Uint8ClampedArray = global.Uint8ClampedArray;\nvar Uint8ClampedArrayPrototype = Uint8ClampedArray && Uint8ClampedArray.prototype;\nvar TypedArray = Int8Array && getPrototypeOf(Int8Array);\nvar TypedArrayPrototype = Int8ArrayPrototype && getPrototypeOf(Int8ArrayPrototype);\nvar ObjectPrototype = Object.prototype;\nvar isPrototypeOf = ObjectPrototype.isPrototypeOf;\n\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar TYPED_ARRAY_TAG = uid('TYPED_ARRAY_TAG');\n// Fixing native typed arrays in Opera Presto crashes the browser, see #595\nvar NATIVE_ARRAY_BUFFER_VIEWS = NATIVE_ARRAY_BUFFER && !!setPrototypeOf && classof(global.opera) !== 'Opera';\nvar TYPED_ARRAY_TAG_REQIRED = false;\nvar NAME;\n\nvar TypedArrayConstructorsList = {\n Int8Array: 1,\n Uint8Array: 1,\n Uint8ClampedArray: 1,\n Int16Array: 2,\n Uint16Array: 2,\n Int32Array: 4,\n Uint32Array: 4,\n Float32Array: 4,\n Float64Array: 8\n};\n\nvar BigIntArrayConstructorsList = {\n BigInt64Array: 8,\n BigUint64Array: 8\n};\n\nvar isView = function isView(it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return klass === 'DataView'\n || has(TypedArrayConstructorsList, klass)\n || has(BigIntArrayConstructorsList, klass);\n};\n\nvar isTypedArray = function (it) {\n if (!isObject(it)) return false;\n var klass = classof(it);\n return has(TypedArrayConstructorsList, klass)\n || has(BigIntArrayConstructorsList, klass);\n};\n\nvar aTypedArray = function (it) {\n if (isTypedArray(it)) return it;\n throw TypeError('Target is not a typed array');\n};\n\nvar aTypedArrayConstructor = function (C) {\n if (setPrototypeOf) {\n if (isPrototypeOf.call(TypedArray, C)) return C;\n } else for (var ARRAY in TypedArrayConstructorsList) if (has(TypedArrayConstructorsList, NAME)) {\n var TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && (C === TypedArrayConstructor || isPrototypeOf.call(TypedArrayConstructor, C))) {\n return C;\n }\n } throw TypeError('Target is not a typed array constructor');\n};\n\nvar exportTypedArrayMethod = function (KEY, property, forced) {\n if (!DESCRIPTORS) return;\n if (forced) for (var ARRAY in TypedArrayConstructorsList) {\n var TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && has(TypedArrayConstructor.prototype, KEY)) {\n delete TypedArrayConstructor.prototype[KEY];\n }\n }\n if (!TypedArrayPrototype[KEY] || forced) {\n redefine(TypedArrayPrototype, KEY, forced ? property\n : NATIVE_ARRAY_BUFFER_VIEWS && Int8ArrayPrototype[KEY] || property);\n }\n};\n\nvar exportTypedArrayStaticMethod = function (KEY, property, forced) {\n var ARRAY, TypedArrayConstructor;\n if (!DESCRIPTORS) return;\n if (setPrototypeOf) {\n if (forced) for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && has(TypedArrayConstructor, KEY)) {\n delete TypedArrayConstructor[KEY];\n }\n }\n if (!TypedArray[KEY] || forced) {\n // V8 ~ Chrome 49-50 `%TypedArray%` methods are non-writable non-configurable\n try {\n return redefine(TypedArray, KEY, forced ? property : NATIVE_ARRAY_BUFFER_VIEWS && Int8Array[KEY] || property);\n } catch (error) { /* empty */ }\n } else return;\n }\n for (ARRAY in TypedArrayConstructorsList) {\n TypedArrayConstructor = global[ARRAY];\n if (TypedArrayConstructor && (!TypedArrayConstructor[KEY] || forced)) {\n redefine(TypedArrayConstructor, KEY, property);\n }\n }\n};\n\nfor (NAME in TypedArrayConstructorsList) {\n if (!global[NAME]) NATIVE_ARRAY_BUFFER_VIEWS = false;\n}\n\n// WebKit bug - typed arrays constructors prototype is Object.prototype\nif (!NATIVE_ARRAY_BUFFER_VIEWS || typeof TypedArray != 'function' || TypedArray === Function.prototype) {\n // eslint-disable-next-line no-shadow\n TypedArray = function TypedArray() {\n throw TypeError('Incorrect invocation');\n };\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME], TypedArray);\n }\n}\n\nif (!NATIVE_ARRAY_BUFFER_VIEWS || !TypedArrayPrototype || TypedArrayPrototype === ObjectPrototype) {\n TypedArrayPrototype = TypedArray.prototype;\n if (NATIVE_ARRAY_BUFFER_VIEWS) for (NAME in TypedArrayConstructorsList) {\n if (global[NAME]) setPrototypeOf(global[NAME].prototype, TypedArrayPrototype);\n }\n}\n\n// WebKit bug - one more object in Uint8ClampedArray prototype chain\nif (NATIVE_ARRAY_BUFFER_VIEWS && getPrototypeOf(Uint8ClampedArrayPrototype) !== TypedArrayPrototype) {\n setPrototypeOf(Uint8ClampedArrayPrototype, TypedArrayPrototype);\n}\n\nif (DESCRIPTORS && !has(TypedArrayPrototype, TO_STRING_TAG)) {\n TYPED_ARRAY_TAG_REQIRED = true;\n defineProperty(TypedArrayPrototype, TO_STRING_TAG, { get: function () {\n return isObject(this) ? this[TYPED_ARRAY_TAG] : undefined;\n } });\n for (NAME in TypedArrayConstructorsList) if (global[NAME]) {\n createNonEnumerableProperty(global[NAME], TYPED_ARRAY_TAG, NAME);\n }\n}\n\nmodule.exports = {\n NATIVE_ARRAY_BUFFER_VIEWS: NATIVE_ARRAY_BUFFER_VIEWS,\n TYPED_ARRAY_TAG: TYPED_ARRAY_TAG_REQIRED && TYPED_ARRAY_TAG,\n aTypedArray: aTypedArray,\n aTypedArrayConstructor: aTypedArrayConstructor,\n exportTypedArrayMethod: exportTypedArrayMethod,\n exportTypedArrayStaticMethod: exportTypedArrayStaticMethod,\n isView: isView,\n isTypedArray: isTypedArray,\n TypedArray: TypedArray,\n TypedArrayPrototype: TypedArrayPrototype\n};\n","/* eslint-disable no-new */\nvar global = require('../internals/global');\nvar fails = require('../internals/fails');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar NATIVE_ARRAY_BUFFER_VIEWS = require('../internals/array-buffer-view-core').NATIVE_ARRAY_BUFFER_VIEWS;\n\nvar ArrayBuffer = global.ArrayBuffer;\nvar Int8Array = global.Int8Array;\n\nmodule.exports = !NATIVE_ARRAY_BUFFER_VIEWS || !fails(function () {\n Int8Array(1);\n}) || !fails(function () {\n new Int8Array(-1);\n}) || !checkCorrectnessOfIteration(function (iterable) {\n new Int8Array();\n new Int8Array(null);\n new Int8Array(1.5);\n new Int8Array(iterable);\n}, true) || fails(function () {\n // Safari (11+) bug - a reason why even Safari 13 should load a typed array polyfill\n return new Int8Array(new ArrayBuffer(2), 1, undefined).length !== 1;\n});\n","var toInteger = require('../internals/to-integer');\n\nmodule.exports = function (it) {\n var result = toInteger(it);\n if (result < 0) throw RangeError(\"The argument can't be less than 0\");\n return result;\n};\n","var toPositiveInteger = require('../internals/to-positive-integer');\n\nmodule.exports = function (it, BYTES) {\n var offset = toPositiveInteger(it);\n if (offset % BYTES) throw RangeError('Wrong offset');\n return offset;\n};\n","var classof = require('../internals/classof');\nvar Iterators = require('../internals/iterators');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\n\nmodule.exports = function (it) {\n if (it != undefined) return it[ITERATOR]\n || it['@@iterator']\n || Iterators[classof(it)];\n};\n","var wellKnownSymbol = require('../internals/well-known-symbol');\nvar Iterators = require('../internals/iterators');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar ArrayPrototype = Array.prototype;\n\n// check on default Array iterator\nmodule.exports = function (it) {\n return it !== undefined && (Iterators.Array === it || ArrayPrototype[ITERATOR] === it);\n};\n","var toObject = require('../internals/to-object');\nvar toLength = require('../internals/to-length');\nvar getIteratorMethod = require('../internals/get-iterator-method');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar bind = require('../internals/function-bind-context');\nvar aTypedArrayConstructor = require('../internals/array-buffer-view-core').aTypedArrayConstructor;\n\nmodule.exports = function from(source /* , mapfn, thisArg */) {\n var O = toObject(source);\n var argumentsLength = arguments.length;\n var mapfn = argumentsLength > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iteratorMethod = getIteratorMethod(O);\n var i, length, result, step, iterator, next;\n if (iteratorMethod != undefined && !isArrayIteratorMethod(iteratorMethod)) {\n iterator = iteratorMethod.call(O);\n next = iterator.next;\n O = [];\n while (!(step = next.call(iterator)).done) {\n O.push(step.value);\n }\n }\n if (mapping && argumentsLength > 2) {\n mapfn = bind(mapfn, arguments[2], 2);\n }\n length = toLength(O.length);\n result = new (aTypedArrayConstructor(this))(length);\n for (i = 0; length > i; i++) {\n result[i] = mapping ? mapfn(O[i], i) : O[i];\n }\n return result;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS = require('../internals/typed-array-constructors-require-wrappers');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar ArrayBufferModule = require('../internals/array-buffer');\nvar anInstance = require('../internals/an-instance');\nvar createPropertyDescriptor = require('../internals/create-property-descriptor');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar toLength = require('../internals/to-length');\nvar toIndex = require('../internals/to-index');\nvar toOffset = require('../internals/to-offset');\nvar toPrimitive = require('../internals/to-primitive');\nvar has = require('../internals/has');\nvar classof = require('../internals/classof');\nvar isObject = require('../internals/is-object');\nvar create = require('../internals/object-create');\nvar setPrototypeOf = require('../internals/object-set-prototype-of');\nvar getOwnPropertyNames = require('../internals/object-get-own-property-names').f;\nvar typedArrayFrom = require('../internals/typed-array-from');\nvar forEach = require('../internals/array-iteration').forEach;\nvar setSpecies = require('../internals/set-species');\nvar definePropertyModule = require('../internals/object-define-property');\nvar getOwnPropertyDescriptorModule = require('../internals/object-get-own-property-descriptor');\nvar InternalStateModule = require('../internals/internal-state');\nvar inheritIfRequired = require('../internals/inherit-if-required');\n\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar nativeDefineProperty = definePropertyModule.f;\nvar nativeGetOwnPropertyDescriptor = getOwnPropertyDescriptorModule.f;\nvar round = Math.round;\nvar RangeError = global.RangeError;\nvar ArrayBuffer = ArrayBufferModule.ArrayBuffer;\nvar DataView = ArrayBufferModule.DataView;\nvar NATIVE_ARRAY_BUFFER_VIEWS = ArrayBufferViewCore.NATIVE_ARRAY_BUFFER_VIEWS;\nvar TYPED_ARRAY_TAG = ArrayBufferViewCore.TYPED_ARRAY_TAG;\nvar TypedArray = ArrayBufferViewCore.TypedArray;\nvar TypedArrayPrototype = ArrayBufferViewCore.TypedArrayPrototype;\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar isTypedArray = ArrayBufferViewCore.isTypedArray;\nvar BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT';\nvar WRONG_LENGTH = 'Wrong length';\n\nvar fromList = function (C, list) {\n var index = 0;\n var length = list.length;\n var result = new (aTypedArrayConstructor(C))(length);\n while (length > index) result[index] = list[index++];\n return result;\n};\n\nvar addGetter = function (it, key) {\n nativeDefineProperty(it, key, { get: function () {\n return getInternalState(this)[key];\n } });\n};\n\nvar isArrayBuffer = function (it) {\n var klass;\n return it instanceof ArrayBuffer || (klass = classof(it)) == 'ArrayBuffer' || klass == 'SharedArrayBuffer';\n};\n\nvar isTypedArrayIndex = function (target, key) {\n return isTypedArray(target)\n && typeof key != 'symbol'\n && key in target\n && String(+key) == String(key);\n};\n\nvar wrappedGetOwnPropertyDescriptor = function getOwnPropertyDescriptor(target, key) {\n return isTypedArrayIndex(target, key = toPrimitive(key, true))\n ? createPropertyDescriptor(2, target[key])\n : nativeGetOwnPropertyDescriptor(target, key);\n};\n\nvar wrappedDefineProperty = function defineProperty(target, key, descriptor) {\n if (isTypedArrayIndex(target, key = toPrimitive(key, true))\n && isObject(descriptor)\n && has(descriptor, 'value')\n && !has(descriptor, 'get')\n && !has(descriptor, 'set')\n // TODO: add validation descriptor w/o calling accessors\n && !descriptor.configurable\n && (!has(descriptor, 'writable') || descriptor.writable)\n && (!has(descriptor, 'enumerable') || descriptor.enumerable)\n ) {\n target[key] = descriptor.value;\n return target;\n } return nativeDefineProperty(target, key, descriptor);\n};\n\nif (DESCRIPTORS) {\n if (!NATIVE_ARRAY_BUFFER_VIEWS) {\n getOwnPropertyDescriptorModule.f = wrappedGetOwnPropertyDescriptor;\n definePropertyModule.f = wrappedDefineProperty;\n addGetter(TypedArrayPrototype, 'buffer');\n addGetter(TypedArrayPrototype, 'byteOffset');\n addGetter(TypedArrayPrototype, 'byteLength');\n addGetter(TypedArrayPrototype, 'length');\n }\n\n $({ target: 'Object', stat: true, forced: !NATIVE_ARRAY_BUFFER_VIEWS }, {\n getOwnPropertyDescriptor: wrappedGetOwnPropertyDescriptor,\n defineProperty: wrappedDefineProperty\n });\n\n module.exports = function (TYPE, wrapper, CLAMPED) {\n var BYTES = TYPE.match(/\\d+$/)[0] / 8;\n var CONSTRUCTOR_NAME = TYPE + (CLAMPED ? 'Clamped' : '') + 'Array';\n var GETTER = 'get' + TYPE;\n var SETTER = 'set' + TYPE;\n var NativeTypedArrayConstructor = global[CONSTRUCTOR_NAME];\n var TypedArrayConstructor = NativeTypedArrayConstructor;\n var TypedArrayConstructorPrototype = TypedArrayConstructor && TypedArrayConstructor.prototype;\n var exported = {};\n\n var getter = function (that, index) {\n var data = getInternalState(that);\n return data.view[GETTER](index * BYTES + data.byteOffset, true);\n };\n\n var setter = function (that, index, value) {\n var data = getInternalState(that);\n if (CLAMPED) value = (value = round(value)) < 0 ? 0 : value > 0xFF ? 0xFF : value & 0xFF;\n data.view[SETTER](index * BYTES + data.byteOffset, value, true);\n };\n\n var addElement = function (that, index) {\n nativeDefineProperty(that, index, {\n get: function () {\n return getter(this, index);\n },\n set: function (value) {\n return setter(this, index, value);\n },\n enumerable: true\n });\n };\n\n if (!NATIVE_ARRAY_BUFFER_VIEWS) {\n TypedArrayConstructor = wrapper(function (that, data, offset, $length) {\n anInstance(that, TypedArrayConstructor, CONSTRUCTOR_NAME);\n var index = 0;\n var byteOffset = 0;\n var buffer, byteLength, length;\n if (!isObject(data)) {\n length = toIndex(data);\n byteLength = length * BYTES;\n buffer = new ArrayBuffer(byteLength);\n } else if (isArrayBuffer(data)) {\n buffer = data;\n byteOffset = toOffset(offset, BYTES);\n var $len = data.byteLength;\n if ($length === undefined) {\n if ($len % BYTES) throw RangeError(WRONG_LENGTH);\n byteLength = $len - byteOffset;\n if (byteLength < 0) throw RangeError(WRONG_LENGTH);\n } else {\n byteLength = toLength($length) * BYTES;\n if (byteLength + byteOffset > $len) throw RangeError(WRONG_LENGTH);\n }\n length = byteLength / BYTES;\n } else if (isTypedArray(data)) {\n return fromList(TypedArrayConstructor, data);\n } else {\n return typedArrayFrom.call(TypedArrayConstructor, data);\n }\n setInternalState(that, {\n buffer: buffer,\n byteOffset: byteOffset,\n byteLength: byteLength,\n length: length,\n view: new DataView(buffer)\n });\n while (index < length) addElement(that, index++);\n });\n\n if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);\n TypedArrayConstructorPrototype = TypedArrayConstructor.prototype = create(TypedArrayPrototype);\n } else if (TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS) {\n TypedArrayConstructor = wrapper(function (dummy, data, typedArrayOffset, $length) {\n anInstance(dummy, TypedArrayConstructor, CONSTRUCTOR_NAME);\n return inheritIfRequired(function () {\n if (!isObject(data)) return new NativeTypedArrayConstructor(toIndex(data));\n if (isArrayBuffer(data)) return $length !== undefined\n ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES), $length)\n : typedArrayOffset !== undefined\n ? new NativeTypedArrayConstructor(data, toOffset(typedArrayOffset, BYTES))\n : new NativeTypedArrayConstructor(data);\n if (isTypedArray(data)) return fromList(TypedArrayConstructor, data);\n return typedArrayFrom.call(TypedArrayConstructor, data);\n }(), dummy, TypedArrayConstructor);\n });\n\n if (setPrototypeOf) setPrototypeOf(TypedArrayConstructor, TypedArray);\n forEach(getOwnPropertyNames(NativeTypedArrayConstructor), function (key) {\n if (!(key in TypedArrayConstructor)) {\n createNonEnumerableProperty(TypedArrayConstructor, key, NativeTypedArrayConstructor[key]);\n }\n });\n TypedArrayConstructor.prototype = TypedArrayConstructorPrototype;\n }\n\n if (TypedArrayConstructorPrototype.constructor !== TypedArrayConstructor) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, 'constructor', TypedArrayConstructor);\n }\n\n if (TYPED_ARRAY_TAG) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, TYPED_ARRAY_TAG, CONSTRUCTOR_NAME);\n }\n\n exported[CONSTRUCTOR_NAME] = TypedArrayConstructor;\n\n $({\n global: true, forced: TypedArrayConstructor != NativeTypedArrayConstructor, sham: !NATIVE_ARRAY_BUFFER_VIEWS\n }, exported);\n\n if (!(BYTES_PER_ELEMENT in TypedArrayConstructor)) {\n createNonEnumerableProperty(TypedArrayConstructor, BYTES_PER_ELEMENT, BYTES);\n }\n\n if (!(BYTES_PER_ELEMENT in TypedArrayConstructorPrototype)) {\n createNonEnumerableProperty(TypedArrayConstructorPrototype, BYTES_PER_ELEMENT, BYTES);\n }\n\n setSpecies(CONSTRUCTOR_NAME);\n };\n} else module.exports = function () { /* empty */ };\n","var createTypedArrayConstructor = require('../internals/typed-array-constructor');\n\n// `Uint8Array` constructor\n// https://tc39.es/ecma262/#sec-typedarray-objects\ncreateTypedArrayConstructor('Uint8', function (init) {\n return function Uint8Array(data, byteOffset, length) {\n return init(this, data, byteOffset, length);\n };\n});\n","'use strict';\nvar toObject = require('../internals/to-object');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar toLength = require('../internals/to-length');\n\nvar min = Math.min;\n\n// `Array.prototype.copyWithin` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.copywithin\nmodule.exports = [].copyWithin || function copyWithin(target /* = 0 */, start /* = 0, end = @length */) {\n var O = toObject(this);\n var len = toLength(O.length);\n var to = toAbsoluteIndex(target, len);\n var from = toAbsoluteIndex(start, len);\n var end = arguments.length > 2 ? arguments[2] : undefined;\n var count = min((end === undefined ? len : toAbsoluteIndex(end, len)) - from, len - to);\n var inc = 1;\n if (from < to && to < from + count) {\n inc = -1;\n from += count - 1;\n to += count - 1;\n }\n while (count-- > 0) {\n if (from in O) O[to] = O[from];\n else delete O[to];\n to += inc;\n from += inc;\n } return O;\n};\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $copyWithin = require('../internals/array-copy-within');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.copyWithin` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.copywithin\nexportTypedArrayMethod('copyWithin', function copyWithin(target, start /* , end */) {\n return $copyWithin.call(aTypedArray(this), target, start, arguments.length > 2 ? arguments[2] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $every = require('../internals/array-iteration').every;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.every` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.every\nexportTypedArrayMethod('every', function every(callbackfn /* , thisArg */) {\n return $every(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $fill = require('../internals/array-fill');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.fill` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.fill\n// eslint-disable-next-line no-unused-vars\nexportTypedArrayMethod('fill', function fill(value /* , start, end */) {\n return $fill.apply(aTypedArray(this), arguments);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $filter = require('../internals/array-iteration').filter;\nvar speciesConstructor = require('../internals/species-constructor');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.filter` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.filter\nexportTypedArrayMethod('filter', function filter(callbackfn /* , thisArg */) {\n var list = $filter(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n var C = speciesConstructor(this, this.constructor);\n var index = 0;\n var length = list.length;\n var result = new (aTypedArrayConstructor(C))(length);\n while (length > index) result[index] = list[index++];\n return result;\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $find = require('../internals/array-iteration').find;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.find` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.find\nexportTypedArrayMethod('find', function find(predicate /* , thisArg */) {\n return $find(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $findIndex = require('../internals/array-iteration').findIndex;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.findIndex` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.findindex\nexportTypedArrayMethod('findIndex', function findIndex(predicate /* , thisArg */) {\n return $findIndex(aTypedArray(this), predicate, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $forEach = require('../internals/array-iteration').forEach;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.forEach` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.foreach\nexportTypedArrayMethod('forEach', function forEach(callbackfn /* , thisArg */) {\n $forEach(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $includes = require('../internals/array-includes').includes;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.includes` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.includes\nexportTypedArrayMethod('includes', function includes(searchElement /* , fromIndex */) {\n return $includes(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $indexOf = require('../internals/array-includes').indexOf;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.indexOf` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.indexof\nexportTypedArrayMethod('indexOf', function indexOf(searchElement /* , fromIndex */) {\n return $indexOf(aTypedArray(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar global = require('../internals/global');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar ArrayIterators = require('../modules/es.array.iterator');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar Uint8Array = global.Uint8Array;\nvar arrayValues = ArrayIterators.values;\nvar arrayKeys = ArrayIterators.keys;\nvar arrayEntries = ArrayIterators.entries;\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar nativeTypedArrayIterator = Uint8Array && Uint8Array.prototype[ITERATOR];\n\nvar CORRECT_ITER_NAME = !!nativeTypedArrayIterator\n && (nativeTypedArrayIterator.name == 'values' || nativeTypedArrayIterator.name == undefined);\n\nvar typedArrayValues = function values() {\n return arrayValues.call(aTypedArray(this));\n};\n\n// `%TypedArray%.prototype.entries` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.entries\nexportTypedArrayMethod('entries', function entries() {\n return arrayEntries.call(aTypedArray(this));\n});\n// `%TypedArray%.prototype.keys` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.keys\nexportTypedArrayMethod('keys', function keys() {\n return arrayKeys.call(aTypedArray(this));\n});\n// `%TypedArray%.prototype.values` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.values\nexportTypedArrayMethod('values', typedArrayValues, !CORRECT_ITER_NAME);\n// `%TypedArray%.prototype[@@iterator]` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype-@@iterator\nexportTypedArrayMethod(ITERATOR, typedArrayValues, !CORRECT_ITER_NAME);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar $join = [].join;\n\n// `%TypedArray%.prototype.join` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.join\n// eslint-disable-next-line no-unused-vars\nexportTypedArrayMethod('join', function join(separator) {\n return $join.apply(aTypedArray(this), arguments);\n});\n","'use strict';\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar toInteger = require('../internals/to-integer');\nvar toLength = require('../internals/to-length');\nvar arrayMethodIsStrict = require('../internals/array-method-is-strict');\nvar arrayMethodUsesToLength = require('../internals/array-method-uses-to-length');\n\nvar min = Math.min;\nvar nativeLastIndexOf = [].lastIndexOf;\nvar NEGATIVE_ZERO = !!nativeLastIndexOf && 1 / [1].lastIndexOf(1, -0) < 0;\nvar STRICT_METHOD = arrayMethodIsStrict('lastIndexOf');\n// For preventing possible almost infinite loop in non-standard implementations, test the forward version of the method\nvar USES_TO_LENGTH = arrayMethodUsesToLength('indexOf', { ACCESSORS: true, 1: 0 });\nvar FORCED = NEGATIVE_ZERO || !STRICT_METHOD || !USES_TO_LENGTH;\n\n// `Array.prototype.lastIndexOf` method implementation\n// https://tc39.es/ecma262/#sec-array.prototype.lastindexof\nmodule.exports = FORCED ? function lastIndexOf(searchElement /* , fromIndex = @[*-1] */) {\n // convert -0 to +0\n if (NEGATIVE_ZERO) return nativeLastIndexOf.apply(this, arguments) || 0;\n var O = toIndexedObject(this);\n var length = toLength(O.length);\n var index = length - 1;\n if (arguments.length > 1) index = min(index, toInteger(arguments[1]));\n if (index < 0) index = length + index;\n for (;index >= 0; index--) if (index in O && O[index] === searchElement) return index || 0;\n return -1;\n} : nativeLastIndexOf;\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $lastIndexOf = require('../internals/array-last-index-of');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.lastIndexOf` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.lastindexof\n// eslint-disable-next-line no-unused-vars\nexportTypedArrayMethod('lastIndexOf', function lastIndexOf(searchElement /* , fromIndex */) {\n return $lastIndexOf.apply(aTypedArray(this), arguments);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $map = require('../internals/array-iteration').map;\nvar speciesConstructor = require('../internals/species-constructor');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.map` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.map\nexportTypedArrayMethod('map', function map(mapfn /* , thisArg */) {\n return $map(aTypedArray(this), mapfn, arguments.length > 1 ? arguments[1] : undefined, function (O, length) {\n return new (aTypedArrayConstructor(speciesConstructor(O, O.constructor)))(length);\n });\n});\n","var aFunction = require('../internals/a-function');\nvar toObject = require('../internals/to-object');\nvar IndexedObject = require('../internals/indexed-object');\nvar toLength = require('../internals/to-length');\n\n// `Array.prototype.{ reduce, reduceRight }` methods implementation\nvar createMethod = function (IS_RIGHT) {\n return function (that, callbackfn, argumentsLength, memo) {\n aFunction(callbackfn);\n var O = toObject(that);\n var self = IndexedObject(O);\n var length = toLength(O.length);\n var index = IS_RIGHT ? length - 1 : 0;\n var i = IS_RIGHT ? -1 : 1;\n if (argumentsLength < 2) while (true) {\n if (index in self) {\n memo = self[index];\n index += i;\n break;\n }\n index += i;\n if (IS_RIGHT ? index < 0 : length <= index) {\n throw TypeError('Reduce of empty array with no initial value');\n }\n }\n for (;IS_RIGHT ? index >= 0 : length > index; index += i) if (index in self) {\n memo = callbackfn(memo, self[index], index, O);\n }\n return memo;\n };\n};\n\nmodule.exports = {\n // `Array.prototype.reduce` method\n // https://tc39.es/ecma262/#sec-array.prototype.reduce\n left: createMethod(false),\n // `Array.prototype.reduceRight` method\n // https://tc39.es/ecma262/#sec-array.prototype.reduceright\n right: createMethod(true)\n};\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $reduce = require('../internals/array-reduce').left;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.reduce` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduce\nexportTypedArrayMethod('reduce', function reduce(callbackfn /* , initialValue */) {\n return $reduce(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $reduceRight = require('../internals/array-reduce').right;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.reduceRicht` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reduceright\nexportTypedArrayMethod('reduceRight', function reduceRight(callbackfn /* , initialValue */) {\n return $reduceRight(aTypedArray(this), callbackfn, arguments.length, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar floor = Math.floor;\n\n// `%TypedArray%.prototype.reverse` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.reverse\nexportTypedArrayMethod('reverse', function reverse() {\n var that = this;\n var length = aTypedArray(that).length;\n var middle = floor(length / 2);\n var index = 0;\n var value;\n while (index < middle) {\n value = that[index];\n that[index++] = that[--length];\n that[length] = value;\n } return that;\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar toLength = require('../internals/to-length');\nvar toOffset = require('../internals/to-offset');\nvar toObject = require('../internals/to-object');\nvar fails = require('../internals/fails');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\nvar FORCED = fails(function () {\n // eslint-disable-next-line no-undef\n new Int8Array(1).set({});\n});\n\n// `%TypedArray%.prototype.set` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.set\nexportTypedArrayMethod('set', function set(arrayLike /* , offset */) {\n aTypedArray(this);\n var offset = toOffset(arguments.length > 1 ? arguments[1] : undefined, 1);\n var length = this.length;\n var src = toObject(arrayLike);\n var len = toLength(src.length);\n var index = 0;\n if (len + offset > length) throw RangeError('Wrong length');\n while (index < len) this[offset + index] = src[index++];\n}, FORCED);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar speciesConstructor = require('../internals/species-constructor');\nvar fails = require('../internals/fails');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar aTypedArrayConstructor = ArrayBufferViewCore.aTypedArrayConstructor;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar $slice = [].slice;\n\nvar FORCED = fails(function () {\n // eslint-disable-next-line no-undef\n new Int8Array(1).slice();\n});\n\n// `%TypedArray%.prototype.slice` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.slice\nexportTypedArrayMethod('slice', function slice(start, end) {\n var list = $slice.call(aTypedArray(this), start, end);\n var C = speciesConstructor(this, this.constructor);\n var index = 0;\n var length = list.length;\n var result = new (aTypedArrayConstructor(C))(length);\n while (length > index) result[index] = list[index++];\n return result;\n}, FORCED);\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar $some = require('../internals/array-iteration').some;\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.some` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.some\nexportTypedArrayMethod('some', function some(callbackfn /* , thisArg */) {\n return $some(aTypedArray(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar $sort = [].sort;\n\n// `%TypedArray%.prototype.sort` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.sort\nexportTypedArrayMethod('sort', function sort(comparefn) {\n return $sort.call(aTypedArray(this), comparefn);\n});\n","'use strict';\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar toLength = require('../internals/to-length');\nvar toAbsoluteIndex = require('../internals/to-absolute-index');\nvar speciesConstructor = require('../internals/species-constructor');\n\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\n\n// `%TypedArray%.prototype.subarray` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.subarray\nexportTypedArrayMethod('subarray', function subarray(begin, end) {\n var O = aTypedArray(this);\n var length = O.length;\n var beginIndex = toAbsoluteIndex(begin, length);\n return new (speciesConstructor(O, O.constructor))(\n O.buffer,\n O.byteOffset + beginIndex * O.BYTES_PER_ELEMENT,\n toLength((end === undefined ? length : toAbsoluteIndex(end, length)) - beginIndex)\n );\n});\n","'use strict';\nvar global = require('../internals/global');\nvar ArrayBufferViewCore = require('../internals/array-buffer-view-core');\nvar fails = require('../internals/fails');\n\nvar Int8Array = global.Int8Array;\nvar aTypedArray = ArrayBufferViewCore.aTypedArray;\nvar exportTypedArrayMethod = ArrayBufferViewCore.exportTypedArrayMethod;\nvar $toLocaleString = [].toLocaleString;\nvar $slice = [].slice;\n\n// iOS Safari 6.x fails here\nvar TO_LOCALE_STRING_BUG = !!Int8Array && fails(function () {\n $toLocaleString.call(new Int8Array(1));\n});\n\nvar FORCED = fails(function () {\n return [1, 2].toLocaleString() != new Int8Array([1, 2]).toLocaleString();\n}) || !fails(function () {\n Int8Array.prototype.toLocaleString.call([1, 2]);\n});\n\n// `%TypedArray%.prototype.toLocaleString` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tolocalestring\nexportTypedArrayMethod('toLocaleString', function toLocaleString() {\n return $toLocaleString.apply(TO_LOCALE_STRING_BUG ? $slice.call(aTypedArray(this)) : aTypedArray(this), arguments);\n}, FORCED);\n","'use strict';\nvar exportTypedArrayMethod = require('../internals/array-buffer-view-core').exportTypedArrayMethod;\nvar fails = require('../internals/fails');\nvar global = require('../internals/global');\n\nvar Uint8Array = global.Uint8Array;\nvar Uint8ArrayPrototype = Uint8Array && Uint8Array.prototype || {};\nvar arrayToString = [].toString;\nvar arrayJoin = [].join;\n\nif (fails(function () { arrayToString.call({}); })) {\n arrayToString = function toString() {\n return arrayJoin.call(this);\n };\n}\n\nvar IS_NOT_ARRAY_METHOD = Uint8ArrayPrototype.toString != arrayToString;\n\n// `%TypedArray%.prototype.toString` method\n// https://tc39.es/ecma262/#sec-%typedarray%.prototype.tostring\nexportTypedArrayMethod('toString', arrayToString, IS_NOT_ARRAY_METHOD);\n","'use strict';\nvar $ = require('../internals/export');\n\n// `URL.prototype.toJSON` method\n// https://url.spec.whatwg.org/#dom-url-tojson\n$({ target: 'URL', proto: true, enumerable: true }, {\n toJSON: function toJSON() {\n return URL.prototype.toString.call(this);\n }\n});\n","\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\nvar inited = false;\nfunction init () {\n inited = true;\n var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n for (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n }\n\n revLookup['-'.charCodeAt(0)] = 62\n revLookup['_'.charCodeAt(0)] = 63\n}\n\nexport function toByteArray (b64) {\n if (!inited) {\n init();\n }\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n\n // base64 is 4/3 + up to two characters of the original data\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nexport function fromByteArray (uint8) {\n if (!inited) {\n init();\n }\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n","\nexport function read (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexport function write (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n\nimport * as base64 from './base64'\nimport * as ieee754 from './ieee754'\nimport isArray from './isArray'\n\nexport var INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : true\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nvar _kMaxLength = kMaxLength()\nexport {_kMaxLength as kMaxLength};\nfunction typedArraySupport () {\n return true;\n // rollup issues\n // try {\n // var arr = new Uint8Array(1)\n // arr.__proto__ = {\n // __proto__: Uint8Array.prototype,\n // foo: function () { return 42 }\n // }\n // return arr.foo() === 42 && // typed array instances can be augmented\n // typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n // arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n // } catch (e) {\n // return false\n // }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nexport function Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n // Object.defineProperty(Buffer, Symbol.species, {\n // value: null,\n // configurable: true\n // })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (internalIsBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nexport function SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\nBuffer.isBuffer = isBuffer;\nfunction internalIsBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!internalIsBuffer(a) || !internalIsBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!internalIsBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (internalIsBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!internalIsBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (internalIsBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!internalIsBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = internalIsBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n\n// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nexport function isBuffer(obj) {\n return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))\n}\n\nfunction isFastBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))\n}\n","// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nif (typeof global.setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n}\nif (typeof global.clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n}\n\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nfunction nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nvar title = 'browser';\nvar platform = 'browser';\nvar browser = true;\nvar env = {};\nvar argv = [];\nvar version = ''; // empty string to avoid regexp issues\nvar versions = {};\nvar release = {};\nvar config = {};\n\nfunction noop() {}\n\nvar on = noop;\nvar addListener = noop;\nvar once = noop;\nvar off = noop;\nvar removeListener = noop;\nvar removeAllListeners = noop;\nvar emit = noop;\n\nfunction binding(name) {\n throw new Error('process.binding is not supported');\n}\n\nfunction cwd () { return '/' }\nfunction chdir (dir) {\n throw new Error('process.chdir is not supported');\n}function umask() { return 0; }\n\n// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js\nvar performance = global.performance || {};\nvar performanceNow =\n performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function(){ return (new Date()).getTime() };\n\n// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nfunction hrtime(previousTimestamp){\n var clocktime = performanceNow.call(performance)*1e-3;\n var seconds = Math.floor(clocktime);\n var nanoseconds = Math.floor((clocktime%1)*1e9);\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0];\n nanoseconds = nanoseconds - previousTimestamp[1];\n if (nanoseconds<0) {\n seconds--;\n nanoseconds += 1e9;\n }\n }\n return [seconds,nanoseconds]\n}\n\nvar startTime = new Date();\nfunction uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1000;\n}\n\nvar browser$1 = {\n nextTick: nextTick,\n title: title,\n browser: browser,\n env: env,\n argv: argv,\n version: version,\n versions: versions,\n on: on,\n addListener: addListener,\n once: once,\n off: off,\n removeListener: removeListener,\n removeAllListeners: removeAllListeners,\n emit: emit,\n binding: binding,\n cwd: cwd,\n chdir: chdir,\n umask: umask,\n hrtime: hrtime,\n platform: platform,\n release: release,\n config: config,\n uptime: uptime\n};\n\nexport default browser$1;\nexport { addListener, argv, binding, browser, chdir, config, cwd, emit, env, hrtime, nextTick, off, on, once, platform, release, removeAllListeners, removeListener, title, umask, uptime, version, versions };\n","\nvar inherits;\nif (typeof Object.create === 'function'){\n inherits = function inherits(ctor, superCtor) {\n // implementation from standard node.js 'util' module\n ctor.super_ = superCtor\n ctor.prototype = Object.create(superCtor.prototype, {\n constructor: {\n value: ctor,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n };\n} else {\n inherits = function inherits(ctor, superCtor) {\n ctor.super_ = superCtor\n var TempCtor = function () {}\n TempCtor.prototype = superCtor.prototype\n ctor.prototype = new TempCtor()\n ctor.prototype.constructor = ctor\n }\n}\nexport default inherits;\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\nimport process from 'process';\nvar formatRegExp = /%[sdj%]/g;\nexport function format(f) {\n if (!isString(f)) {\n var objects = [];\n for (var i = 0; i < arguments.length; i++) {\n objects.push(inspect(arguments[i]));\n }\n return objects.join(' ');\n }\n\n var i = 1;\n var args = arguments;\n var len = args.length;\n var str = String(f).replace(formatRegExp, function(x) {\n if (x === '%%') return '%';\n if (i >= len) return x;\n switch (x) {\n case '%s': return String(args[i++]);\n case '%d': return Number(args[i++]);\n case '%j':\n try {\n return JSON.stringify(args[i++]);\n } catch (_) {\n return '[Circular]';\n }\n default:\n return x;\n }\n });\n for (var x = args[i]; i < len; x = args[++i]) {\n if (isNull(x) || !isObject(x)) {\n str += ' ' + x;\n } else {\n str += ' ' + inspect(x);\n }\n }\n return str;\n};\n\n\n// Mark that a method should not be used.\n// Returns a modified function which warns once by default.\n// If --no-deprecation is set, then it is a no-op.\nexport function deprecate(fn, msg) {\n // Allow for deprecating things in the process of starting up.\n if (isUndefined(global.process)) {\n return function() {\n return deprecate(fn, msg).apply(this, arguments);\n };\n }\n\n if (process.noDeprecation === true) {\n return fn;\n }\n\n var warned = false;\n function deprecated() {\n if (!warned) {\n if (process.throwDeprecation) {\n throw new Error(msg);\n } else if (process.traceDeprecation) {\n console.trace(msg);\n } else {\n console.error(msg);\n }\n warned = true;\n }\n return fn.apply(this, arguments);\n }\n\n return deprecated;\n};\n\n\nvar debugs = {};\nvar debugEnviron;\nexport function debuglog(set) {\n if (isUndefined(debugEnviron))\n debugEnviron = process.env.NODE_DEBUG || '';\n set = set.toUpperCase();\n if (!debugs[set]) {\n if (new RegExp('\\\\b' + set + '\\\\b', 'i').test(debugEnviron)) {\n var pid = 0;\n debugs[set] = function() {\n var msg = format.apply(null, arguments);\n console.error('%s %d: %s', set, pid, msg);\n };\n } else {\n debugs[set] = function() {};\n }\n }\n return debugs[set];\n};\n\n\n/**\n * Echos the value of a value. Trys to print the value out\n * in the best way possible given the different types.\n *\n * @param {Object} obj The object to print out.\n * @param {Object} opts Optional options object that alters the output.\n */\n/* legacy: obj, showHidden, depth, colors*/\nexport function inspect(obj, opts) {\n // default options\n var ctx = {\n seen: [],\n stylize: stylizeNoColor\n };\n // legacy...\n if (arguments.length >= 3) ctx.depth = arguments[2];\n if (arguments.length >= 4) ctx.colors = arguments[3];\n if (isBoolean(opts)) {\n // legacy...\n ctx.showHidden = opts;\n } else if (opts) {\n // got an \"options\" object\n _extend(ctx, opts);\n }\n // set default options\n if (isUndefined(ctx.showHidden)) ctx.showHidden = false;\n if (isUndefined(ctx.depth)) ctx.depth = 2;\n if (isUndefined(ctx.colors)) ctx.colors = false;\n if (isUndefined(ctx.customInspect)) ctx.customInspect = true;\n if (ctx.colors) ctx.stylize = stylizeWithColor;\n return formatValue(ctx, obj, ctx.depth);\n}\n\n// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics\ninspect.colors = {\n 'bold' : [1, 22],\n 'italic' : [3, 23],\n 'underline' : [4, 24],\n 'inverse' : [7, 27],\n 'white' : [37, 39],\n 'grey' : [90, 39],\n 'black' : [30, 39],\n 'blue' : [34, 39],\n 'cyan' : [36, 39],\n 'green' : [32, 39],\n 'magenta' : [35, 39],\n 'red' : [31, 39],\n 'yellow' : [33, 39]\n};\n\n// Don't use 'blue' not visible on cmd.exe\ninspect.styles = {\n 'special': 'cyan',\n 'number': 'yellow',\n 'boolean': 'yellow',\n 'undefined': 'grey',\n 'null': 'bold',\n 'string': 'green',\n 'date': 'magenta',\n // \"name\": intentionally not styling\n 'regexp': 'red'\n};\n\n\nfunction stylizeWithColor(str, styleType) {\n var style = inspect.styles[styleType];\n\n if (style) {\n return '\\u001b[' + inspect.colors[style][0] + 'm' + str +\n '\\u001b[' + inspect.colors[style][1] + 'm';\n } else {\n return str;\n }\n}\n\n\nfunction stylizeNoColor(str, styleType) {\n return str;\n}\n\n\nfunction arrayToHash(array) {\n var hash = {};\n\n array.forEach(function(val, idx) {\n hash[val] = true;\n });\n\n return hash;\n}\n\n\nfunction formatValue(ctx, value, recurseTimes) {\n // Provide a hook for user-specified inspect functions.\n // Check that value is an object with an inspect function on it\n if (ctx.customInspect &&\n value &&\n isFunction(value.inspect) &&\n // Filter out the util module, it's inspect function is special\n value.inspect !== inspect &&\n // Also filter out any prototype objects using the circular check.\n !(value.constructor && value.constructor.prototype === value)) {\n var ret = value.inspect(recurseTimes, ctx);\n if (!isString(ret)) {\n ret = formatValue(ctx, ret, recurseTimes);\n }\n return ret;\n }\n\n // Primitive types cannot have properties\n var primitive = formatPrimitive(ctx, value);\n if (primitive) {\n return primitive;\n }\n\n // Look up the keys of the object.\n var keys = Object.keys(value);\n var visibleKeys = arrayToHash(keys);\n\n if (ctx.showHidden) {\n keys = Object.getOwnPropertyNames(value);\n }\n\n // IE doesn't make error fields non-enumerable\n // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx\n if (isError(value)\n && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {\n return formatError(value);\n }\n\n // Some type of object without properties can be shortcutted.\n if (keys.length === 0) {\n if (isFunction(value)) {\n var name = value.name ? ': ' + value.name : '';\n return ctx.stylize('[Function' + name + ']', 'special');\n }\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n }\n if (isDate(value)) {\n return ctx.stylize(Date.prototype.toString.call(value), 'date');\n }\n if (isError(value)) {\n return formatError(value);\n }\n }\n\n var base = '', array = false, braces = ['{', '}'];\n\n // Make Array say that they are Array\n if (isArray(value)) {\n array = true;\n braces = ['[', ']'];\n }\n\n // Make functions say that they are functions\n if (isFunction(value)) {\n var n = value.name ? ': ' + value.name : '';\n base = ' [Function' + n + ']';\n }\n\n // Make RegExps say that they are RegExps\n if (isRegExp(value)) {\n base = ' ' + RegExp.prototype.toString.call(value);\n }\n\n // Make dates with properties first say the date\n if (isDate(value)) {\n base = ' ' + Date.prototype.toUTCString.call(value);\n }\n\n // Make error with message first say the error\n if (isError(value)) {\n base = ' ' + formatError(value);\n }\n\n if (keys.length === 0 && (!array || value.length == 0)) {\n return braces[0] + base + braces[1];\n }\n\n if (recurseTimes < 0) {\n if (isRegExp(value)) {\n return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');\n } else {\n return ctx.stylize('[Object]', 'special');\n }\n }\n\n ctx.seen.push(value);\n\n var output;\n if (array) {\n output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);\n } else {\n output = keys.map(function(key) {\n return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);\n });\n }\n\n ctx.seen.pop();\n\n return reduceToSingleString(output, base, braces);\n}\n\n\nfunction formatPrimitive(ctx, value) {\n if (isUndefined(value))\n return ctx.stylize('undefined', 'undefined');\n if (isString(value)) {\n var simple = '\\'' + JSON.stringify(value).replace(/^\"|\"$/g, '')\n .replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"') + '\\'';\n return ctx.stylize(simple, 'string');\n }\n if (isNumber(value))\n return ctx.stylize('' + value, 'number');\n if (isBoolean(value))\n return ctx.stylize('' + value, 'boolean');\n // For some reason typeof null is \"object\", so special case here.\n if (isNull(value))\n return ctx.stylize('null', 'null');\n}\n\n\nfunction formatError(value) {\n return '[' + Error.prototype.toString.call(value) + ']';\n}\n\n\nfunction formatArray(ctx, value, recurseTimes, visibleKeys, keys) {\n var output = [];\n for (var i = 0, l = value.length; i < l; ++i) {\n if (hasOwnProperty(value, String(i))) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n String(i), true));\n } else {\n output.push('');\n }\n }\n keys.forEach(function(key) {\n if (!key.match(/^\\d+$/)) {\n output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,\n key, true));\n }\n });\n return output;\n}\n\n\nfunction formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {\n var name, str, desc;\n desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };\n if (desc.get) {\n if (desc.set) {\n str = ctx.stylize('[Getter/Setter]', 'special');\n } else {\n str = ctx.stylize('[Getter]', 'special');\n }\n } else {\n if (desc.set) {\n str = ctx.stylize('[Setter]', 'special');\n }\n }\n if (!hasOwnProperty(visibleKeys, key)) {\n name = '[' + key + ']';\n }\n if (!str) {\n if (ctx.seen.indexOf(desc.value) < 0) {\n if (isNull(recurseTimes)) {\n str = formatValue(ctx, desc.value, null);\n } else {\n str = formatValue(ctx, desc.value, recurseTimes - 1);\n }\n if (str.indexOf('\\n') > -1) {\n if (array) {\n str = str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n').substr(2);\n } else {\n str = '\\n' + str.split('\\n').map(function(line) {\n return ' ' + line;\n }).join('\\n');\n }\n }\n } else {\n str = ctx.stylize('[Circular]', 'special');\n }\n }\n if (isUndefined(name)) {\n if (array && key.match(/^\\d+$/)) {\n return str;\n }\n name = JSON.stringify('' + key);\n if (name.match(/^\"([a-zA-Z_][a-zA-Z_0-9]*)\"$/)) {\n name = name.substr(1, name.length - 2);\n name = ctx.stylize(name, 'name');\n } else {\n name = name.replace(/'/g, \"\\\\'\")\n .replace(/\\\\\"/g, '\"')\n .replace(/(^\"|\"$)/g, \"'\");\n name = ctx.stylize(name, 'string');\n }\n }\n\n return name + ': ' + str;\n}\n\n\nfunction reduceToSingleString(output, base, braces) {\n var numLinesEst = 0;\n var length = output.reduce(function(prev, cur) {\n numLinesEst++;\n if (cur.indexOf('\\n') >= 0) numLinesEst++;\n return prev + cur.replace(/\\u001b\\[\\d\\d?m/g, '').length + 1;\n }, 0);\n\n if (length > 60) {\n return braces[0] +\n (base === '' ? '' : base + '\\n ') +\n ' ' +\n output.join(',\\n ') +\n ' ' +\n braces[1];\n }\n\n return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];\n}\n\n\n// NOTE: These type checking functions intentionally don't use `instanceof`\n// because it is fragile and can be easily faked with `Object.create()`.\nexport function isArray(ar) {\n return Array.isArray(ar);\n}\n\nexport function isBoolean(arg) {\n return typeof arg === 'boolean';\n}\n\nexport function isNull(arg) {\n return arg === null;\n}\n\nexport function isNullOrUndefined(arg) {\n return arg == null;\n}\n\nexport function isNumber(arg) {\n return typeof arg === 'number';\n}\n\nexport function isString(arg) {\n return typeof arg === 'string';\n}\n\nexport function isSymbol(arg) {\n return typeof arg === 'symbol';\n}\n\nexport function isUndefined(arg) {\n return arg === void 0;\n}\n\nexport function isRegExp(re) {\n return isObject(re) && objectToString(re) === '[object RegExp]';\n}\n\nexport function isObject(arg) {\n return typeof arg === 'object' && arg !== null;\n}\n\nexport function isDate(d) {\n return isObject(d) && objectToString(d) === '[object Date]';\n}\n\nexport function isError(e) {\n return isObject(e) &&\n (objectToString(e) === '[object Error]' || e instanceof Error);\n}\n\nexport function isFunction(arg) {\n return typeof arg === 'function';\n}\n\nexport function isPrimitive(arg) {\n return arg === null ||\n typeof arg === 'boolean' ||\n typeof arg === 'number' ||\n typeof arg === 'string' ||\n typeof arg === 'symbol' || // ES6 symbol\n typeof arg === 'undefined';\n}\n\nexport function isBuffer(maybeBuf) {\n return Buffer.isBuffer(maybeBuf);\n}\n\nfunction objectToString(o) {\n return Object.prototype.toString.call(o);\n}\n\n\nfunction pad(n) {\n return n < 10 ? '0' + n.toString(10) : n.toString(10);\n}\n\n\nvar months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',\n 'Oct', 'Nov', 'Dec'];\n\n// 26 Feb 16:19:34\nfunction timestamp() {\n var d = new Date();\n var time = [pad(d.getHours()),\n pad(d.getMinutes()),\n pad(d.getSeconds())].join(':');\n return [d.getDate(), months[d.getMonth()], time].join(' ');\n}\n\n\n// log is just a thin wrapper to console.log that prepends a timestamp\nexport function log() {\n console.log('%s - %s', timestamp(), format.apply(null, arguments));\n}\n\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * The Function.prototype.inherits from lang.js rewritten as a standalone\n * function (not on Function.prototype). NOTE: If this file is to be loaded\n * during bootstrapping this function needs to be rewritten using some native\n * functions as prototype setup using normal JavaScript does not work as\n * expected during bootstrapping (see mirror.js in r114903).\n *\n * @param {function} ctor Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor Constructor function to inherit prototype from.\n */\nimport inherits from './inherits';\nexport {inherits}\n\nexport function _extend(origin, add) {\n // Don't do anything if add isn't an object\n if (!add || !isObject(add)) return origin;\n\n var keys = Object.keys(add);\n var i = keys.length;\n while (i--) {\n origin[keys[i]] = add[keys[i]];\n }\n return origin;\n};\n\nfunction hasOwnProperty(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nexport default {\n inherits: inherits,\n _extend: _extend,\n log: log,\n isBuffer: isBuffer,\n isPrimitive: isPrimitive,\n isFunction: isFunction,\n isError: isError,\n isDate: isDate,\n isObject: isObject,\n isRegExp: isRegExp,\n isUndefined: isUndefined,\n isSymbol: isSymbol,\n isString: isString,\n isNumber: isNumber,\n isNullOrUndefined: isNullOrUndefined,\n isNull: isNull,\n isBoolean: isBoolean,\n isArray: isArray,\n inspect: inspect,\n deprecate: deprecate,\n format: format,\n debuglog: debuglog\n}\n","var lookup = [];\nvar revLookup = [];\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array;\nvar inited = false;\nfunction init () {\n inited = true;\n var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n for (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i];\n revLookup[code.charCodeAt(i)] = i;\n }\n\n revLookup['-'.charCodeAt(0)] = 62;\n revLookup['_'.charCodeAt(0)] = 63;\n}\n\nfunction toByteArray (b64) {\n if (!inited) {\n init();\n }\n var i, j, l, tmp, placeHolders, arr;\n var len = b64.length;\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0;\n\n // base64 is 4/3 + up to two characters of the original data\n arr = new Arr(len * 3 / 4 - placeHolders);\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len;\n\n var L = 0;\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)];\n arr[L++] = (tmp >> 16) & 0xFF;\n arr[L++] = (tmp >> 8) & 0xFF;\n arr[L++] = tmp & 0xFF;\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4);\n arr[L++] = tmp & 0xFF;\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2);\n arr[L++] = (tmp >> 8) & 0xFF;\n arr[L++] = tmp & 0xFF;\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp;\n var output = [];\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]);\n output.push(tripletToBase64(tmp));\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n if (!inited) {\n init();\n }\n var tmp;\n var len = uint8.length;\n var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes\n var output = '';\n var parts = [];\n var maxChunkLength = 16383; // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)));\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1];\n output += lookup[tmp >> 2];\n output += lookup[(tmp << 4) & 0x3F];\n output += '==';\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1]);\n output += lookup[tmp >> 10];\n output += lookup[(tmp >> 4) & 0x3F];\n output += lookup[(tmp << 2) & 0x3F];\n output += '=';\n }\n\n parts.push(output);\n\n return parts.join('')\n}\n\nfunction read (buffer, offset, isLE, mLen, nBytes) {\n var e, m;\n var eLen = nBytes * 8 - mLen - 1;\n var eMax = (1 << eLen) - 1;\n var eBias = eMax >> 1;\n var nBits = -7;\n var i = isLE ? (nBytes - 1) : 0;\n var d = isLE ? -1 : 1;\n var s = buffer[offset + i];\n\n i += d;\n\n e = s & ((1 << (-nBits)) - 1);\n s >>= (-nBits);\n nBits += eLen;\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1);\n e >>= (-nBits);\n nBits += mLen;\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias;\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen);\n e = e - eBias;\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nfunction write (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c;\n var eLen = nBytes * 8 - mLen - 1;\n var eMax = (1 << eLen) - 1;\n var eBias = eMax >> 1;\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0);\n var i = isLE ? 0 : (nBytes - 1);\n var d = isLE ? 1 : -1;\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0;\n\n value = Math.abs(value);\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0;\n e = eMax;\n } else {\n e = Math.floor(Math.log(value) / Math.LN2);\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--;\n c *= 2;\n }\n if (e + eBias >= 1) {\n value += rt / c;\n } else {\n value += rt * Math.pow(2, 1 - eBias);\n }\n if (value * c >= 2) {\n e++;\n c /= 2;\n }\n\n if (e + eBias >= eMax) {\n m = 0;\n e = eMax;\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen);\n e = e + eBias;\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen);\n e = 0;\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m;\n eLen += mLen;\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128;\n}\n\nvar toString = {}.toString;\n\nvar isArray = Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n\n/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n\nvar INSPECT_MAX_BYTES = 50;\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : true;\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nvar _kMaxLength = kMaxLength();\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length);\n that.__proto__ = Buffer.prototype;\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length);\n }\n that.length = length;\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192; // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype;\n return arr\n};\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n};\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype;\n Buffer.__proto__ = Uint8Array;\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size);\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n};\n\nfunction allocUnsafe (that, size) {\n assertSize(size);\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0);\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0;\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n};\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n};\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8';\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0;\n that = createBuffer(that, length);\n\n var actual = that.write(string, encoding);\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual);\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0;\n that = createBuffer(that, length);\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255;\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength; // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array);\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset);\n } else {\n array = new Uint8Array(array, byteOffset, length);\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array;\n that.__proto__ = Buffer.prototype;\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array);\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (internalIsBuffer(obj)) {\n var len = checked(obj.length) | 0;\n that = createBuffer(that, len);\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len);\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0;\n }\n return Buffer.alloc(+length)\n}\nBuffer.isBuffer = isBuffer;\nfunction internalIsBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!internalIsBuffer(a) || !internalIsBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length;\n var y = b.length;\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i];\n y = b[i];\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n};\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n};\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i;\n if (length === undefined) {\n length = 0;\n for (i = 0; i < list.length; ++i) {\n length += list[i].length;\n }\n }\n\n var buffer = Buffer.allocUnsafe(length);\n var pos = 0;\n for (i = 0; i < list.length; ++i) {\n var buf = list[i];\n if (!internalIsBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos);\n pos += buf.length;\n }\n return buffer\n};\n\nfunction byteLength (string, encoding) {\n if (internalIsBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string;\n }\n\n var len = string.length;\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false;\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase();\n loweredCase = true;\n }\n }\n}\nBuffer.byteLength = byteLength;\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false;\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0;\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length;\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0;\n start >>>= 0;\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8';\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase();\n loweredCase = true;\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true;\n\nfunction swap (b, n, m) {\n var i = b[n];\n b[n] = b[m];\n b[m] = i;\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length;\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1);\n }\n return this\n};\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length;\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3);\n swap(this, i + 1, i + 2);\n }\n return this\n};\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length;\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7);\n swap(this, i + 1, i + 6);\n swap(this, i + 2, i + 5);\n swap(this, i + 3, i + 4);\n }\n return this\n};\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0;\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n};\n\nBuffer.prototype.equals = function equals (b) {\n if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n};\n\nBuffer.prototype.inspect = function inspect () {\n var str = '';\n var max = INSPECT_MAX_BYTES;\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ');\n if (this.length > max) str += ' ... ';\n }\n return ''\n};\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!internalIsBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0;\n }\n if (end === undefined) {\n end = target ? target.length : 0;\n }\n if (thisStart === undefined) {\n thisStart = 0;\n }\n if (thisEnd === undefined) {\n thisEnd = this.length;\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0;\n end >>>= 0;\n thisStart >>>= 0;\n thisEnd >>>= 0;\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart;\n var y = end - start;\n var len = Math.min(x, y);\n\n var thisCopy = this.slice(thisStart, thisEnd);\n var targetCopy = target.slice(start, end);\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i];\n y = targetCopy[i];\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n};\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset;\n byteOffset = 0;\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff;\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000;\n }\n byteOffset = +byteOffset; // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1);\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset;\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1;\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0;\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding);\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (internalIsBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF; // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1;\n var arrLength = arr.length;\n var valLength = val.length;\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase();\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2;\n arrLength /= 2;\n valLength /= 2;\n byteOffset /= 2;\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i;\n if (dir) {\n var foundIndex = -1;\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i;\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex;\n foundIndex = -1;\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;\n for (i = byteOffset; i >= 0; i--) {\n var found = true;\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false;\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n};\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n};\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n};\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0;\n var remaining = buf.length - offset;\n if (!length) {\n length = remaining;\n } else {\n length = Number(length);\n if (length > remaining) {\n length = remaining;\n }\n }\n\n // must be an even number of digits\n var strLen = string.length;\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2;\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16);\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed;\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8';\n length = this.length;\n offset = 0;\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset;\n length = this.length;\n offset = 0;\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0;\n if (isFinite(length)) {\n length = length | 0;\n if (encoding === undefined) encoding = 'utf8';\n } else {\n encoding = length;\n length = undefined;\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset;\n if (length === undefined || length > remaining) length = remaining;\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8';\n\n var loweredCase = false;\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase();\n loweredCase = true;\n }\n }\n};\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n};\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return fromByteArray(buf)\n } else {\n return fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end);\n var res = [];\n\n var i = start;\n while (i < end) {\n var firstByte = buf[i];\n var codePoint = null;\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1;\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint;\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte;\n }\n break\n case 2:\n secondByte = buf[i + 1];\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint;\n }\n }\n break\n case 3:\n secondByte = buf[i + 1];\n thirdByte = buf[i + 2];\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint;\n }\n }\n break\n case 4:\n secondByte = buf[i + 1];\n thirdByte = buf[i + 2];\n fourthByte = buf[i + 3];\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint;\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD;\n bytesPerSequence = 1;\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000;\n res.push(codePoint >>> 10 & 0x3FF | 0xD800);\n codePoint = 0xDC00 | codePoint & 0x3FF;\n }\n\n res.push(codePoint);\n i += bytesPerSequence;\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000;\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length;\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = '';\n var i = 0;\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n );\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = '';\n end = Math.min(buf.length, end);\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F);\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = '';\n end = Math.min(buf.length, end);\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i]);\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length;\n\n if (!start || start < 0) start = 0;\n if (!end || end < 0 || end > len) end = len;\n\n var out = '';\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i]);\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end);\n var res = '';\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256);\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length;\n start = ~~start;\n end = end === undefined ? len : ~~end;\n\n if (start < 0) {\n start += len;\n if (start < 0) start = 0;\n } else if (start > len) {\n start = len;\n }\n\n if (end < 0) {\n end += len;\n if (end < 0) end = 0;\n } else if (end > len) {\n end = len;\n }\n\n if (end < start) end = start;\n\n var newBuf;\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end);\n newBuf.__proto__ = Buffer.prototype;\n } else {\n var sliceLen = end - start;\n newBuf = new Buffer(sliceLen, undefined);\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start];\n }\n }\n\n return newBuf\n};\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var val = this[offset];\n var mul = 1;\n var i = 0;\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul;\n }\n\n return val\n};\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length);\n }\n\n var val = this[offset + --byteLength];\n var mul = 1;\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul;\n }\n\n return val\n};\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length);\n return this[offset]\n};\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n return this[offset] | (this[offset + 1] << 8)\n};\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n return (this[offset] << 8) | this[offset + 1]\n};\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n};\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n};\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var val = this[offset];\n var mul = 1;\n var i = 0;\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul;\n }\n mul *= 0x80;\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n return val\n};\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) checkOffset(offset, byteLength, this.length);\n\n var i = byteLength;\n var mul = 1;\n var val = this[offset + --i];\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul;\n }\n mul *= 0x80;\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength);\n\n return val\n};\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length);\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n};\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n var val = this[offset] | (this[offset + 1] << 8);\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n};\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length);\n var val = this[offset + 1] | (this[offset] << 8);\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n};\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n};\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n};\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n return read(this, offset, true, 23, 4)\n};\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length);\n return read(this, offset, false, 23, 4)\n};\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length);\n return read(this, offset, true, 52, 8)\n};\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length);\n return read(this, offset, false, 52, 8)\n};\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!internalIsBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1;\n checkInt(this, value, offset, byteLength, maxBytes, 0);\n }\n\n var mul = 1;\n var i = 0;\n this[offset] = value & 0xFF;\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n byteLength = byteLength | 0;\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1;\n checkInt(this, value, offset, byteLength, maxBytes, 0);\n }\n\n var i = byteLength - 1;\n var mul = 1;\n this[offset + i] = value & 0xFF;\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);\n this[offset] = (value & 0xff);\n return offset + 1\n};\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1;\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8;\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n } else {\n objectWriteUInt16(this, value, offset, true);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8);\n this[offset + 1] = (value & 0xff);\n } else {\n objectWriteUInt16(this, value, offset, false);\n }\n return offset + 2\n};\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1;\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff;\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24);\n this[offset + 2] = (value >>> 16);\n this[offset + 1] = (value >>> 8);\n this[offset] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, true);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24);\n this[offset + 1] = (value >>> 16);\n this[offset + 2] = (value >>> 8);\n this[offset + 3] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, false);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1);\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit);\n }\n\n var i = 0;\n var mul = 1;\n var sub = 0;\n this[offset] = value & 0xFF;\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1;\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1);\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit);\n }\n\n var i = byteLength - 1;\n var mul = 1;\n var sub = 0;\n this[offset + i] = value & 0xFF;\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1;\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;\n }\n\n return offset + byteLength\n};\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value);\n if (value < 0) value = 0xff + value + 1;\n this[offset] = (value & 0xff);\n return offset + 1\n};\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n } else {\n objectWriteUInt16(this, value, offset, true);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8);\n this[offset + 1] = (value & 0xff);\n } else {\n objectWriteUInt16(this, value, offset, false);\n }\n return offset + 2\n};\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff);\n this[offset + 1] = (value >>> 8);\n this[offset + 2] = (value >>> 16);\n this[offset + 3] = (value >>> 24);\n } else {\n objectWriteUInt32(this, value, offset, true);\n }\n return offset + 4\n};\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value;\n offset = offset | 0;\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);\n if (value < 0) value = 0xffffffff + value + 1;\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24);\n this[offset + 1] = (value >>> 16);\n this[offset + 2] = (value >>> 8);\n this[offset + 3] = (value & 0xff);\n } else {\n objectWriteUInt32(this, value, offset, false);\n }\n return offset + 4\n};\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4);\n }\n write(buf, value, offset, littleEndian, 23, 4);\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n};\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n};\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8);\n }\n write(buf, value, offset, littleEndian, 52, 8);\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n};\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n};\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0;\n if (!end && end !== 0) end = this.length;\n if (targetStart >= target.length) targetStart = target.length;\n if (!targetStart) targetStart = 0;\n if (end > 0 && end < start) end = start;\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length;\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start;\n }\n\n var len = end - start;\n var i;\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start];\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start];\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n );\n }\n\n return len\n};\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start;\n start = 0;\n end = this.length;\n } else if (typeof end === 'string') {\n encoding = end;\n end = this.length;\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0);\n if (code < 256) {\n val = code;\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255;\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0;\n end = end === undefined ? this.length : end >>> 0;\n\n if (!val) val = 0;\n\n var i;\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val;\n }\n } else {\n var bytes = internalIsBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString());\n var len = bytes.length;\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len];\n }\n }\n\n return this\n};\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g;\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '');\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '=';\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity;\n var codePoint;\n var length = string.length;\n var leadSurrogate = null;\n var bytes = [];\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i);\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint;\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n leadSurrogate = codePoint;\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);\n }\n\n leadSurrogate = null;\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint);\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n );\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n );\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n );\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = [];\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF);\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo;\n var byteArray = [];\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i);\n hi = c >> 8;\n lo = c % 256;\n byteArray.push(lo);\n byteArray.push(hi);\n }\n\n return byteArray\n}\n\n\nfunction base64ToBytes (str) {\n return toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i];\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n\n// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nfunction isBuffer(obj) {\n return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))\n}\n\nfunction isFastBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))\n}\n\nexport { Buffer, INSPECT_MAX_BYTES, SlowBuffer, isBuffer, _kMaxLength as kMaxLength };\n","import {Buffer} from 'buffer';\n\nexport default BufferList;\n\nfunction BufferList() {\n this.head = null;\n this.tail = null;\n this.length = 0;\n}\n\nBufferList.prototype.push = function (v) {\n var entry = { data: v, next: null };\n if (this.length > 0) this.tail.next = entry;else this.head = entry;\n this.tail = entry;\n ++this.length;\n};\n\nBufferList.prototype.unshift = function (v) {\n var entry = { data: v, next: this.head };\n if (this.length === 0) this.tail = entry;\n this.head = entry;\n ++this.length;\n};\n\nBufferList.prototype.shift = function () {\n if (this.length === 0) return;\n var ret = this.head.data;\n if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;\n --this.length;\n return ret;\n};\n\nBufferList.prototype.clear = function () {\n this.head = this.tail = null;\n this.length = 0;\n};\n\nBufferList.prototype.join = function (s) {\n if (this.length === 0) return '';\n var p = this.head;\n var ret = '' + p.data;\n while (p = p.next) {\n ret += s + p.data;\n }return ret;\n};\n\nBufferList.prototype.concat = function (n) {\n if (this.length === 0) return Buffer.alloc(0);\n if (this.length === 1) return this.head.data;\n var ret = Buffer.allocUnsafe(n >>> 0);\n var p = this.head;\n var i = 0;\n while (p) {\n p.data.copy(ret, i);\n i += p.data.length;\n p = p.next;\n }\n return ret;\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nimport {Buffer} from 'buffer';\nvar isBufferEncoding = Buffer.isEncoding\n || function(encoding) {\n switch (encoding && encoding.toLowerCase()) {\n case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;\n default: return false;\n }\n }\n\n\nfunction assertEncoding(encoding) {\n if (encoding && !isBufferEncoding(encoding)) {\n throw new Error('Unknown encoding: ' + encoding);\n }\n}\n\n// StringDecoder provides an interface for efficiently splitting a series of\n// buffers into a series of JS strings without breaking apart multi-byte\n// characters. CESU-8 is handled as part of the UTF-8 encoding.\n//\n// @TODO Handling all encodings inside a single object makes it very difficult\n// to reason about this code, so it should be split up in the future.\n// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code\n// points as used by CESU-8.\nexport function StringDecoder(encoding) {\n this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');\n assertEncoding(encoding);\n switch (this.encoding) {\n case 'utf8':\n // CESU-8 represents each of Surrogate Pair by 3-bytes\n this.surrogateSize = 3;\n break;\n case 'ucs2':\n case 'utf16le':\n // UTF-16 represents each of Surrogate Pair by 2-bytes\n this.surrogateSize = 2;\n this.detectIncompleteChar = utf16DetectIncompleteChar;\n break;\n case 'base64':\n // Base-64 stores 3 bytes in 4 chars, and pads the remainder.\n this.surrogateSize = 3;\n this.detectIncompleteChar = base64DetectIncompleteChar;\n break;\n default:\n this.write = passThroughWrite;\n return;\n }\n\n // Enough space to store all bytes of a single character. UTF-8 needs 4\n // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).\n this.charBuffer = new Buffer(6);\n // Number of bytes received for the current incomplete multi-byte character.\n this.charReceived = 0;\n // Number of bytes expected for the current incomplete multi-byte character.\n this.charLength = 0;\n};\n\n\n// write decodes the given buffer and returns it as JS string that is\n// guaranteed to not contain any partial multi-byte characters. Any partial\n// character found at the end of the buffer is buffered up, and will be\n// returned when calling write again with the remaining bytes.\n//\n// Note: Converting a Buffer containing an orphan surrogate to a String\n// currently works, but converting a String to a Buffer (via `new Buffer`, or\n// Buffer#write) will replace incomplete surrogates with the unicode\n// replacement character. See https://codereview.chromium.org/121173009/ .\nStringDecoder.prototype.write = function(buffer) {\n var charStr = '';\n // if our last write ended with an incomplete multibyte character\n while (this.charLength) {\n // determine how many remaining bytes this buffer has to offer for this char\n var available = (buffer.length >= this.charLength - this.charReceived) ?\n this.charLength - this.charReceived :\n buffer.length;\n\n // add the new bytes to the char buffer\n buffer.copy(this.charBuffer, this.charReceived, 0, available);\n this.charReceived += available;\n\n if (this.charReceived < this.charLength) {\n // still not enough chars in this buffer? wait for more ...\n return '';\n }\n\n // remove bytes belonging to the current character from the buffer\n buffer = buffer.slice(available, buffer.length);\n\n // get the character that was split\n charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);\n\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n var charCode = charStr.charCodeAt(charStr.length - 1);\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n this.charLength += this.surrogateSize;\n charStr = '';\n continue;\n }\n this.charReceived = this.charLength = 0;\n\n // if there are no more bytes in this buffer, just emit our char\n if (buffer.length === 0) {\n return charStr;\n }\n break;\n }\n\n // determine and set charLength / charReceived\n this.detectIncompleteChar(buffer);\n\n var end = buffer.length;\n if (this.charLength) {\n // buffer the incomplete character bytes we got\n buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);\n end -= this.charReceived;\n }\n\n charStr += buffer.toString(this.encoding, 0, end);\n\n var end = charStr.length - 1;\n var charCode = charStr.charCodeAt(end);\n // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character\n if (charCode >= 0xD800 && charCode <= 0xDBFF) {\n var size = this.surrogateSize;\n this.charLength += size;\n this.charReceived += size;\n this.charBuffer.copy(this.charBuffer, size, 0, size);\n buffer.copy(this.charBuffer, 0, 0, size);\n return charStr.substring(0, end);\n }\n\n // or just emit the charStr\n return charStr;\n};\n\n// detectIncompleteChar determines if there is an incomplete UTF-8 character at\n// the end of the given buffer. If so, it sets this.charLength to the byte\n// length that character, and sets this.charReceived to the number of bytes\n// that are available for this character.\nStringDecoder.prototype.detectIncompleteChar = function(buffer) {\n // determine how many bytes we have to check at the end of this buffer\n var i = (buffer.length >= 3) ? 3 : buffer.length;\n\n // Figure out if one of the last i bytes of our buffer announces an\n // incomplete char.\n for (; i > 0; i--) {\n var c = buffer[buffer.length - i];\n\n // See http://en.wikipedia.org/wiki/UTF-8#Description\n\n // 110XXXXX\n if (i == 1 && c >> 5 == 0x06) {\n this.charLength = 2;\n break;\n }\n\n // 1110XXXX\n if (i <= 2 && c >> 4 == 0x0E) {\n this.charLength = 3;\n break;\n }\n\n // 11110XXX\n if (i <= 3 && c >> 3 == 0x1E) {\n this.charLength = 4;\n break;\n }\n }\n this.charReceived = i;\n};\n\nStringDecoder.prototype.end = function(buffer) {\n var res = '';\n if (buffer && buffer.length)\n res = this.write(buffer);\n\n if (this.charReceived) {\n var cr = this.charReceived;\n var buf = this.charBuffer;\n var enc = this.encoding;\n res += buf.slice(0, cr).toString(enc);\n }\n\n return res;\n};\n\nfunction passThroughWrite(buffer) {\n return buffer.toString(this.encoding);\n}\n\nfunction utf16DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 2;\n this.charLength = this.charReceived ? 2 : 0;\n}\n\nfunction base64DetectIncompleteChar(buffer) {\n this.charReceived = buffer.length % 3;\n this.charLength = this.charReceived ? 3 : 0;\n}\n","'use strict';\n\n\nReadable.ReadableState = ReadableState;\nimport EventEmitter from 'events';\nimport {inherits, debuglog} from 'util';\nimport BufferList from './buffer-list';\nimport {StringDecoder} from 'string_decoder';\nimport {Duplex} from './duplex';\nimport {nextTick} from 'process';\n\nvar debug = debuglog('stream');\ninherits(Readable, EventEmitter);\n\nfunction prependListener(emitter, event, fn) {\n // Sadly this is not cacheable as some libraries bundle their own\n // event emitter implementation with them.\n if (typeof emitter.prependListener === 'function') {\n return emitter.prependListener(event, fn);\n } else {\n // This is a hack to make sure that our error handler is attached before any\n // userland ones. NEVER DO THIS. This is here only because this code needs\n // to continue to work with older versions of Node.js that do not include\n // the prependListener() method. The goal is to eventually remove this hack.\n if (!emitter._events || !emitter._events[event])\n emitter.on(event, fn);\n else if (Array.isArray(emitter._events[event]))\n emitter._events[event].unshift(fn);\n else\n emitter._events[event] = [fn, emitter._events[event]];\n }\n}\nfunction listenerCount (emitter, type) {\n return emitter.listeners(type).length;\n}\nfunction ReadableState(options, stream) {\n\n options = options || {};\n\n // object stream flag. Used to make read(n) ignore n and to\n // make all the buffer merging and length checks go away\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;\n\n // the point at which it stops calling _read() to fill the buffer\n // Note: 0 is a valid value, means \"don't call _read preemptively ever\"\n var hwm = options.highWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;\n\n // cast to ints.\n this.highWaterMark = ~ ~this.highWaterMark;\n\n // A linked list is used to store data chunks instead of an array because the\n // linked list can remove elements from the beginning faster than\n // array.shift()\n this.buffer = new BufferList();\n this.length = 0;\n this.pipes = null;\n this.pipesCount = 0;\n this.flowing = null;\n this.ended = false;\n this.endEmitted = false;\n this.reading = false;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // whenever we return null, then we set a flag to say\n // that we're awaiting a 'readable' event emission.\n this.needReadable = false;\n this.emittedReadable = false;\n this.readableListening = false;\n this.resumeScheduled = false;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // when piping, we only care about 'readable' events that happen\n // after read()ing all the bytes and not getting any pushback.\n this.ranOut = false;\n\n // the number of writers that are awaiting a drain event in .pipe()s\n this.awaitDrain = 0;\n\n // if true, a maybeReadMore has been scheduled\n this.readingMore = false;\n\n this.decoder = null;\n this.encoding = null;\n if (options.encoding) {\n this.decoder = new StringDecoder(options.encoding);\n this.encoding = options.encoding;\n }\n}\nexport default Readable;\nexport function Readable(options) {\n\n if (!(this instanceof Readable)) return new Readable(options);\n\n this._readableState = new ReadableState(options, this);\n\n // legacy\n this.readable = true;\n\n if (options && typeof options.read === 'function') this._read = options.read;\n\n EventEmitter.call(this);\n}\n\n// Manually shove something into the read() buffer.\n// This returns true if the highWaterMark has not been hit yet,\n// similar to how Writable.write() returns true if you should\n// write() some more.\nReadable.prototype.push = function (chunk, encoding) {\n var state = this._readableState;\n\n if (!state.objectMode && typeof chunk === 'string') {\n encoding = encoding || state.defaultEncoding;\n if (encoding !== state.encoding) {\n chunk = Buffer.from(chunk, encoding);\n encoding = '';\n }\n }\n\n return readableAddChunk(this, state, chunk, encoding, false);\n};\n\n// Unshift should *always* be something directly out of read()\nReadable.prototype.unshift = function (chunk) {\n var state = this._readableState;\n return readableAddChunk(this, state, chunk, '', true);\n};\n\nReadable.prototype.isPaused = function () {\n return this._readableState.flowing === false;\n};\n\nfunction readableAddChunk(stream, state, chunk, encoding, addToFront) {\n var er = chunkInvalid(state, chunk);\n if (er) {\n stream.emit('error', er);\n } else if (chunk === null) {\n state.reading = false;\n onEofChunk(stream, state);\n } else if (state.objectMode || chunk && chunk.length > 0) {\n if (state.ended && !addToFront) {\n var e = new Error('stream.push() after EOF');\n stream.emit('error', e);\n } else if (state.endEmitted && addToFront) {\n var _e = new Error('stream.unshift() after end event');\n stream.emit('error', _e);\n } else {\n var skipAdd;\n if (state.decoder && !addToFront && !encoding) {\n chunk = state.decoder.write(chunk);\n skipAdd = !state.objectMode && chunk.length === 0;\n }\n\n if (!addToFront) state.reading = false;\n\n // Don't add to the buffer if we've decoded to an empty string chunk and\n // we're not in object mode\n if (!skipAdd) {\n // if we want the data now, just emit it.\n if (state.flowing && state.length === 0 && !state.sync) {\n stream.emit('data', chunk);\n stream.read(0);\n } else {\n // update the buffer info.\n state.length += state.objectMode ? 1 : chunk.length;\n if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);\n\n if (state.needReadable) emitReadable(stream);\n }\n }\n\n maybeReadMore(stream, state);\n }\n } else if (!addToFront) {\n state.reading = false;\n }\n\n return needMoreData(state);\n}\n\n// if it's past the high water mark, we can push in some more.\n// Also, if we have no data yet, we can stand some\n// more bytes. This is to work around cases where hwm=0,\n// such as the repl. Also, if the push() triggered a\n// readable event, and the user called read(largeNumber) such that\n// needReadable was set, then we ought to push more, so that another\n// 'readable' event will be triggered.\nfunction needMoreData(state) {\n return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);\n}\n\n// backwards compatibility.\nReadable.prototype.setEncoding = function (enc) {\n this._readableState.decoder = new StringDecoder(enc);\n this._readableState.encoding = enc;\n return this;\n};\n\n// Don't raise the hwm > 8MB\nvar MAX_HWM = 0x800000;\nfunction computeNewHighWaterMark(n) {\n if (n >= MAX_HWM) {\n n = MAX_HWM;\n } else {\n // Get the next highest power of 2 to prevent increasing hwm excessively in\n // tiny amounts\n n--;\n n |= n >>> 1;\n n |= n >>> 2;\n n |= n >>> 4;\n n |= n >>> 8;\n n |= n >>> 16;\n n++;\n }\n return n;\n}\n\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction howMuchToRead(n, state) {\n if (n <= 0 || state.length === 0 && state.ended) return 0;\n if (state.objectMode) return 1;\n if (n !== n) {\n // Only flow one buffer at a time\n if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;\n }\n // If we're asking for more than the current hwm, then raise the hwm.\n if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);\n if (n <= state.length) return n;\n // Don't have enough\n if (!state.ended) {\n state.needReadable = true;\n return 0;\n }\n return state.length;\n}\n\n// you can override either this method, or the async _read(n) below.\nReadable.prototype.read = function (n) {\n debug('read', n);\n n = parseInt(n, 10);\n var state = this._readableState;\n var nOrig = n;\n\n if (n !== 0) state.emittedReadable = false;\n\n // if we're doing read(0) to trigger a readable event, but we\n // already have a bunch of data in the buffer, then just trigger\n // the 'readable' event and move on.\n if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {\n debug('read: emitReadable', state.length, state.ended);\n if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);\n return null;\n }\n\n n = howMuchToRead(n, state);\n\n // if we've ended, and we're now clear, then finish it up.\n if (n === 0 && state.ended) {\n if (state.length === 0) endReadable(this);\n return null;\n }\n\n // All the actual chunk generation logic needs to be\n // *below* the call to _read. The reason is that in certain\n // synthetic stream cases, such as passthrough streams, _read\n // may be a completely synchronous operation which may change\n // the state of the read buffer, providing enough data when\n // before there was *not* enough.\n //\n // So, the steps are:\n // 1. Figure out what the state of things will be after we do\n // a read from the buffer.\n //\n // 2. If that resulting state will trigger a _read, then call _read.\n // Note that this may be asynchronous, or synchronous. Yes, it is\n // deeply ugly to write APIs this way, but that still doesn't mean\n // that the Readable class should behave improperly, as streams are\n // designed to be sync/async agnostic.\n // Take note if the _read call is sync or async (ie, if the read call\n // has returned yet), so that we know whether or not it's safe to emit\n // 'readable' etc.\n //\n // 3. Actually pull the requested chunks out of the buffer and return.\n\n // if we need a readable event, then we need to do some reading.\n var doRead = state.needReadable;\n debug('need readable', doRead);\n\n // if we currently have less than the highWaterMark, then also read some\n if (state.length === 0 || state.length - n < state.highWaterMark) {\n doRead = true;\n debug('length less than watermark', doRead);\n }\n\n // however, if we've ended, then there's no point, and if we're already\n // reading, then it's unnecessary.\n if (state.ended || state.reading) {\n doRead = false;\n debug('reading or ended', doRead);\n } else if (doRead) {\n debug('do read');\n state.reading = true;\n state.sync = true;\n // if the length is currently zero, then we *need* a readable event.\n if (state.length === 0) state.needReadable = true;\n // call internal read method\n this._read(state.highWaterMark);\n state.sync = false;\n // If _read pushed data synchronously, then `reading` will be false,\n // and we need to re-evaluate how much data we can return to the user.\n if (!state.reading) n = howMuchToRead(nOrig, state);\n }\n\n var ret;\n if (n > 0) ret = fromList(n, state);else ret = null;\n\n if (ret === null) {\n state.needReadable = true;\n n = 0;\n } else {\n state.length -= n;\n }\n\n if (state.length === 0) {\n // If we have nothing in the buffer, then we want to know\n // as soon as we *do* get something into the buffer.\n if (!state.ended) state.needReadable = true;\n\n // If we tried to read() past the EOF, then emit end on the next tick.\n if (nOrig !== n && state.ended) endReadable(this);\n }\n\n if (ret !== null) this.emit('data', ret);\n\n return ret;\n};\n\nfunction chunkInvalid(state, chunk) {\n var er = null;\n if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n return er;\n}\n\nfunction onEofChunk(stream, state) {\n if (state.ended) return;\n if (state.decoder) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) {\n state.buffer.push(chunk);\n state.length += state.objectMode ? 1 : chunk.length;\n }\n }\n state.ended = true;\n\n // emit 'readable' now to make sure it gets picked up.\n emitReadable(stream);\n}\n\n// Don't emit readable right away in sync mode, because this can trigger\n// another read() call => stack overflow. This way, it might trigger\n// a nextTick recursion warning, but that's not so bad.\nfunction emitReadable(stream) {\n var state = stream._readableState;\n state.needReadable = false;\n if (!state.emittedReadable) {\n debug('emitReadable', state.flowing);\n state.emittedReadable = true;\n if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream);\n }\n}\n\nfunction emitReadable_(stream) {\n debug('emit readable');\n stream.emit('readable');\n flow(stream);\n}\n\n// at this point, the user has presumably seen the 'readable' event,\n// and called read() to consume some data. that may have triggered\n// in turn another _read(n) call, in which case reading = true if\n// it's in progress.\n// However, if we're not ended, or reading, and the length < hwm,\n// then go ahead and try to read some more preemptively.\nfunction maybeReadMore(stream, state) {\n if (!state.readingMore) {\n state.readingMore = true;\n nextTick(maybeReadMore_, stream, state);\n }\n}\n\nfunction maybeReadMore_(stream, state) {\n var len = state.length;\n while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {\n debug('maybeReadMore read 0');\n stream.read(0);\n if (len === state.length)\n // didn't get any data, stop spinning.\n break;else len = state.length;\n }\n state.readingMore = false;\n}\n\n// abstract method. to be overridden in specific implementation classes.\n// call cb(er, data) where data is <= n in length.\n// for virtual (non-string, non-buffer) streams, \"length\" is somewhat\n// arbitrary, and perhaps not very meaningful.\nReadable.prototype._read = function (n) {\n this.emit('error', new Error('not implemented'));\n};\n\nReadable.prototype.pipe = function (dest, pipeOpts) {\n var src = this;\n var state = this._readableState;\n\n switch (state.pipesCount) {\n case 0:\n state.pipes = dest;\n break;\n case 1:\n state.pipes = [state.pipes, dest];\n break;\n default:\n state.pipes.push(dest);\n break;\n }\n state.pipesCount += 1;\n debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);\n\n var doEnd = (!pipeOpts || pipeOpts.end !== false);\n\n var endFn = doEnd ? onend : cleanup;\n if (state.endEmitted) nextTick(endFn);else src.once('end', endFn);\n\n dest.on('unpipe', onunpipe);\n function onunpipe(readable) {\n debug('onunpipe');\n if (readable === src) {\n cleanup();\n }\n }\n\n function onend() {\n debug('onend');\n dest.end();\n }\n\n // when the dest drains, it reduces the awaitDrain counter\n // on the source. This would be more elegant with a .once()\n // handler in flow(), but adding and removing repeatedly is\n // too slow.\n var ondrain = pipeOnDrain(src);\n dest.on('drain', ondrain);\n\n var cleanedUp = false;\n function cleanup() {\n debug('cleanup');\n // cleanup event handlers once the pipe is broken\n dest.removeListener('close', onclose);\n dest.removeListener('finish', onfinish);\n dest.removeListener('drain', ondrain);\n dest.removeListener('error', onerror);\n dest.removeListener('unpipe', onunpipe);\n src.removeListener('end', onend);\n src.removeListener('end', cleanup);\n src.removeListener('data', ondata);\n\n cleanedUp = true;\n\n // if the reader is waiting for a drain event from this\n // specific writer, then it would cause it to never start\n // flowing again.\n // So, if this is awaiting a drain, then we just call it now.\n // If we don't know, then assume that we are waiting for one.\n if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();\n }\n\n // If the user pushes more data while we're writing to dest then we'll end up\n // in ondata again. However, we only want to increase awaitDrain once because\n // dest will only emit one 'drain' event for the multiple writes.\n // => Introduce a guard on increasing awaitDrain.\n var increasedAwaitDrain = false;\n src.on('data', ondata);\n function ondata(chunk) {\n debug('ondata');\n increasedAwaitDrain = false;\n var ret = dest.write(chunk);\n if (false === ret && !increasedAwaitDrain) {\n // If the user unpiped during `dest.write()`, it is possible\n // to get stuck in a permanently paused state if that write\n // also returned false.\n // => Check whether `dest` is still a piping destination.\n if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {\n debug('false write response, pause', src._readableState.awaitDrain);\n src._readableState.awaitDrain++;\n increasedAwaitDrain = true;\n }\n src.pause();\n }\n }\n\n // if the dest has an error, then stop piping into it.\n // however, don't suppress the throwing behavior for this.\n function onerror(er) {\n debug('onerror', er);\n unpipe();\n dest.removeListener('error', onerror);\n if (listenerCount(dest, 'error') === 0) dest.emit('error', er);\n }\n\n // Make sure our error handler is attached before userland ones.\n prependListener(dest, 'error', onerror);\n\n // Both close and finish should trigger unpipe, but only once.\n function onclose() {\n dest.removeListener('finish', onfinish);\n unpipe();\n }\n dest.once('close', onclose);\n function onfinish() {\n debug('onfinish');\n dest.removeListener('close', onclose);\n unpipe();\n }\n dest.once('finish', onfinish);\n\n function unpipe() {\n debug('unpipe');\n src.unpipe(dest);\n }\n\n // tell the dest that it's being piped to\n dest.emit('pipe', src);\n\n // start the flow if it hasn't been started already.\n if (!state.flowing) {\n debug('pipe resume');\n src.resume();\n }\n\n return dest;\n};\n\nfunction pipeOnDrain(src) {\n return function () {\n var state = src._readableState;\n debug('pipeOnDrain', state.awaitDrain);\n if (state.awaitDrain) state.awaitDrain--;\n if (state.awaitDrain === 0 && src.listeners('data').length) {\n state.flowing = true;\n flow(src);\n }\n };\n}\n\nReadable.prototype.unpipe = function (dest) {\n var state = this._readableState;\n\n // if we're not piping anywhere, then do nothing.\n if (state.pipesCount === 0) return this;\n\n // just one destination. most common case.\n if (state.pipesCount === 1) {\n // passed in one, but it's not the right one.\n if (dest && dest !== state.pipes) return this;\n\n if (!dest) dest = state.pipes;\n\n // got a match.\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n if (dest) dest.emit('unpipe', this);\n return this;\n }\n\n // slow case. multiple pipe destinations.\n\n if (!dest) {\n // remove all.\n var dests = state.pipes;\n var len = state.pipesCount;\n state.pipes = null;\n state.pipesCount = 0;\n state.flowing = false;\n\n for (var _i = 0; _i < len; _i++) {\n dests[_i].emit('unpipe', this);\n }return this;\n }\n\n // try to find the right one.\n var i = indexOf(state.pipes, dest);\n if (i === -1) return this;\n\n state.pipes.splice(i, 1);\n state.pipesCount -= 1;\n if (state.pipesCount === 1) state.pipes = state.pipes[0];\n\n dest.emit('unpipe', this);\n\n return this;\n};\n\n// set up data events if they are asked for\n// Ensure readable listeners eventually get something\nReadable.prototype.on = function (ev, fn) {\n var res = EventEmitter.prototype.on.call(this, ev, fn);\n\n if (ev === 'data') {\n // Start flowing on next tick if stream isn't explicitly paused\n if (this._readableState.flowing !== false) this.resume();\n } else if (ev === 'readable') {\n var state = this._readableState;\n if (!state.endEmitted && !state.readableListening) {\n state.readableListening = state.needReadable = true;\n state.emittedReadable = false;\n if (!state.reading) {\n nextTick(nReadingNextTick, this);\n } else if (state.length) {\n emitReadable(this, state);\n }\n }\n }\n\n return res;\n};\nReadable.prototype.addListener = Readable.prototype.on;\n\nfunction nReadingNextTick(self) {\n debug('readable nexttick read 0');\n self.read(0);\n}\n\n// pause() and resume() are remnants of the legacy readable stream API\n// If the user uses them, then switch into old mode.\nReadable.prototype.resume = function () {\n var state = this._readableState;\n if (!state.flowing) {\n debug('resume');\n state.flowing = true;\n resume(this, state);\n }\n return this;\n};\n\nfunction resume(stream, state) {\n if (!state.resumeScheduled) {\n state.resumeScheduled = true;\n nextTick(resume_, stream, state);\n }\n}\n\nfunction resume_(stream, state) {\n if (!state.reading) {\n debug('resume read 0');\n stream.read(0);\n }\n\n state.resumeScheduled = false;\n state.awaitDrain = 0;\n stream.emit('resume');\n flow(stream);\n if (state.flowing && !state.reading) stream.read(0);\n}\n\nReadable.prototype.pause = function () {\n debug('call pause flowing=%j', this._readableState.flowing);\n if (false !== this._readableState.flowing) {\n debug('pause');\n this._readableState.flowing = false;\n this.emit('pause');\n }\n return this;\n};\n\nfunction flow(stream) {\n var state = stream._readableState;\n debug('flow', state.flowing);\n while (state.flowing && stream.read() !== null) {}\n}\n\n// wrap an old-style stream as the async data source.\n// This is *not* part of the readable stream interface.\n// It is an ugly unfortunate mess of history.\nReadable.prototype.wrap = function (stream) {\n var state = this._readableState;\n var paused = false;\n\n var self = this;\n stream.on('end', function () {\n debug('wrapped end');\n if (state.decoder && !state.ended) {\n var chunk = state.decoder.end();\n if (chunk && chunk.length) self.push(chunk);\n }\n\n self.push(null);\n });\n\n stream.on('data', function (chunk) {\n debug('wrapped data');\n if (state.decoder) chunk = state.decoder.write(chunk);\n\n // don't skip over falsy values in objectMode\n if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;\n\n var ret = self.push(chunk);\n if (!ret) {\n paused = true;\n stream.pause();\n }\n });\n\n // proxy all the other methods.\n // important when wrapping filters and duplexes.\n for (var i in stream) {\n if (this[i] === undefined && typeof stream[i] === 'function') {\n this[i] = function (method) {\n return function () {\n return stream[method].apply(stream, arguments);\n };\n }(i);\n }\n }\n\n // proxy certain important events.\n var events = ['error', 'close', 'destroy', 'pause', 'resume'];\n forEach(events, function (ev) {\n stream.on(ev, self.emit.bind(self, ev));\n });\n\n // when we try to consume some more bytes, simply unpause the\n // underlying stream.\n self._read = function (n) {\n debug('wrapped _read', n);\n if (paused) {\n paused = false;\n stream.resume();\n }\n };\n\n return self;\n};\n\n// exposed for testing purposes only.\nReadable._fromList = fromList;\n\n// Pluck off n bytes from an array of buffers.\n// Length is the combined lengths of all the buffers in the list.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromList(n, state) {\n // nothing buffered\n if (state.length === 0) return null;\n\n var ret;\n if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {\n // read it all, truncate the list\n if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);\n state.buffer.clear();\n } else {\n // read part of list\n ret = fromListPartial(n, state.buffer, state.decoder);\n }\n\n return ret;\n}\n\n// Extracts only enough buffered data to satisfy the amount requested.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction fromListPartial(n, list, hasStrings) {\n var ret;\n if (n < list.head.data.length) {\n // slice is the same for buffers and strings\n ret = list.head.data.slice(0, n);\n list.head.data = list.head.data.slice(n);\n } else if (n === list.head.data.length) {\n // first chunk is a perfect match\n ret = list.shift();\n } else {\n // result spans more than one buffer\n ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);\n }\n return ret;\n}\n\n// Copies a specified amount of characters from the list of buffered data\n// chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBufferString(n, list) {\n var p = list.head;\n var c = 1;\n var ret = p.data;\n n -= ret.length;\n while (p = p.next) {\n var str = p.data;\n var nb = n > str.length ? str.length : n;\n if (nb === str.length) ret += str;else ret += str.slice(0, n);\n n -= nb;\n if (n === 0) {\n if (nb === str.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = str.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\n// Copies a specified amount of bytes from the list of buffered data chunks.\n// This function is designed to be inlinable, so please take care when making\n// changes to the function body.\nfunction copyFromBuffer(n, list) {\n var ret = Buffer.allocUnsafe(n);\n var p = list.head;\n var c = 1;\n p.data.copy(ret);\n n -= p.data.length;\n while (p = p.next) {\n var buf = p.data;\n var nb = n > buf.length ? buf.length : n;\n buf.copy(ret, ret.length - n, 0, nb);\n n -= nb;\n if (n === 0) {\n if (nb === buf.length) {\n ++c;\n if (p.next) list.head = p.next;else list.head = list.tail = null;\n } else {\n list.head = p;\n p.data = buf.slice(nb);\n }\n break;\n }\n ++c;\n }\n list.length -= c;\n return ret;\n}\n\nfunction endReadable(stream) {\n var state = stream._readableState;\n\n // If we get here before consuming all the bytes, then that is a\n // bug in node. Should never happen.\n if (state.length > 0) throw new Error('\"endReadable()\" called on non-empty stream');\n\n if (!state.endEmitted) {\n state.ended = true;\n nextTick(endReadableNT, state, stream);\n }\n}\n\nfunction endReadableNT(state, stream) {\n // Check that we didn't get one last unshift.\n if (!state.endEmitted && state.length === 0) {\n state.endEmitted = true;\n stream.readable = false;\n stream.emit('end');\n }\n}\n\nfunction forEach(xs, f) {\n for (var i = 0, l = xs.length; i < l; i++) {\n f(xs[i], i);\n }\n}\n\nfunction indexOf(xs, x) {\n for (var i = 0, l = xs.length; i < l; i++) {\n if (xs[i] === x) return i;\n }\n return -1;\n}\n","// A bit simpler than readable streams.\n// Implement an async ._write(chunk, encoding, cb), and it'll handle all\n// the drain event emission and buffering.\n\n\nimport {inherits, deprecate} from 'util';\nimport {Buffer} from 'buffer';\nWritable.WritableState = WritableState;\nimport {EventEmitter} from 'events';\nimport {Duplex} from './duplex';\nimport {nextTick} from 'process';\ninherits(Writable, EventEmitter);\n\nfunction nop() {}\n\nfunction WriteReq(chunk, encoding, cb) {\n this.chunk = chunk;\n this.encoding = encoding;\n this.callback = cb;\n this.next = null;\n}\n\nfunction WritableState(options, stream) {\n Object.defineProperty(this, 'buffer', {\n get: deprecate(function () {\n return this.getBuffer();\n }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')\n });\n options = options || {};\n\n // object stream flag to indicate whether or not this stream\n // contains buffers or objects.\n this.objectMode = !!options.objectMode;\n\n if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;\n\n // the point at which write() starts returning false\n // Note: 0 is a valid value, means that we always return false if\n // the entire buffer is not flushed immediately on write()\n var hwm = options.highWaterMark;\n var defaultHwm = this.objectMode ? 16 : 16 * 1024;\n this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;\n\n // cast to ints.\n this.highWaterMark = ~ ~this.highWaterMark;\n\n this.needDrain = false;\n // at the start of calling end()\n this.ending = false;\n // when end() has been called, and returned\n this.ended = false;\n // when 'finish' is emitted\n this.finished = false;\n\n // should we decode strings into buffers before passing to _write?\n // this is here so that some node-core streams can optimize string\n // handling at a lower level.\n var noDecode = options.decodeStrings === false;\n this.decodeStrings = !noDecode;\n\n // Crypto is kind of old and crusty. Historically, its default string\n // encoding is 'binary' so we have to make this configurable.\n // Everything else in the universe uses 'utf8', though.\n this.defaultEncoding = options.defaultEncoding || 'utf8';\n\n // not an actual buffer we keep track of, but a measurement\n // of how much we're waiting to get pushed to some underlying\n // socket or file.\n this.length = 0;\n\n // a flag to see when we're in the middle of a write.\n this.writing = false;\n\n // when true all writes will be buffered until .uncork() call\n this.corked = 0;\n\n // a flag to be able to tell if the onwrite cb is called immediately,\n // or on a later tick. We set this to true at first, because any\n // actions that shouldn't happen until \"later\" should generally also\n // not happen before the first write call.\n this.sync = true;\n\n // a flag to know if we're processing previously buffered items, which\n // may call the _write() callback in the same tick, so that we don't\n // end up in an overlapped onwrite situation.\n this.bufferProcessing = false;\n\n // the callback that's passed to _write(chunk,cb)\n this.onwrite = function (er) {\n onwrite(stream, er);\n };\n\n // the callback that the user supplies to write(chunk,encoding,cb)\n this.writecb = null;\n\n // the amount that is being written when _write is called.\n this.writelen = 0;\n\n this.bufferedRequest = null;\n this.lastBufferedRequest = null;\n\n // number of pending user-supplied write callbacks\n // this must be 0 before 'finish' can be emitted\n this.pendingcb = 0;\n\n // emit prefinish if the only thing we're waiting for is _write cbs\n // This is relevant for synchronous Transform streams\n this.prefinished = false;\n\n // True if the error was already emitted and should not be thrown again\n this.errorEmitted = false;\n\n // count buffered requests\n this.bufferedRequestCount = 0;\n\n // allocate the first CorkedRequest, there is always\n // one allocated and free to use, and we maintain at most two\n this.corkedRequestsFree = new CorkedRequest(this);\n}\n\nWritableState.prototype.getBuffer = function writableStateGetBuffer() {\n var current = this.bufferedRequest;\n var out = [];\n while (current) {\n out.push(current);\n current = current.next;\n }\n return out;\n};\n\nexport default Writable;\nexport function Writable(options) {\n\n // Writable ctor is applied to Duplexes, though they're not\n // instanceof Writable, they're instanceof Readable.\n if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);\n\n this._writableState = new WritableState(options, this);\n\n // legacy.\n this.writable = true;\n\n if (options) {\n if (typeof options.write === 'function') this._write = options.write;\n\n if (typeof options.writev === 'function') this._writev = options.writev;\n }\n\n EventEmitter.call(this);\n}\n\n// Otherwise people can pipe Writable streams, which is just wrong.\nWritable.prototype.pipe = function () {\n this.emit('error', new Error('Cannot pipe, not readable'));\n};\n\nfunction writeAfterEnd(stream, cb) {\n var er = new Error('write after end');\n // TODO: defer error events consistently everywhere, not just the cb\n stream.emit('error', er);\n nextTick(cb, er);\n}\n\n// If we get something that is not a buffer, string, null, or undefined,\n// and we're not in objectMode, then that's an error.\n// Otherwise stream chunks are all considered to be of length=1, and the\n// watermarks determine how many objects to keep in the buffer, rather than\n// how many bytes or characters.\nfunction validChunk(stream, state, chunk, cb) {\n var valid = true;\n var er = false;\n // Always throw error if a null is written\n // if we are not in object mode then throw\n // if it is not a buffer, string, or undefined.\n if (chunk === null) {\n er = new TypeError('May not write null values to stream');\n } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {\n er = new TypeError('Invalid non-string/buffer chunk');\n }\n if (er) {\n stream.emit('error', er);\n nextTick(cb, er);\n valid = false;\n }\n return valid;\n}\n\nWritable.prototype.write = function (chunk, encoding, cb) {\n var state = this._writableState;\n var ret = false;\n\n if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;\n\n if (typeof cb !== 'function') cb = nop;\n\n if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {\n state.pendingcb++;\n ret = writeOrBuffer(this, state, chunk, encoding, cb);\n }\n\n return ret;\n};\n\nWritable.prototype.cork = function () {\n var state = this._writableState;\n\n state.corked++;\n};\n\nWritable.prototype.uncork = function () {\n var state = this._writableState;\n\n if (state.corked) {\n state.corked--;\n\n if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);\n }\n};\n\nWritable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {\n // node::ParseEncoding() requires lower case.\n if (typeof encoding === 'string') encoding = encoding.toLowerCase();\n if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);\n this._writableState.defaultEncoding = encoding;\n return this;\n};\n\nfunction decodeChunk(state, chunk, encoding) {\n if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {\n chunk = Buffer.from(chunk, encoding);\n }\n return chunk;\n}\n\n// if we're already writing something, then just put this\n// in the queue, and wait our turn. Otherwise, call _write\n// If we return false, then we need a drain event, so set that flag.\nfunction writeOrBuffer(stream, state, chunk, encoding, cb) {\n chunk = decodeChunk(state, chunk, encoding);\n\n if (Buffer.isBuffer(chunk)) encoding = 'buffer';\n var len = state.objectMode ? 1 : chunk.length;\n\n state.length += len;\n\n var ret = state.length < state.highWaterMark;\n // we must ensure that previous needDrain will not be reset to false.\n if (!ret) state.needDrain = true;\n\n if (state.writing || state.corked) {\n var last = state.lastBufferedRequest;\n state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);\n if (last) {\n last.next = state.lastBufferedRequest;\n } else {\n state.bufferedRequest = state.lastBufferedRequest;\n }\n state.bufferedRequestCount += 1;\n } else {\n doWrite(stream, state, false, len, chunk, encoding, cb);\n }\n\n return ret;\n}\n\nfunction doWrite(stream, state, writev, len, chunk, encoding, cb) {\n state.writelen = len;\n state.writecb = cb;\n state.writing = true;\n state.sync = true;\n if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);\n state.sync = false;\n}\n\nfunction onwriteError(stream, state, sync, er, cb) {\n --state.pendingcb;\n if (sync) nextTick(cb, er);else cb(er);\n\n stream._writableState.errorEmitted = true;\n stream.emit('error', er);\n}\n\nfunction onwriteStateUpdate(state) {\n state.writing = false;\n state.writecb = null;\n state.length -= state.writelen;\n state.writelen = 0;\n}\n\nfunction onwrite(stream, er) {\n var state = stream._writableState;\n var sync = state.sync;\n var cb = state.writecb;\n\n onwriteStateUpdate(state);\n\n if (er) onwriteError(stream, state, sync, er, cb);else {\n // Check if we're actually ready to finish, but don't emit yet\n var finished = needFinish(state);\n\n if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {\n clearBuffer(stream, state);\n }\n\n if (sync) {\n /**/\n nextTick(afterWrite, stream, state, finished, cb);\n /**/\n } else {\n afterWrite(stream, state, finished, cb);\n }\n }\n}\n\nfunction afterWrite(stream, state, finished, cb) {\n if (!finished) onwriteDrain(stream, state);\n state.pendingcb--;\n cb();\n finishMaybe(stream, state);\n}\n\n// Must force callback to be called on nextTick, so that we don't\n// emit 'drain' before the write() consumer gets the 'false' return\n// value, and has a chance to attach a 'drain' listener.\nfunction onwriteDrain(stream, state) {\n if (state.length === 0 && state.needDrain) {\n state.needDrain = false;\n stream.emit('drain');\n }\n}\n\n// if there's something in the buffer waiting, then process it\nfunction clearBuffer(stream, state) {\n state.bufferProcessing = true;\n var entry = state.bufferedRequest;\n\n if (stream._writev && entry && entry.next) {\n // Fast case, write everything using _writev()\n var l = state.bufferedRequestCount;\n var buffer = new Array(l);\n var holder = state.corkedRequestsFree;\n holder.entry = entry;\n\n var count = 0;\n while (entry) {\n buffer[count] = entry;\n entry = entry.next;\n count += 1;\n }\n\n doWrite(stream, state, true, state.length, buffer, '', holder.finish);\n\n // doWrite is almost always async, defer these to save a bit of time\n // as the hot path ends with doWrite\n state.pendingcb++;\n state.lastBufferedRequest = null;\n if (holder.next) {\n state.corkedRequestsFree = holder.next;\n holder.next = null;\n } else {\n state.corkedRequestsFree = new CorkedRequest(state);\n }\n } else {\n // Slow case, write chunks one-by-one\n while (entry) {\n var chunk = entry.chunk;\n var encoding = entry.encoding;\n var cb = entry.callback;\n var len = state.objectMode ? 1 : chunk.length;\n\n doWrite(stream, state, false, len, chunk, encoding, cb);\n entry = entry.next;\n // if we didn't call the onwrite immediately, then\n // it means that we need to wait until it does.\n // also, that means that the chunk and cb are currently\n // being processed, so move the buffer counter past them.\n if (state.writing) {\n break;\n }\n }\n\n if (entry === null) state.lastBufferedRequest = null;\n }\n\n state.bufferedRequestCount = 0;\n state.bufferedRequest = entry;\n state.bufferProcessing = false;\n}\n\nWritable.prototype._write = function (chunk, encoding, cb) {\n cb(new Error('not implemented'));\n};\n\nWritable.prototype._writev = null;\n\nWritable.prototype.end = function (chunk, encoding, cb) {\n var state = this._writableState;\n\n if (typeof chunk === 'function') {\n cb = chunk;\n chunk = null;\n encoding = null;\n } else if (typeof encoding === 'function') {\n cb = encoding;\n encoding = null;\n }\n\n if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);\n\n // .end() fully uncorks\n if (state.corked) {\n state.corked = 1;\n this.uncork();\n }\n\n // ignore unnecessary end() calls.\n if (!state.ending && !state.finished) endWritable(this, state, cb);\n};\n\nfunction needFinish(state) {\n return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;\n}\n\nfunction prefinish(stream, state) {\n if (!state.prefinished) {\n state.prefinished = true;\n stream.emit('prefinish');\n }\n}\n\nfunction finishMaybe(stream, state) {\n var need = needFinish(state);\n if (need) {\n if (state.pendingcb === 0) {\n prefinish(stream, state);\n state.finished = true;\n stream.emit('finish');\n } else {\n prefinish(stream, state);\n }\n }\n return need;\n}\n\nfunction endWritable(stream, state, cb) {\n state.ending = true;\n finishMaybe(stream, state);\n if (cb) {\n if (state.finished) nextTick(cb);else stream.once('finish', cb);\n }\n state.ended = true;\n stream.writable = false;\n}\n\n// It seems a linked list but it is not\n// there will be only 2 of these for each stream\nfunction CorkedRequest(state) {\n var _this = this;\n\n this.next = null;\n this.entry = null;\n\n this.finish = function (err) {\n var entry = _this.entry;\n _this.entry = null;\n while (entry) {\n var cb = entry.callback;\n state.pendingcb--;\n cb(err);\n entry = entry.next;\n }\n if (state.corkedRequestsFree) {\n state.corkedRequestsFree.next = _this;\n } else {\n state.corkedRequestsFree = _this;\n }\n };\n}\n","\nimport {inherits} from 'util';\nimport {nextTick} from 'process';\nimport {Readable} from './readable';\nimport {Writable} from './writable';\n\n\ninherits(Duplex, Readable);\n\nvar keys = Object.keys(Writable.prototype);\nfor (var v = 0; v < keys.length; v++) {\n var method = keys[v];\n if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];\n}\nexport default Duplex;\nexport function Duplex(options) {\n if (!(this instanceof Duplex)) return new Duplex(options);\n\n Readable.call(this, options);\n Writable.call(this, options);\n\n if (options && options.readable === false) this.readable = false;\n\n if (options && options.writable === false) this.writable = false;\n\n this.allowHalfOpen = true;\n if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;\n\n this.once('end', onend);\n}\n\n// the no-half-open enforcer\nfunction onend() {\n // if we allow half-open state, or if the writable side ended,\n // then we're ok.\n if (this.allowHalfOpen || this._writableState.ended) return;\n\n // no more data can be written.\n // But allow more writes to happen in this tick.\n nextTick(onEndNT, this);\n}\n\nfunction onEndNT(self) {\n self.end();\n}\n","// a transform stream is a readable/writable stream where you do\n// something with the data. Sometimes it's called a \"filter\",\n// but that's not a great name for it, since that implies a thing where\n// some bits pass through, and others are simply ignored. (That would\n// be a valid example of a transform, of course.)\n//\n// While the output is causally related to the input, it's not a\n// necessarily symmetric or synchronous transformation. For example,\n// a zlib stream might take multiple plain-text writes(), and then\n// emit a single compressed chunk some time in the future.\n//\n// Here's how this works:\n//\n// The Transform stream has all the aspects of the readable and writable\n// stream classes. When you write(chunk), that calls _write(chunk,cb)\n// internally, and returns false if there's a lot of pending writes\n// buffered up. When you call read(), that calls _read(n) until\n// there's enough pending readable data buffered up.\n//\n// In a transform stream, the written data is placed in a buffer. When\n// _read(n) is called, it transforms the queued up data, calling the\n// buffered _write cb's as it consumes chunks. If consuming a single\n// written chunk would result in multiple output chunks, then the first\n// outputted bit calls the readcb, and subsequent chunks just go into\n// the read buffer, and will cause it to emit 'readable' if necessary.\n//\n// This way, back-pressure is actually determined by the reading side,\n// since _read has to be called to start processing a new chunk. However,\n// a pathological inflate type of transform can cause excessive buffering\n// here. For example, imagine a stream where every byte of input is\n// interpreted as an integer from 0-255, and then results in that many\n// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in\n// 1kb of data being output. In this case, you could write a very small\n// amount of input, and end up with a very large amount of output. In\n// such a pathological inflating mechanism, there'd be no way to tell\n// the system to stop doing the transform. A single 4MB write could\n// cause the system to run out of memory.\n//\n// However, even in such a pathological case, only a single written chunk\n// would be consumed, and then the rest would wait (un-transformed) until\n// the results of the previous transformed chunk were consumed.\n\n\nimport {Duplex} from './duplex';\n\n\nimport {inherits} from 'util';\ninherits(Transform, Duplex);\n\nfunction TransformState(stream) {\n this.afterTransform = function (er, data) {\n return afterTransform(stream, er, data);\n };\n\n this.needTransform = false;\n this.transforming = false;\n this.writecb = null;\n this.writechunk = null;\n this.writeencoding = null;\n}\n\nfunction afterTransform(stream, er, data) {\n var ts = stream._transformState;\n ts.transforming = false;\n\n var cb = ts.writecb;\n\n if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));\n\n ts.writechunk = null;\n ts.writecb = null;\n\n if (data !== null && data !== undefined) stream.push(data);\n\n cb(er);\n\n var rs = stream._readableState;\n rs.reading = false;\n if (rs.needReadable || rs.length < rs.highWaterMark) {\n stream._read(rs.highWaterMark);\n }\n}\nexport default Transform;\nexport function Transform(options) {\n if (!(this instanceof Transform)) return new Transform(options);\n\n Duplex.call(this, options);\n\n this._transformState = new TransformState(this);\n\n // when the writable side finishes, then flush out anything remaining.\n var stream = this;\n\n // start out asking for a readable event once data is transformed.\n this._readableState.needReadable = true;\n\n // we have implemented the _read method, and done the other things\n // that Readable wants before the first _read call, so unset the\n // sync guard flag.\n this._readableState.sync = false;\n\n if (options) {\n if (typeof options.transform === 'function') this._transform = options.transform;\n\n if (typeof options.flush === 'function') this._flush = options.flush;\n }\n\n this.once('prefinish', function () {\n if (typeof this._flush === 'function') this._flush(function (er) {\n done(stream, er);\n });else done(stream);\n });\n}\n\nTransform.prototype.push = function (chunk, encoding) {\n this._transformState.needTransform = false;\n return Duplex.prototype.push.call(this, chunk, encoding);\n};\n\n// This is the part where you do stuff!\n// override this function in implementation classes.\n// 'chunk' is an input chunk.\n//\n// Call `push(newChunk)` to pass along transformed output\n// to the readable side. You may call 'push' zero or more times.\n//\n// Call `cb(err)` when you are done with this chunk. If you pass\n// an error, then that'll put the hurt on the whole operation. If you\n// never call cb(), then you'll never get another chunk.\nTransform.prototype._transform = function (chunk, encoding, cb) {\n throw new Error('Not implemented');\n};\n\nTransform.prototype._write = function (chunk, encoding, cb) {\n var ts = this._transformState;\n ts.writecb = cb;\n ts.writechunk = chunk;\n ts.writeencoding = encoding;\n if (!ts.transforming) {\n var rs = this._readableState;\n if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);\n }\n};\n\n// Doesn't matter what the args are here.\n// _transform does all the work.\n// That we got here means that the readable side wants more data.\nTransform.prototype._read = function (n) {\n var ts = this._transformState;\n\n if (ts.writechunk !== null && ts.writecb && !ts.transforming) {\n ts.transforming = true;\n this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);\n } else {\n // mark that we need a transform, so that any data that comes in\n // will get processed, now that we've asked for it.\n ts.needTransform = true;\n }\n};\n\nfunction done(stream, er) {\n if (er) return stream.emit('error', er);\n\n // if there's nothing in the write buffer, then that means\n // that nothing more will ever be provided\n var ws = stream._writableState;\n var ts = stream._transformState;\n\n if (ws.length) throw new Error('Calling transform done when ws.length != 0');\n\n if (ts.transforming) throw new Error('Calling transform done when still transforming');\n\n return stream.push(null);\n}\n","\nimport {Transform} from './transform';\n\nimport {inherits} from 'util';\ninherits(PassThrough, Transform);\nexport default PassThrough;\nexport function PassThrough(options) {\n if (!(this instanceof PassThrough)) return new PassThrough(options);\n\n Transform.call(this, options);\n}\n\nPassThrough.prototype._transform = function (chunk, encoding, cb) {\n cb(null, chunk);\n};\n","import EE from 'events';\nimport {inherits} from 'util';\n\nimport {Duplex} from './readable-stream/duplex.js';\nimport {Readable} from './readable-stream/readable.js';\nimport {Writable} from './readable-stream/writable.js';\nimport {Transform} from './readable-stream/transform.js';\nimport {PassThrough} from './readable-stream/passthrough.js';\ninherits(Stream, EE);\nStream.Readable = Readable;\nStream.Writable = Writable;\nStream.Duplex = Duplex;\nStream.Transform = Transform;\nStream.PassThrough = PassThrough;\n\n// Backwards-compat with node 0.4.x\nStream.Stream = Stream;\n\nexport default Stream;\nexport {Readable,Writable,Duplex,Transform,PassThrough,Stream}\n\n// old-style streams. Note that the pipe method (the only relevant\n// part of this class) is overridden in the Readable class.\n\nfunction Stream() {\n EE.call(this);\n}\n\nStream.prototype.pipe = function(dest, options) {\n var source = this;\n\n function ondata(chunk) {\n if (dest.writable) {\n if (false === dest.write(chunk) && source.pause) {\n source.pause();\n }\n }\n }\n\n source.on('data', ondata);\n\n function ondrain() {\n if (source.readable && source.resume) {\n source.resume();\n }\n }\n\n dest.on('drain', ondrain);\n\n // If the 'end' option is not supplied, dest.end() will be called when\n // source gets the 'end' or 'close' events. Only dest.end() once.\n if (!dest._isStdio && (!options || options.end !== false)) {\n source.on('end', onend);\n source.on('close', onclose);\n }\n\n var didOnEnd = false;\n function onend() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n dest.end();\n }\n\n\n function onclose() {\n if (didOnEnd) return;\n didOnEnd = true;\n\n if (typeof dest.destroy === 'function') dest.destroy();\n }\n\n // don't leave dangling pipes when there are errors.\n function onerror(er) {\n cleanup();\n if (EE.listenerCount(this, 'error') === 0) {\n throw er; // Unhandled stream error in pipe.\n }\n }\n\n source.on('error', onerror);\n dest.on('error', onerror);\n\n // remove all the event listeners that were added.\n function cleanup() {\n source.removeListener('data', ondata);\n dest.removeListener('drain', ondrain);\n\n source.removeListener('end', onend);\n source.removeListener('close', onclose);\n\n source.removeListener('error', onerror);\n dest.removeListener('error', onerror);\n\n source.removeListener('end', cleanup);\n source.removeListener('close', cleanup);\n\n dest.removeListener('close', cleanup);\n }\n\n source.on('end', cleanup);\n source.on('close', cleanup);\n\n dest.on('close', cleanup);\n\n dest.emit('pipe', source);\n\n // Allow for unix-like usage: A.pipe(B).pipe(C)\n return dest;\n};\n","var WritableStream = require('stream').Writable\nvar inherits = require('util').inherits\n\nmodule.exports = BrowserStdout\n\n\ninherits(BrowserStdout, WritableStream)\n\nfunction BrowserStdout(opts) {\n if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)\n\n opts = opts || {}\n WritableStream.call(this, opts)\n this.label = (opts.label !== undefined) ? opts.label : 'stdout'\n}\n\nBrowserStdout.prototype._write = function(chunks, encoding, cb) {\n var output = chunks.toString ? chunks.toString() : chunks\n if (this.label === false) {\n console.log(output)\n } else {\n console.log(this.label+':', output)\n }\n process.nextTick(cb)\n}\n","'use strict';\n\n/**\n * Parse the given `qs`.\n *\n * @private\n * @param {string} qs\n * @return {Object}\n */\nmodule.exports = function parseQuery(qs) {\n return qs\n .replace('?', '')\n .split('&')\n .reduce(function(obj, pair) {\n var i = pair.indexOf('=');\n var key = pair.slice(0, i);\n var val = pair.slice(++i);\n\n // Due to how the URLSearchParams API treats spaces\n obj[key] = decodeURIComponent(val.replace(/\\+/g, '%20'));\n\n return obj;\n }, {});\n};\n","'use strict';\n\n/**\n * Highlight the given string of `js`.\n *\n * @private\n * @param {string} js\n * @return {string}\n */\nfunction highlight(js) {\n return js\n .replace(//g, '>')\n .replace(/\\/\\/(.*)/gm, '//$1')\n .replace(/('.*?')/gm, '$1')\n .replace(/(\\d+\\.\\d+)/gm, '$1')\n .replace(/(\\d+)/gm, '$1')\n .replace(\n /\\bnew[ \\t]+(\\w+)/gm,\n 'new $1'\n )\n .replace(\n /\\b(function|new|throw|return|var|if|else)\\b/gm,\n '$1'\n );\n}\n\n/**\n * Highlight the contents of tag `name`.\n *\n * @private\n * @param {string} name\n */\nmodule.exports = function highlightTags(name) {\n var code = document.getElementById('mocha').getElementsByTagName(name);\n for (var i = 0, len = code.length; i < len; ++i) {\n code[i].innerHTML = highlight(code[i].innerHTML);\n }\n};\n","var global = require('../internals/global');\n\nmodule.exports = global.Promise;\n","var anObject = require('../internals/an-object');\n\nmodule.exports = function (iterator) {\n var returnMethod = iterator['return'];\n if (returnMethod !== undefined) {\n return anObject(returnMethod.call(iterator)).value;\n }\n};\n","var anObject = require('../internals/an-object');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar toLength = require('../internals/to-length');\nvar bind = require('../internals/function-bind-context');\nvar getIteratorMethod = require('../internals/get-iterator-method');\nvar iteratorClose = require('../internals/iterator-close');\n\nvar Result = function (stopped, result) {\n this.stopped = stopped;\n this.result = result;\n};\n\nmodule.exports = function (iterable, unboundFunction, options) {\n var that = options && options.that;\n var AS_ENTRIES = !!(options && options.AS_ENTRIES);\n var IS_ITERATOR = !!(options && options.IS_ITERATOR);\n var INTERRUPTED = !!(options && options.INTERRUPTED);\n var fn = bind(unboundFunction, that, 1 + AS_ENTRIES + INTERRUPTED);\n var iterator, iterFn, index, length, result, next, step;\n\n var stop = function (condition) {\n if (iterator) iteratorClose(iterator);\n return new Result(true, condition);\n };\n\n var callFn = function (value) {\n if (AS_ENTRIES) {\n anObject(value);\n return INTERRUPTED ? fn(value[0], value[1], stop) : fn(value[0], value[1]);\n } return INTERRUPTED ? fn(value, stop) : fn(value);\n };\n\n if (IS_ITERATOR) {\n iterator = iterable;\n } else {\n iterFn = getIteratorMethod(iterable);\n if (typeof iterFn != 'function') throw TypeError('Target is not iterable');\n // optimisation for array iterators\n if (isArrayIteratorMethod(iterFn)) {\n for (index = 0, length = toLength(iterable.length); length > index; index++) {\n result = callFn(iterable[index]);\n if (result && result instanceof Result) return result;\n } return new Result(false);\n }\n iterator = iterFn.call(iterable);\n }\n\n next = iterator.next;\n while (!(step = next.call(iterator)).done) {\n try {\n result = callFn(step.value);\n } catch (error) {\n iteratorClose(iterator);\n throw error;\n }\n if (typeof result == 'object' && result && result instanceof Result) return result;\n } return new Result(false);\n};\n","var userAgent = require('../internals/engine-user-agent');\n\nmodule.exports = /(iphone|ipod|ipad).*applewebkit/i.test(userAgent);\n","var classof = require('../internals/classof-raw');\nvar global = require('../internals/global');\n\nmodule.exports = classof(global.process) == 'process';\n","var global = require('../internals/global');\nvar fails = require('../internals/fails');\nvar bind = require('../internals/function-bind-context');\nvar html = require('../internals/html');\nvar createElement = require('../internals/document-create-element');\nvar IS_IOS = require('../internals/engine-is-ios');\nvar IS_NODE = require('../internals/engine-is-node');\n\nvar location = global.location;\nvar set = global.setImmediate;\nvar clear = global.clearImmediate;\nvar process = global.process;\nvar MessageChannel = global.MessageChannel;\nvar Dispatch = global.Dispatch;\nvar counter = 0;\nvar queue = {};\nvar ONREADYSTATECHANGE = 'onreadystatechange';\nvar defer, channel, port;\n\nvar run = function (id) {\n // eslint-disable-next-line no-prototype-builtins\n if (queue.hasOwnProperty(id)) {\n var fn = queue[id];\n delete queue[id];\n fn();\n }\n};\n\nvar runner = function (id) {\n return function () {\n run(id);\n };\n};\n\nvar listener = function (event) {\n run(event.data);\n};\n\nvar post = function (id) {\n // old engines have not location.origin\n global.postMessage(id + '', location.protocol + '//' + location.host);\n};\n\n// Node.js 0.9+ & IE10+ has setImmediate, otherwise:\nif (!set || !clear) {\n set = function setImmediate(fn) {\n var args = [];\n var i = 1;\n while (arguments.length > i) args.push(arguments[i++]);\n queue[++counter] = function () {\n // eslint-disable-next-line no-new-func\n (typeof fn == 'function' ? fn : Function(fn)).apply(undefined, args);\n };\n defer(counter);\n return counter;\n };\n clear = function clearImmediate(id) {\n delete queue[id];\n };\n // Node.js 0.8-\n if (IS_NODE) {\n defer = function (id) {\n process.nextTick(runner(id));\n };\n // Sphere (JS game engine) Dispatch API\n } else if (Dispatch && Dispatch.now) {\n defer = function (id) {\n Dispatch.now(runner(id));\n };\n // Browsers with MessageChannel, includes WebWorkers\n // except iOS - https://github.com/zloirock/core-js/issues/624\n } else if (MessageChannel && !IS_IOS) {\n channel = new MessageChannel();\n port = channel.port2;\n channel.port1.onmessage = listener;\n defer = bind(port.postMessage, port, 1);\n // Browsers with postMessage, skip WebWorkers\n // IE8 has postMessage, but it's sync & typeof its postMessage is 'object'\n } else if (\n global.addEventListener &&\n typeof postMessage == 'function' &&\n !global.importScripts &&\n location && location.protocol !== 'file:' &&\n !fails(post)\n ) {\n defer = post;\n global.addEventListener('message', listener, false);\n // IE8-\n } else if (ONREADYSTATECHANGE in createElement('script')) {\n defer = function (id) {\n html.appendChild(createElement('script'))[ONREADYSTATECHANGE] = function () {\n html.removeChild(this);\n run(id);\n };\n };\n // Rest old browsers\n } else {\n defer = function (id) {\n setTimeout(runner(id), 0);\n };\n }\n}\n\nmodule.exports = {\n set: set,\n clear: clear\n};\n","var userAgent = require('../internals/engine-user-agent');\n\nmodule.exports = /web0s(?!.*chrome)/i.test(userAgent);\n","var global = require('../internals/global');\nvar getOwnPropertyDescriptor = require('../internals/object-get-own-property-descriptor').f;\nvar macrotask = require('../internals/task').set;\nvar IS_IOS = require('../internals/engine-is-ios');\nvar IS_WEBOS_WEBKIT = require('../internals/engine-is-webos-webkit');\nvar IS_NODE = require('../internals/engine-is-node');\n\nvar MutationObserver = global.MutationObserver || global.WebKitMutationObserver;\nvar document = global.document;\nvar process = global.process;\nvar Promise = global.Promise;\n// Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`\nvar queueMicrotaskDescriptor = getOwnPropertyDescriptor(global, 'queueMicrotask');\nvar queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;\n\nvar flush, head, last, notify, toggle, node, promise, then;\n\n// modern engines have queueMicrotask method\nif (!queueMicrotask) {\n flush = function () {\n var parent, fn;\n if (IS_NODE && (parent = process.domain)) parent.exit();\n while (head) {\n fn = head.fn;\n head = head.next;\n try {\n fn();\n } catch (error) {\n if (head) notify();\n else last = undefined;\n throw error;\n }\n } last = undefined;\n if (parent) parent.enter();\n };\n\n // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339\n // also except WebOS Webkit https://github.com/zloirock/core-js/issues/898\n if (!IS_IOS && !IS_NODE && !IS_WEBOS_WEBKIT && MutationObserver && document) {\n toggle = true;\n node = document.createTextNode('');\n new MutationObserver(flush).observe(node, { characterData: true });\n notify = function () {\n node.data = toggle = !toggle;\n };\n // environments with maybe non-completely correct, but existent Promise\n } else if (Promise && Promise.resolve) {\n // Promise.resolve without an argument throws an error in LG WebOS 2\n promise = Promise.resolve(undefined);\n then = promise.then;\n notify = function () {\n then.call(promise, flush);\n };\n // Node.js without promises\n } else if (IS_NODE) {\n notify = function () {\n process.nextTick(flush);\n };\n // for other environments - macrotask based on:\n // - setImmediate\n // - MessageChannel\n // - window.postMessag\n // - onreadystatechange\n // - setTimeout\n } else {\n notify = function () {\n // strange IE + webpack dev server bug - use .call(global)\n macrotask.call(global, flush);\n };\n }\n}\n\nmodule.exports = queueMicrotask || function (fn) {\n var task = { fn: fn, next: undefined };\n if (last) last.next = task;\n if (!head) {\n head = task;\n notify();\n } last = task;\n};\n","'use strict';\nvar aFunction = require('../internals/a-function');\n\nvar PromiseCapability = function (C) {\n var resolve, reject;\n this.promise = new C(function ($$resolve, $$reject) {\n if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');\n resolve = $$resolve;\n reject = $$reject;\n });\n this.resolve = aFunction(resolve);\n this.reject = aFunction(reject);\n};\n\n// 25.4.1.5 NewPromiseCapability(C)\nmodule.exports.f = function (C) {\n return new PromiseCapability(C);\n};\n","var anObject = require('../internals/an-object');\nvar isObject = require('../internals/is-object');\nvar newPromiseCapability = require('../internals/new-promise-capability');\n\nmodule.exports = function (C, x) {\n anObject(C);\n if (isObject(x) && x.constructor === C) return x;\n var promiseCapability = newPromiseCapability.f(C);\n var resolve = promiseCapability.resolve;\n resolve(x);\n return promiseCapability.promise;\n};\n","var global = require('../internals/global');\n\nmodule.exports = function (a, b) {\n var console = global.console;\n if (console && console.error) {\n arguments.length === 1 ? console.error(a) : console.error(a, b);\n }\n};\n","module.exports = function (exec) {\n try {\n return { error: false, value: exec() };\n } catch (error) {\n return { error: true, value: error };\n }\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar IS_PURE = require('../internals/is-pure');\nvar global = require('../internals/global');\nvar getBuiltIn = require('../internals/get-built-in');\nvar NativePromise = require('../internals/native-promise-constructor');\nvar redefine = require('../internals/redefine');\nvar redefineAll = require('../internals/redefine-all');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar setSpecies = require('../internals/set-species');\nvar isObject = require('../internals/is-object');\nvar aFunction = require('../internals/a-function');\nvar anInstance = require('../internals/an-instance');\nvar inspectSource = require('../internals/inspect-source');\nvar iterate = require('../internals/iterate');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar speciesConstructor = require('../internals/species-constructor');\nvar task = require('../internals/task').set;\nvar microtask = require('../internals/microtask');\nvar promiseResolve = require('../internals/promise-resolve');\nvar hostReportErrors = require('../internals/host-report-errors');\nvar newPromiseCapabilityModule = require('../internals/new-promise-capability');\nvar perform = require('../internals/perform');\nvar InternalStateModule = require('../internals/internal-state');\nvar isForced = require('../internals/is-forced');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\nvar IS_NODE = require('../internals/engine-is-node');\nvar V8_VERSION = require('../internals/engine-v8-version');\n\nvar SPECIES = wellKnownSymbol('species');\nvar PROMISE = 'Promise';\nvar getInternalState = InternalStateModule.get;\nvar setInternalState = InternalStateModule.set;\nvar getInternalPromiseState = InternalStateModule.getterFor(PROMISE);\nvar PromiseConstructor = NativePromise;\nvar TypeError = global.TypeError;\nvar document = global.document;\nvar process = global.process;\nvar $fetch = getBuiltIn('fetch');\nvar newPromiseCapability = newPromiseCapabilityModule.f;\nvar newGenericPromiseCapability = newPromiseCapability;\nvar DISPATCH_EVENT = !!(document && document.createEvent && global.dispatchEvent);\nvar NATIVE_REJECTION_EVENT = typeof PromiseRejectionEvent == 'function';\nvar UNHANDLED_REJECTION = 'unhandledrejection';\nvar REJECTION_HANDLED = 'rejectionhandled';\nvar PENDING = 0;\nvar FULFILLED = 1;\nvar REJECTED = 2;\nvar HANDLED = 1;\nvar UNHANDLED = 2;\nvar Internal, OwnPromiseCapability, PromiseWrapper, nativeThen;\n\nvar FORCED = isForced(PROMISE, function () {\n var GLOBAL_CORE_JS_PROMISE = inspectSource(PromiseConstructor) !== String(PromiseConstructor);\n if (!GLOBAL_CORE_JS_PROMISE) {\n // V8 6.6 (Node 10 and Chrome 66) have a bug with resolving custom thenables\n // https://bugs.chromium.org/p/chromium/issues/detail?id=830565\n // We can't detect it synchronously, so just check versions\n if (V8_VERSION === 66) return true;\n // Unhandled rejections tracking support, NodeJS Promise without it fails @@species test\n if (!IS_NODE && !NATIVE_REJECTION_EVENT) return true;\n }\n // We need Promise#finally in the pure version for preventing prototype pollution\n if (IS_PURE && !PromiseConstructor.prototype['finally']) return true;\n // We can't use @@species feature detection in V8 since it causes\n // deoptimization and performance degradation\n // https://github.com/zloirock/core-js/issues/679\n if (V8_VERSION >= 51 && /native code/.test(PromiseConstructor)) return false;\n // Detect correctness of subclassing with @@species support\n var promise = PromiseConstructor.resolve(1);\n var FakePromise = function (exec) {\n exec(function () { /* empty */ }, function () { /* empty */ });\n };\n var constructor = promise.constructor = {};\n constructor[SPECIES] = FakePromise;\n return !(promise.then(function () { /* empty */ }) instanceof FakePromise);\n});\n\nvar INCORRECT_ITERATION = FORCED || !checkCorrectnessOfIteration(function (iterable) {\n PromiseConstructor.all(iterable)['catch'](function () { /* empty */ });\n});\n\n// helpers\nvar isThenable = function (it) {\n var then;\n return isObject(it) && typeof (then = it.then) == 'function' ? then : false;\n};\n\nvar notify = function (state, isReject) {\n if (state.notified) return;\n state.notified = true;\n var chain = state.reactions;\n microtask(function () {\n var value = state.value;\n var ok = state.state == FULFILLED;\n var index = 0;\n // variable length - can't use forEach\n while (chain.length > index) {\n var reaction = chain[index++];\n var handler = ok ? reaction.ok : reaction.fail;\n var resolve = reaction.resolve;\n var reject = reaction.reject;\n var domain = reaction.domain;\n var result, then, exited;\n try {\n if (handler) {\n if (!ok) {\n if (state.rejection === UNHANDLED) onHandleUnhandled(state);\n state.rejection = HANDLED;\n }\n if (handler === true) result = value;\n else {\n if (domain) domain.enter();\n result = handler(value); // can throw\n if (domain) {\n domain.exit();\n exited = true;\n }\n }\n if (result === reaction.promise) {\n reject(TypeError('Promise-chain cycle'));\n } else if (then = isThenable(result)) {\n then.call(result, resolve, reject);\n } else resolve(result);\n } else reject(value);\n } catch (error) {\n if (domain && !exited) domain.exit();\n reject(error);\n }\n }\n state.reactions = [];\n state.notified = false;\n if (isReject && !state.rejection) onUnhandled(state);\n });\n};\n\nvar dispatchEvent = function (name, promise, reason) {\n var event, handler;\n if (DISPATCH_EVENT) {\n event = document.createEvent('Event');\n event.promise = promise;\n event.reason = reason;\n event.initEvent(name, false, true);\n global.dispatchEvent(event);\n } else event = { promise: promise, reason: reason };\n if (!NATIVE_REJECTION_EVENT && (handler = global['on' + name])) handler(event);\n else if (name === UNHANDLED_REJECTION) hostReportErrors('Unhandled promise rejection', reason);\n};\n\nvar onUnhandled = function (state) {\n task.call(global, function () {\n var promise = state.facade;\n var value = state.value;\n var IS_UNHANDLED = isUnhandled(state);\n var result;\n if (IS_UNHANDLED) {\n result = perform(function () {\n if (IS_NODE) {\n process.emit('unhandledRejection', value, promise);\n } else dispatchEvent(UNHANDLED_REJECTION, promise, value);\n });\n // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should\n state.rejection = IS_NODE || isUnhandled(state) ? UNHANDLED : HANDLED;\n if (result.error) throw result.value;\n }\n });\n};\n\nvar isUnhandled = function (state) {\n return state.rejection !== HANDLED && !state.parent;\n};\n\nvar onHandleUnhandled = function (state) {\n task.call(global, function () {\n var promise = state.facade;\n if (IS_NODE) {\n process.emit('rejectionHandled', promise);\n } else dispatchEvent(REJECTION_HANDLED, promise, state.value);\n });\n};\n\nvar bind = function (fn, state, unwrap) {\n return function (value) {\n fn(state, value, unwrap);\n };\n};\n\nvar internalReject = function (state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n state.value = value;\n state.state = REJECTED;\n notify(state, true);\n};\n\nvar internalResolve = function (state, value, unwrap) {\n if (state.done) return;\n state.done = true;\n if (unwrap) state = unwrap;\n try {\n if (state.facade === value) throw TypeError(\"Promise can't be resolved itself\");\n var then = isThenable(value);\n if (then) {\n microtask(function () {\n var wrapper = { done: false };\n try {\n then.call(value,\n bind(internalResolve, wrapper, state),\n bind(internalReject, wrapper, state)\n );\n } catch (error) {\n internalReject(wrapper, error, state);\n }\n });\n } else {\n state.value = value;\n state.state = FULFILLED;\n notify(state, false);\n }\n } catch (error) {\n internalReject({ done: false }, error, state);\n }\n};\n\n// constructor polyfill\nif (FORCED) {\n // 25.4.3.1 Promise(executor)\n PromiseConstructor = function Promise(executor) {\n anInstance(this, PromiseConstructor, PROMISE);\n aFunction(executor);\n Internal.call(this);\n var state = getInternalState(this);\n try {\n executor(bind(internalResolve, state), bind(internalReject, state));\n } catch (error) {\n internalReject(state, error);\n }\n };\n // eslint-disable-next-line no-unused-vars\n Internal = function Promise(executor) {\n setInternalState(this, {\n type: PROMISE,\n done: false,\n notified: false,\n parent: false,\n reactions: [],\n rejection: false,\n state: PENDING,\n value: undefined\n });\n };\n Internal.prototype = redefineAll(PromiseConstructor.prototype, {\n // `Promise.prototype.then` method\n // https://tc39.es/ecma262/#sec-promise.prototype.then\n then: function then(onFulfilled, onRejected) {\n var state = getInternalPromiseState(this);\n var reaction = newPromiseCapability(speciesConstructor(this, PromiseConstructor));\n reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;\n reaction.fail = typeof onRejected == 'function' && onRejected;\n reaction.domain = IS_NODE ? process.domain : undefined;\n state.parent = true;\n state.reactions.push(reaction);\n if (state.state != PENDING) notify(state, false);\n return reaction.promise;\n },\n // `Promise.prototype.catch` method\n // https://tc39.es/ecma262/#sec-promise.prototype.catch\n 'catch': function (onRejected) {\n return this.then(undefined, onRejected);\n }\n });\n OwnPromiseCapability = function () {\n var promise = new Internal();\n var state = getInternalState(promise);\n this.promise = promise;\n this.resolve = bind(internalResolve, state);\n this.reject = bind(internalReject, state);\n };\n newPromiseCapabilityModule.f = newPromiseCapability = function (C) {\n return C === PromiseConstructor || C === PromiseWrapper\n ? new OwnPromiseCapability(C)\n : newGenericPromiseCapability(C);\n };\n\n if (!IS_PURE && typeof NativePromise == 'function') {\n nativeThen = NativePromise.prototype.then;\n\n // wrap native Promise#then for native async functions\n redefine(NativePromise.prototype, 'then', function then(onFulfilled, onRejected) {\n var that = this;\n return new PromiseConstructor(function (resolve, reject) {\n nativeThen.call(that, resolve, reject);\n }).then(onFulfilled, onRejected);\n // https://github.com/zloirock/core-js/issues/640\n }, { unsafe: true });\n\n // wrap fetch result\n if (typeof $fetch == 'function') $({ global: true, enumerable: true, forced: true }, {\n // eslint-disable-next-line no-unused-vars\n fetch: function fetch(input /* , init */) {\n return promiseResolve(PromiseConstructor, $fetch.apply(global, arguments));\n }\n });\n }\n}\n\n$({ global: true, wrap: true, forced: FORCED }, {\n Promise: PromiseConstructor\n});\n\nsetToStringTag(PromiseConstructor, PROMISE, false, true);\nsetSpecies(PROMISE);\n\nPromiseWrapper = getBuiltIn(PROMISE);\n\n// statics\n$({ target: PROMISE, stat: true, forced: FORCED }, {\n // `Promise.reject` method\n // https://tc39.es/ecma262/#sec-promise.reject\n reject: function reject(r) {\n var capability = newPromiseCapability(this);\n capability.reject.call(undefined, r);\n return capability.promise;\n }\n});\n\n$({ target: PROMISE, stat: true, forced: IS_PURE || FORCED }, {\n // `Promise.resolve` method\n // https://tc39.es/ecma262/#sec-promise.resolve\n resolve: function resolve(x) {\n return promiseResolve(IS_PURE && this === PromiseWrapper ? PromiseConstructor : this, x);\n }\n});\n\n$({ target: PROMISE, stat: true, forced: INCORRECT_ITERATION }, {\n // `Promise.all` method\n // https://tc39.es/ecma262/#sec-promise.all\n all: function all(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var resolve = capability.resolve;\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n var values = [];\n var counter = 0;\n var remaining = 1;\n iterate(iterable, function (promise) {\n var index = counter++;\n var alreadyCalled = false;\n values.push(undefined);\n remaining++;\n $promiseResolve.call(C, promise).then(function (value) {\n if (alreadyCalled) return;\n alreadyCalled = true;\n values[index] = value;\n --remaining || resolve(values);\n }, reject);\n });\n --remaining || resolve(values);\n });\n if (result.error) reject(result.value);\n return capability.promise;\n },\n // `Promise.race` method\n // https://tc39.es/ecma262/#sec-promise.race\n race: function race(iterable) {\n var C = this;\n var capability = newPromiseCapability(C);\n var reject = capability.reject;\n var result = perform(function () {\n var $promiseResolve = aFunction(C.resolve);\n iterate(iterable, function (promise) {\n $promiseResolve.call(C, promise).then(capability.resolve, reject);\n });\n });\n if (result.error) reject(result.value);\n return capability.promise;\n }\n});\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.asyncIterator` well-known symbol\n// https://tc39.es/ecma262/#sec-symbol.asynciterator\ndefineWellKnownSymbol('asyncIterator');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.iterator` well-known symbol\n// https://tc39.es/ecma262/#sec-symbol.iterator\ndefineWellKnownSymbol('iterator');\n","var defineWellKnownSymbol = require('../internals/define-well-known-symbol');\n\n// `Symbol.toStringTag` well-known symbol\n// https://tc39.es/ecma262/#sec-symbol.tostringtag\ndefineWellKnownSymbol('toStringTag');\n","var global = require('../internals/global');\nvar setToStringTag = require('../internals/set-to-string-tag');\n\n// JSON[@@toStringTag] property\n// https://tc39.es/ecma262/#sec-json-@@tostringtag\nsetToStringTag(global.JSON, 'JSON', true);\n","var setToStringTag = require('../internals/set-to-string-tag');\n\n// Math[@@toStringTag] property\n// https://tc39.es/ecma262/#sec-math-@@tostringtag\nsetToStringTag(Math, 'Math', true);\n","'use strict';\nvar charAt = require('../internals/string-multibyte').charAt;\nvar InternalStateModule = require('../internals/internal-state');\nvar defineIterator = require('../internals/define-iterator');\n\nvar STRING_ITERATOR = 'String Iterator';\nvar setInternalState = InternalStateModule.set;\nvar getInternalState = InternalStateModule.getterFor(STRING_ITERATOR);\n\n// `String.prototype[@@iterator]` method\n// https://tc39.es/ecma262/#sec-string.prototype-@@iterator\ndefineIterator(String, 'String', function (iterated) {\n setInternalState(this, {\n type: STRING_ITERATOR,\n string: String(iterated),\n index: 0\n });\n// `%StringIteratorPrototype%.next` method\n// https://tc39.es/ecma262/#sec-%stringiteratorprototype%.next\n}, function next() {\n var state = getInternalState(this);\n var string = state.string;\n var index = state.index;\n var point;\n if (index >= string.length) return { value: undefined, done: true };\n point = charAt(string, index);\n state.index += point.length;\n return { value: point, done: false };\n});\n","var global = require('../internals/global');\nvar DOMIterables = require('../internals/dom-iterables');\nvar ArrayIteratorMethods = require('../modules/es.array.iterator');\nvar createNonEnumerableProperty = require('../internals/create-non-enumerable-property');\nvar wellKnownSymbol = require('../internals/well-known-symbol');\n\nvar ITERATOR = wellKnownSymbol('iterator');\nvar TO_STRING_TAG = wellKnownSymbol('toStringTag');\nvar ArrayValues = ArrayIteratorMethods.values;\n\nfor (var COLLECTION_NAME in DOMIterables) {\n var Collection = global[COLLECTION_NAME];\n var CollectionPrototype = Collection && Collection.prototype;\n if (CollectionPrototype) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[ITERATOR] !== ArrayValues) try {\n createNonEnumerableProperty(CollectionPrototype, ITERATOR, ArrayValues);\n } catch (error) {\n CollectionPrototype[ITERATOR] = ArrayValues;\n }\n if (!CollectionPrototype[TO_STRING_TAG]) {\n createNonEnumerableProperty(CollectionPrototype, TO_STRING_TAG, COLLECTION_NAME);\n }\n if (DOMIterables[COLLECTION_NAME]) for (var METHOD_NAME in ArrayIteratorMethods) {\n // some Chrome versions have non-configurable methods on DOMTokenList\n if (CollectionPrototype[METHOD_NAME] !== ArrayIteratorMethods[METHOD_NAME]) try {\n createNonEnumerableProperty(CollectionPrototype, METHOD_NAME, ArrayIteratorMethods[METHOD_NAME]);\n } catch (error) {\n CollectionPrototype[METHOD_NAME] = ArrayIteratorMethods[METHOD_NAME];\n }\n }\n }\n}\n","/**\n * Copyright (c) 2014-present, Facebook, Inc.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\nvar runtime = (function (exports) {\n \"use strict\";\n\n var Op = Object.prototype;\n var hasOwn = Op.hasOwnProperty;\n var undefined; // More compressible than void 0.\n var $Symbol = typeof Symbol === \"function\" ? Symbol : {};\n var iteratorSymbol = $Symbol.iterator || \"@@iterator\";\n var asyncIteratorSymbol = $Symbol.asyncIterator || \"@@asyncIterator\";\n var toStringTagSymbol = $Symbol.toStringTag || \"@@toStringTag\";\n\n function define(obj, key, value) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n return obj[key];\n }\n try {\n // IE 8 has a broken Object.defineProperty that only works on DOM objects.\n define({}, \"\");\n } catch (err) {\n define = function(obj, key, value) {\n return obj[key] = value;\n };\n }\n\n function wrap(innerFn, outerFn, self, tryLocsList) {\n // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.\n var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;\n var generator = Object.create(protoGenerator.prototype);\n var context = new Context(tryLocsList || []);\n\n // The ._invoke method unifies the implementations of the .next,\n // .throw, and .return methods.\n generator._invoke = makeInvokeMethod(innerFn, self, context);\n\n return generator;\n }\n exports.wrap = wrap;\n\n // Try/catch helper to minimize deoptimizations. Returns a completion\n // record like context.tryEntries[i].completion. This interface could\n // have been (and was previously) designed to take a closure to be\n // invoked without arguments, but in all the cases we care about we\n // already have an existing method we want to call, so there's no need\n // to create a new function object. We can even get away with assuming\n // the method takes exactly one argument, since that happens to be true\n // in every case, so we don't have to touch the arguments object. The\n // only additional allocation required is the completion record, which\n // has a stable shape and so hopefully should be cheap to allocate.\n function tryCatch(fn, obj, arg) {\n try {\n return { type: \"normal\", arg: fn.call(obj, arg) };\n } catch (err) {\n return { type: \"throw\", arg: err };\n }\n }\n\n var GenStateSuspendedStart = \"suspendedStart\";\n var GenStateSuspendedYield = \"suspendedYield\";\n var GenStateExecuting = \"executing\";\n var GenStateCompleted = \"completed\";\n\n // Returning this object from the innerFn has the same effect as\n // breaking out of the dispatch switch statement.\n var ContinueSentinel = {};\n\n // Dummy constructor functions that we use as the .constructor and\n // .constructor.prototype properties for functions that return Generator\n // objects. For full spec compliance, you may wish to configure your\n // minifier not to mangle the names of these two functions.\n function Generator() {}\n function GeneratorFunction() {}\n function GeneratorFunctionPrototype() {}\n\n // This is a polyfill for %IteratorPrototype% for environments that\n // don't natively support it.\n var IteratorPrototype = {};\n IteratorPrototype[iteratorSymbol] = function () {\n return this;\n };\n\n var getProto = Object.getPrototypeOf;\n var NativeIteratorPrototype = getProto && getProto(getProto(values([])));\n if (NativeIteratorPrototype &&\n NativeIteratorPrototype !== Op &&\n hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {\n // This environment has a native %IteratorPrototype%; use it instead\n // of the polyfill.\n IteratorPrototype = NativeIteratorPrototype;\n }\n\n var Gp = GeneratorFunctionPrototype.prototype =\n Generator.prototype = Object.create(IteratorPrototype);\n GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;\n GeneratorFunctionPrototype.constructor = GeneratorFunction;\n GeneratorFunction.displayName = define(\n GeneratorFunctionPrototype,\n toStringTagSymbol,\n \"GeneratorFunction\"\n );\n\n // Helper for defining the .next, .throw, and .return methods of the\n // Iterator interface in terms of a single ._invoke method.\n function defineIteratorMethods(prototype) {\n [\"next\", \"throw\", \"return\"].forEach(function(method) {\n define(prototype, method, function(arg) {\n return this._invoke(method, arg);\n });\n });\n }\n\n exports.isGeneratorFunction = function(genFun) {\n var ctor = typeof genFun === \"function\" && genFun.constructor;\n return ctor\n ? ctor === GeneratorFunction ||\n // For the native GeneratorFunction constructor, the best we can\n // do is to check its .name property.\n (ctor.displayName || ctor.name) === \"GeneratorFunction\"\n : false;\n };\n\n exports.mark = function(genFun) {\n if (Object.setPrototypeOf) {\n Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);\n } else {\n genFun.__proto__ = GeneratorFunctionPrototype;\n define(genFun, toStringTagSymbol, \"GeneratorFunction\");\n }\n genFun.prototype = Object.create(Gp);\n return genFun;\n };\n\n // Within the body of any async function, `await x` is transformed to\n // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test\n // `hasOwn.call(value, \"__await\")` to determine if the yielded value is\n // meant to be awaited.\n exports.awrap = function(arg) {\n return { __await: arg };\n };\n\n function AsyncIterator(generator, PromiseImpl) {\n function invoke(method, arg, resolve, reject) {\n var record = tryCatch(generator[method], generator, arg);\n if (record.type === \"throw\") {\n reject(record.arg);\n } else {\n var result = record.arg;\n var value = result.value;\n if (value &&\n typeof value === \"object\" &&\n hasOwn.call(value, \"__await\")) {\n return PromiseImpl.resolve(value.__await).then(function(value) {\n invoke(\"next\", value, resolve, reject);\n }, function(err) {\n invoke(\"throw\", err, resolve, reject);\n });\n }\n\n return PromiseImpl.resolve(value).then(function(unwrapped) {\n // When a yielded Promise is resolved, its final value becomes\n // the .value of the Promise<{value,done}> result for the\n // current iteration.\n result.value = unwrapped;\n resolve(result);\n }, function(error) {\n // If a rejected Promise was yielded, throw the rejection back\n // into the async generator function so it can be handled there.\n return invoke(\"throw\", error, resolve, reject);\n });\n }\n }\n\n var previousPromise;\n\n function enqueue(method, arg) {\n function callInvokeWithMethodAndArg() {\n return new PromiseImpl(function(resolve, reject) {\n invoke(method, arg, resolve, reject);\n });\n }\n\n return previousPromise =\n // If enqueue has been called before, then we want to wait until\n // all previous Promises have been resolved before calling invoke,\n // so that results are always delivered in the correct order. If\n // enqueue has not been called before, then it is important to\n // call invoke immediately, without waiting on a callback to fire,\n // so that the async generator function has the opportunity to do\n // any necessary setup in a predictable way. This predictability\n // is why the Promise constructor synchronously invokes its\n // executor callback, and why async functions synchronously\n // execute code before the first await. Since we implement simple\n // async functions in terms of async generators, it is especially\n // important to get this right, even though it requires care.\n previousPromise ? previousPromise.then(\n callInvokeWithMethodAndArg,\n // Avoid propagating failures to Promises returned by later\n // invocations of the iterator.\n callInvokeWithMethodAndArg\n ) : callInvokeWithMethodAndArg();\n }\n\n // Define the unified helper method that is used to implement .next,\n // .throw, and .return (see defineIteratorMethods).\n this._invoke = enqueue;\n }\n\n defineIteratorMethods(AsyncIterator.prototype);\n AsyncIterator.prototype[asyncIteratorSymbol] = function () {\n return this;\n };\n exports.AsyncIterator = AsyncIterator;\n\n // Note that simple async functions are implemented on top of\n // AsyncIterator objects; they just return a Promise for the value of\n // the final result produced by the iterator.\n exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) {\n if (PromiseImpl === void 0) PromiseImpl = Promise;\n\n var iter = new AsyncIterator(\n wrap(innerFn, outerFn, self, tryLocsList),\n PromiseImpl\n );\n\n return exports.isGeneratorFunction(outerFn)\n ? iter // If outerFn is a generator, return the full iterator.\n : iter.next().then(function(result) {\n return result.done ? result.value : iter.next();\n });\n };\n\n function makeInvokeMethod(innerFn, self, context) {\n var state = GenStateSuspendedStart;\n\n return function invoke(method, arg) {\n if (state === GenStateExecuting) {\n throw new Error(\"Generator is already running\");\n }\n\n if (state === GenStateCompleted) {\n if (method === \"throw\") {\n throw arg;\n }\n\n // Be forgiving, per 25.3.3.3.3 of the spec:\n // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume\n return doneResult();\n }\n\n context.method = method;\n context.arg = arg;\n\n while (true) {\n var delegate = context.delegate;\n if (delegate) {\n var delegateResult = maybeInvokeDelegate(delegate, context);\n if (delegateResult) {\n if (delegateResult === ContinueSentinel) continue;\n return delegateResult;\n }\n }\n\n if (context.method === \"next\") {\n // Setting context._sent for legacy support of Babel's\n // function.sent implementation.\n context.sent = context._sent = context.arg;\n\n } else if (context.method === \"throw\") {\n if (state === GenStateSuspendedStart) {\n state = GenStateCompleted;\n throw context.arg;\n }\n\n context.dispatchException(context.arg);\n\n } else if (context.method === \"return\") {\n context.abrupt(\"return\", context.arg);\n }\n\n state = GenStateExecuting;\n\n var record = tryCatch(innerFn, self, context);\n if (record.type === \"normal\") {\n // If an exception is thrown from innerFn, we leave state ===\n // GenStateExecuting and loop back for another invocation.\n state = context.done\n ? GenStateCompleted\n : GenStateSuspendedYield;\n\n if (record.arg === ContinueSentinel) {\n continue;\n }\n\n return {\n value: record.arg,\n done: context.done\n };\n\n } else if (record.type === \"throw\") {\n state = GenStateCompleted;\n // Dispatch the exception by looping back around to the\n // context.dispatchException(context.arg) call above.\n context.method = \"throw\";\n context.arg = record.arg;\n }\n }\n };\n }\n\n // Call delegate.iterator[context.method](context.arg) and handle the\n // result, either by returning a { value, done } result from the\n // delegate iterator, or by modifying context.method and context.arg,\n // setting context.delegate to null, and returning the ContinueSentinel.\n function maybeInvokeDelegate(delegate, context) {\n var method = delegate.iterator[context.method];\n if (method === undefined) {\n // A .throw or .return when the delegate iterator has no .throw\n // method always terminates the yield* loop.\n context.delegate = null;\n\n if (context.method === \"throw\") {\n // Note: [\"return\"] must be used for ES3 parsing compatibility.\n if (delegate.iterator[\"return\"]) {\n // If the delegate iterator has a return method, give it a\n // chance to clean up.\n context.method = \"return\";\n context.arg = undefined;\n maybeInvokeDelegate(delegate, context);\n\n if (context.method === \"throw\") {\n // If maybeInvokeDelegate(context) changed context.method from\n // \"return\" to \"throw\", let that override the TypeError below.\n return ContinueSentinel;\n }\n }\n\n context.method = \"throw\";\n context.arg = new TypeError(\n \"The iterator does not provide a 'throw' method\");\n }\n\n return ContinueSentinel;\n }\n\n var record = tryCatch(method, delegate.iterator, context.arg);\n\n if (record.type === \"throw\") {\n context.method = \"throw\";\n context.arg = record.arg;\n context.delegate = null;\n return ContinueSentinel;\n }\n\n var info = record.arg;\n\n if (! info) {\n context.method = \"throw\";\n context.arg = new TypeError(\"iterator result is not an object\");\n context.delegate = null;\n return ContinueSentinel;\n }\n\n if (info.done) {\n // Assign the result of the finished delegate to the temporary\n // variable specified by delegate.resultName (see delegateYield).\n context[delegate.resultName] = info.value;\n\n // Resume execution at the desired location (see delegateYield).\n context.next = delegate.nextLoc;\n\n // If context.method was \"throw\" but the delegate handled the\n // exception, let the outer generator proceed normally. If\n // context.method was \"next\", forget context.arg since it has been\n // \"consumed\" by the delegate iterator. If context.method was\n // \"return\", allow the original .return call to continue in the\n // outer generator.\n if (context.method !== \"return\") {\n context.method = \"next\";\n context.arg = undefined;\n }\n\n } else {\n // Re-yield the result returned by the delegate method.\n return info;\n }\n\n // The delegate iterator is finished, so forget it and continue with\n // the outer generator.\n context.delegate = null;\n return ContinueSentinel;\n }\n\n // Define Generator.prototype.{next,throw,return} in terms of the\n // unified ._invoke helper method.\n defineIteratorMethods(Gp);\n\n define(Gp, toStringTagSymbol, \"Generator\");\n\n // A Generator should always return itself as the iterator object when the\n // @@iterator function is called on it. Some browsers' implementations of the\n // iterator prototype chain incorrectly implement this, causing the Generator\n // object to not be returned from this call. This ensures that doesn't happen.\n // See https://github.com/facebook/regenerator/issues/274 for more details.\n Gp[iteratorSymbol] = function() {\n return this;\n };\n\n Gp.toString = function() {\n return \"[object Generator]\";\n };\n\n function pushTryEntry(locs) {\n var entry = { tryLoc: locs[0] };\n\n if (1 in locs) {\n entry.catchLoc = locs[1];\n }\n\n if (2 in locs) {\n entry.finallyLoc = locs[2];\n entry.afterLoc = locs[3];\n }\n\n this.tryEntries.push(entry);\n }\n\n function resetTryEntry(entry) {\n var record = entry.completion || {};\n record.type = \"normal\";\n delete record.arg;\n entry.completion = record;\n }\n\n function Context(tryLocsList) {\n // The root entry object (effectively a try statement without a catch\n // or a finally block) gives us a place to store values thrown from\n // locations where there is no enclosing try statement.\n this.tryEntries = [{ tryLoc: \"root\" }];\n tryLocsList.forEach(pushTryEntry, this);\n this.reset(true);\n }\n\n exports.keys = function(object) {\n var keys = [];\n for (var key in object) {\n keys.push(key);\n }\n keys.reverse();\n\n // Rather than returning an object with a next method, we keep\n // things simple and return the next function itself.\n return function next() {\n while (keys.length) {\n var key = keys.pop();\n if (key in object) {\n next.value = key;\n next.done = false;\n return next;\n }\n }\n\n // To avoid creating an additional object, we just hang the .value\n // and .done properties off the next function object itself. This\n // also ensures that the minifier will not anonymize the function.\n next.done = true;\n return next;\n };\n };\n\n function values(iterable) {\n if (iterable) {\n var iteratorMethod = iterable[iteratorSymbol];\n if (iteratorMethod) {\n return iteratorMethod.call(iterable);\n }\n\n if (typeof iterable.next === \"function\") {\n return iterable;\n }\n\n if (!isNaN(iterable.length)) {\n var i = -1, next = function next() {\n while (++i < iterable.length) {\n if (hasOwn.call(iterable, i)) {\n next.value = iterable[i];\n next.done = false;\n return next;\n }\n }\n\n next.value = undefined;\n next.done = true;\n\n return next;\n };\n\n return next.next = next;\n }\n }\n\n // Return an iterator with no values.\n return { next: doneResult };\n }\n exports.values = values;\n\n function doneResult() {\n return { value: undefined, done: true };\n }\n\n Context.prototype = {\n constructor: Context,\n\n reset: function(skipTempReset) {\n this.prev = 0;\n this.next = 0;\n // Resetting context._sent for legacy support of Babel's\n // function.sent implementation.\n this.sent = this._sent = undefined;\n this.done = false;\n this.delegate = null;\n\n this.method = \"next\";\n this.arg = undefined;\n\n this.tryEntries.forEach(resetTryEntry);\n\n if (!skipTempReset) {\n for (var name in this) {\n // Not sure about the optimal order of these conditions:\n if (name.charAt(0) === \"t\" &&\n hasOwn.call(this, name) &&\n !isNaN(+name.slice(1))) {\n this[name] = undefined;\n }\n }\n }\n },\n\n stop: function() {\n this.done = true;\n\n var rootEntry = this.tryEntries[0];\n var rootRecord = rootEntry.completion;\n if (rootRecord.type === \"throw\") {\n throw rootRecord.arg;\n }\n\n return this.rval;\n },\n\n dispatchException: function(exception) {\n if (this.done) {\n throw exception;\n }\n\n var context = this;\n function handle(loc, caught) {\n record.type = \"throw\";\n record.arg = exception;\n context.next = loc;\n\n if (caught) {\n // If the dispatched exception was caught by a catch block,\n // then let that catch block handle the exception normally.\n context.method = \"next\";\n context.arg = undefined;\n }\n\n return !! caught;\n }\n\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n var record = entry.completion;\n\n if (entry.tryLoc === \"root\") {\n // Exception thrown outside of any try block that could handle\n // it, so set the completion value of the entire function to\n // throw the exception.\n return handle(\"end\");\n }\n\n if (entry.tryLoc <= this.prev) {\n var hasCatch = hasOwn.call(entry, \"catchLoc\");\n var hasFinally = hasOwn.call(entry, \"finallyLoc\");\n\n if (hasCatch && hasFinally) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n } else if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else if (hasCatch) {\n if (this.prev < entry.catchLoc) {\n return handle(entry.catchLoc, true);\n }\n\n } else if (hasFinally) {\n if (this.prev < entry.finallyLoc) {\n return handle(entry.finallyLoc);\n }\n\n } else {\n throw new Error(\"try statement without catch or finally\");\n }\n }\n }\n },\n\n abrupt: function(type, arg) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc <= this.prev &&\n hasOwn.call(entry, \"finallyLoc\") &&\n this.prev < entry.finallyLoc) {\n var finallyEntry = entry;\n break;\n }\n }\n\n if (finallyEntry &&\n (type === \"break\" ||\n type === \"continue\") &&\n finallyEntry.tryLoc <= arg &&\n arg <= finallyEntry.finallyLoc) {\n // Ignore the finally entry if control is not jumping to a\n // location outside the try/catch block.\n finallyEntry = null;\n }\n\n var record = finallyEntry ? finallyEntry.completion : {};\n record.type = type;\n record.arg = arg;\n\n if (finallyEntry) {\n this.method = \"next\";\n this.next = finallyEntry.finallyLoc;\n return ContinueSentinel;\n }\n\n return this.complete(record);\n },\n\n complete: function(record, afterLoc) {\n if (record.type === \"throw\") {\n throw record.arg;\n }\n\n if (record.type === \"break\" ||\n record.type === \"continue\") {\n this.next = record.arg;\n } else if (record.type === \"return\") {\n this.rval = this.arg = record.arg;\n this.method = \"return\";\n this.next = \"end\";\n } else if (record.type === \"normal\" && afterLoc) {\n this.next = afterLoc;\n }\n\n return ContinueSentinel;\n },\n\n finish: function(finallyLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.finallyLoc === finallyLoc) {\n this.complete(entry.completion, entry.afterLoc);\n resetTryEntry(entry);\n return ContinueSentinel;\n }\n }\n },\n\n \"catch\": function(tryLoc) {\n for (var i = this.tryEntries.length - 1; i >= 0; --i) {\n var entry = this.tryEntries[i];\n if (entry.tryLoc === tryLoc) {\n var record = entry.completion;\n if (record.type === \"throw\") {\n var thrown = record.arg;\n resetTryEntry(entry);\n }\n return thrown;\n }\n }\n\n // The context.catch method must only be called with a location\n // argument that corresponds to a known catch block.\n throw new Error(\"illegal catch attempt\");\n },\n\n delegateYield: function(iterable, resultName, nextLoc) {\n this.delegate = {\n iterator: values(iterable),\n resultName: resultName,\n nextLoc: nextLoc\n };\n\n if (this.method === \"next\") {\n // Deliberately forget the last sent value so that we don't\n // accidentally pass it on to the delegate.\n this.arg = undefined;\n }\n\n return ContinueSentinel;\n }\n };\n\n // Regardless of whether this script is executing as a CommonJS module\n // or not, return the runtime object so that we can declare the variable\n // regeneratorRuntime in the outer scope, which allows this module to be\n // injected easily by `bin/regenerator --include-runtime script.js`.\n return exports;\n\n}(\n // If this script is executing as a CommonJS module, use module.exports\n // as the regeneratorRuntime namespace. Otherwise create a new empty\n // object. Either way, the resulting object will be used to initialize\n // the regeneratorRuntime variable at the top of this file.\n typeof module === \"object\" ? module.exports : {}\n));\n\ntry {\n regeneratorRuntime = runtime;\n} catch (accidentalStrictMode) {\n // This module should not be running in strict mode, so the above\n // assignment should always work unless something is misconfigured. Just\n // in case runtime.js accidentally runs in strict mode, we can escape\n // strict mode using a global Function call. This could conceivably fail\n // if a Content Security Policy forbids using Function, but in that case\n // the proper solution is to fix the accidental strict mode problem. If\n // you've misconfigured your bundler to force strict mode and applied a\n // CSP to forbid Function, and you're not willing to fix either of those\n // problems, please detail your unique predicament in a GitHub issue.\n Function(\"r\", \"regeneratorRuntime = r\")(runtime);\n}\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a \\unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n};\n","// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n// resolves . and .. elements in a path array with directory names there\n// must be no slashes, empty elements, or device names (c:\\) in the array\n// (so also no leading and trailing slashes - it does not distinguish\n// relative and absolute paths)\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n var up = 0;\n for (var i = parts.length - 1; i >= 0; i--) {\n var last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nvar splitPathRe =\n /^(\\/?|)([\\s\\S]*?)((?:\\.{1,2}|[^\\/]+?|)(\\.[^.\\/]*|))(?:[\\/]*)$/;\nvar splitPath = function(filename) {\n return splitPathRe.exec(filename).slice(1);\n};\n\n// path.resolve([from ...], to)\n// posix version\nexport function resolve() {\n var resolvedPath = '',\n resolvedAbsolute = false;\n\n for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n var path = (i >= 0) ? arguments[i] : '/';\n\n // Skip empty and invalid entries\n if (typeof path !== 'string') {\n throw new TypeError('Arguments to path.resolve must be strings');\n } else if (!path) {\n continue;\n }\n\n resolvedPath = path + '/' + resolvedPath;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {\n return !!p;\n }), !resolvedAbsolute).join('/');\n\n return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';\n};\n\n// path.normalize(path)\n// posix version\nexport function normalize(path) {\n var isPathAbsolute = isAbsolute(path),\n trailingSlash = substr(path, -1) === '/';\n\n // Normalize the path\n path = normalizeArray(filter(path.split('/'), function(p) {\n return !!p;\n }), !isPathAbsolute).join('/');\n\n if (!path && !isPathAbsolute) {\n path = '.';\n }\n if (path && trailingSlash) {\n path += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + path;\n};\n\n// posix version\nexport function isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\nexport function join() {\n var paths = Array.prototype.slice.call(arguments, 0);\n return normalize(filter(paths, function(p, index) {\n if (typeof p !== 'string') {\n throw new TypeError('Arguments to path.join must be strings');\n }\n return p;\n }).join('/'));\n}\n\n\n// path.relative(from, to)\n// posix version\nexport function relative(from, to) {\n from = resolve(from).substr(1);\n to = resolve(to).substr(1);\n\n function trim(arr) {\n var start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') break;\n }\n\n var end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') break;\n }\n\n if (start > end) return [];\n return arr.slice(start, end - start + 1);\n }\n\n var fromParts = trim(from.split('/'));\n var toParts = trim(to.split('/'));\n\n var length = Math.min(fromParts.length, toParts.length);\n var samePartsLength = length;\n for (var i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n var outputParts = [];\n for (var i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\nexport var sep = '/';\nexport var delimiter = ':';\n\nexport function dirname(path) {\n var result = splitPath(path),\n root = result[0],\n dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.substr(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\nexport function basename(path, ext) {\n var f = splitPath(path)[2];\n // TODO: make this comparison case-insensitive on windows?\n if (ext && f.substr(-1 * ext.length) === ext) {\n f = f.substr(0, f.length - ext.length);\n }\n return f;\n}\n\n\nexport function extname(path) {\n return splitPath(path)[3];\n}\nexport default {\n extname: extname,\n basename: basename,\n dirname: dirname,\n sep: sep,\n delimiter: delimiter,\n relative: relative,\n join: join,\n isAbsolute: isAbsolute,\n normalize: normalize,\n resolve: resolve\n};\nfunction filter (xs, f) {\n if (xs.filter) return xs.filter(f);\n var res = [];\n for (var i = 0; i < xs.length; i++) {\n if (f(xs[i], i, xs)) res.push(xs[i]);\n }\n return res;\n}\n\n// String.prototype.substr - negative index don't work in IE8\nvar substr = 'ab'.substr(-1) === 'b' ?\n function (str, start, len) { return str.substr(start, len) } :\n function (str, start, len) {\n if (start < 0) start = str.length + start;\n return str.substr(start, len);\n }\n;\n","var anObject = require('../internals/an-object');\nvar iteratorClose = require('../internals/iterator-close');\n\n// call something on iterator step with safe closing on error\nmodule.exports = function (iterator, fn, value, ENTRIES) {\n try {\n return ENTRIES ? fn(anObject(value)[0], value[1]) : fn(value);\n // 7.4.6 IteratorClose(iterator, completion)\n } catch (error) {\n iteratorClose(iterator);\n throw error;\n }\n};\n","'use strict';\nvar bind = require('../internals/function-bind-context');\nvar toObject = require('../internals/to-object');\nvar callWithSafeIterationClosing = require('../internals/call-with-safe-iteration-closing');\nvar isArrayIteratorMethod = require('../internals/is-array-iterator-method');\nvar toLength = require('../internals/to-length');\nvar createProperty = require('../internals/create-property');\nvar getIteratorMethod = require('../internals/get-iterator-method');\n\n// `Array.from` method implementation\n// https://tc39.es/ecma262/#sec-array.from\nmodule.exports = function from(arrayLike /* , mapfn = undefined, thisArg = undefined */) {\n var O = toObject(arrayLike);\n var C = typeof this == 'function' ? this : Array;\n var argumentsLength = arguments.length;\n var mapfn = argumentsLength > 1 ? arguments[1] : undefined;\n var mapping = mapfn !== undefined;\n var iteratorMethod = getIteratorMethod(O);\n var index = 0;\n var length, result, step, iterator, next, value;\n if (mapping) mapfn = bind(mapfn, argumentsLength > 2 ? arguments[2] : undefined, 2);\n // if the target is not iterable or it's an array with the default iterator - use a simple case\n if (iteratorMethod != undefined && !(C == Array && isArrayIteratorMethod(iteratorMethod))) {\n iterator = iteratorMethod.call(O);\n next = iterator.next;\n result = new C();\n for (;!(step = next.call(iterator)).done; index++) {\n value = mapping ? callWithSafeIterationClosing(iterator, mapfn, [step.value, index], true) : step.value;\n createProperty(result, index, value);\n }\n } else {\n length = toLength(O.length);\n result = new C(length);\n for (;length > index; index++) {\n value = mapping ? mapfn(O[index], index) : O[index];\n createProperty(result, index, value);\n }\n }\n result.length = index;\n return result;\n};\n","var $ = require('../internals/export');\nvar from = require('../internals/array-from');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\n\nvar INCORRECT_ITERATION = !checkCorrectnessOfIteration(function (iterable) {\n Array.from(iterable);\n});\n\n// `Array.from` method\n// https://tc39.es/ecma262/#sec-array.from\n$({ target: 'Array', stat: true, forced: INCORRECT_ITERATION }, {\n from: from\n});\n","(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :\n typeof define === 'function' && define.amd ? define(['exports'], factory) :\n (global = global || self, factory(global.Diff = {}));\n}(this, (function (exports) { 'use strict';\n\n function Diff() {}\n Diff.prototype = {\n diff: function diff(oldString, newString) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var callback = options.callback;\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n this.options = options;\n var self = this;\n\n function done(value) {\n if (callback) {\n setTimeout(function () {\n callback(undefined, value);\n }, 0);\n return true;\n } else {\n return value;\n }\n } // Allow subclasses to massage the input prior to running\n\n\n oldString = this.castInput(oldString);\n newString = this.castInput(newString);\n oldString = this.removeEmpty(this.tokenize(oldString));\n newString = this.removeEmpty(this.tokenize(newString));\n var newLen = newString.length,\n oldLen = oldString.length;\n var editLength = 1;\n var maxEditLength = newLen + oldLen;\n var bestPath = [{\n newPos: -1,\n components: []\n }]; // Seed editLength = 0, i.e. the content starts with the same values\n\n var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);\n\n if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {\n // Identity per the equality and tokenizer\n return done([{\n value: this.join(newString),\n count: newString.length\n }]);\n } // Main worker method. checks all permutations of a given edit length for acceptance.\n\n\n function execEditLength() {\n for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {\n var basePath = void 0;\n\n var addPath = bestPath[diagonalPath - 1],\n removePath = bestPath[diagonalPath + 1],\n _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;\n\n if (addPath) {\n // No one else is going to attempt to use this value, clear it\n bestPath[diagonalPath - 1] = undefined;\n }\n\n var canAdd = addPath && addPath.newPos + 1 < newLen,\n canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;\n\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n bestPath[diagonalPath] = undefined;\n continue;\n } // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the new string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n\n\n if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {\n basePath = clonePath(removePath);\n self.pushComponent(basePath.components, undefined, true);\n } else {\n basePath = addPath; // No need to clone, we've pulled it from the list\n\n basePath.newPos++;\n self.pushComponent(basePath.components, true, undefined);\n }\n\n _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done\n\n if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {\n return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));\n } else {\n // Otherwise track this path as a potential candidate and continue.\n bestPath[diagonalPath] = basePath;\n }\n }\n\n editLength++;\n } // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced.\n\n\n if (callback) {\n (function exec() {\n setTimeout(function () {\n // This should not happen, but we want to be safe.\n\n /* istanbul ignore next */\n if (editLength > maxEditLength) {\n return callback();\n }\n\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n })();\n } else {\n while (editLength <= maxEditLength) {\n var ret = execEditLength();\n\n if (ret) {\n return ret;\n }\n }\n }\n },\n pushComponent: function pushComponent(components, added, removed) {\n var last = components[components.length - 1];\n\n if (last && last.added === added && last.removed === removed) {\n // We need to clone here as the component clone operation is just\n // as shallow array clone\n components[components.length - 1] = {\n count: last.count + 1,\n added: added,\n removed: removed\n };\n } else {\n components.push({\n count: 1,\n added: added,\n removed: removed\n });\n }\n },\n extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {\n var newLen = newString.length,\n oldLen = oldString.length,\n newPos = basePath.newPos,\n oldPos = newPos - diagonalPath,\n commonCount = 0;\n\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {\n newPos++;\n oldPos++;\n commonCount++;\n }\n\n if (commonCount) {\n basePath.components.push({\n count: commonCount\n });\n }\n\n basePath.newPos = newPos;\n return oldPos;\n },\n equals: function equals(left, right) {\n if (this.options.comparator) {\n return this.options.comparator(left, right);\n } else {\n return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();\n }\n },\n removeEmpty: function removeEmpty(array) {\n var ret = [];\n\n for (var i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n\n return ret;\n },\n castInput: function castInput(value) {\n return value;\n },\n tokenize: function tokenize(value) {\n return value.split('');\n },\n join: function join(chars) {\n return chars.join('');\n }\n };\n\n function buildValues(diff, components, newString, oldString, useLongestToken) {\n var componentPos = 0,\n componentLen = components.length,\n newPos = 0,\n oldPos = 0;\n\n for (; componentPos < componentLen; componentPos++) {\n var component = components[componentPos];\n\n if (!component.removed) {\n if (!component.added && useLongestToken) {\n var value = newString.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n var oldValue = oldString[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = diff.join(value);\n } else {\n component.value = diff.join(newString.slice(newPos, newPos + component.count));\n }\n\n newPos += component.count; // Common case\n\n if (!component.added) {\n oldPos += component.count;\n }\n } else {\n component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));\n oldPos += component.count; // Reverse add and remove so removes are output first to match common convention\n // The diffing algorithm is tied to add then remove output and this is the simplest\n // route to get the desired output with minimal overhead.\n\n if (componentPos && components[componentPos - 1].added) {\n var tmp = components[componentPos - 1];\n components[componentPos - 1] = components[componentPos];\n components[componentPos] = tmp;\n }\n }\n } // Special case handle for when one terminal is ignored (i.e. whitespace).\n // For this case we merge the terminal into the prior string and drop the change.\n // This is only available for string mode.\n\n\n var lastComponent = components[componentLen - 1];\n\n if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {\n components[componentLen - 2].value += lastComponent.value;\n components.pop();\n }\n\n return components;\n }\n\n function clonePath(path) {\n return {\n newPos: path.newPos,\n components: path.components.slice(0)\n };\n }\n\n var characterDiff = new Diff();\n function diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n }\n\n function generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n } else if (options) {\n for (var name in options) {\n /* istanbul ignore else */\n if (options.hasOwnProperty(name)) {\n defaults[name] = options[name];\n }\n }\n }\n\n return defaults;\n }\n\n //\n // Ranges and exceptions:\n // Latin-1 Supplement, 0080–00FF\n // - U+00D7 × Multiplication sign\n // - U+00F7 ÷ Division sign\n // Latin Extended-A, 0100–017F\n // Latin Extended-B, 0180–024F\n // IPA Extensions, 0250–02AF\n // Spacing Modifier Letters, 02B0–02FF\n // - U+02C7 ˇ ˇ Caron\n // - U+02D8 ˘ ˘ Breve\n // - U+02D9 ˙ ˙ Dot Above\n // - U+02DA ˚ ˚ Ring Above\n // - U+02DB ˛ ˛ Ogonek\n // - U+02DC ˜ ˜ Small Tilde\n // - U+02DD ˝ ˝ Double Acute Accent\n // Latin Extended Additional, 1E00–1EFF\n\n var extendedWordChars = /^[A-Za-z\\xC0-\\u02C6\\u02C8-\\u02D7\\u02DE-\\u02FF\\u1E00-\\u1EFF]+$/;\n var reWhitespace = /\\S/;\n var wordDiff = new Diff();\n\n wordDiff.equals = function (left, right) {\n if (this.options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n\n return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);\n };\n\n wordDiff.tokenize = function (value) {\n // All whitespace symbols except newline group into one token, each newline - in separate token\n var tokens = value.split(/([^\\S\\r\\n]+|[()[\\]{}'\"\\r\\n]|\\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.\n\n for (var i = 0; i < tokens.length - 1; i++) {\n // If we have an empty string in the next field and we have only word chars before and after, merge\n if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {\n tokens[i] += tokens[i + 2];\n tokens.splice(i + 1, 2);\n i--;\n }\n }\n\n return tokens;\n };\n\n function diffWords(oldStr, newStr, options) {\n options = generateOptions(options, {\n ignoreWhitespace: true\n });\n return wordDiff.diff(oldStr, newStr, options);\n }\n function diffWordsWithSpace(oldStr, newStr, options) {\n return wordDiff.diff(oldStr, newStr, options);\n }\n\n var lineDiff = new Diff();\n\n lineDiff.tokenize = function (value) {\n var retLines = [],\n linesAndNewlines = value.split(/(\\n|\\r\\n)/); // Ignore the final empty token that occurs if the string ends with a new line\n\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n } // Merge the content and line separators into single tokens\n\n\n for (var i = 0; i < linesAndNewlines.length; i++) {\n var line = linesAndNewlines[i];\n\n if (i % 2 && !this.options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n } else {\n if (this.options.ignoreWhitespace) {\n line = line.trim();\n }\n\n retLines.push(line);\n }\n }\n\n return retLines;\n };\n\n function diffLines(oldStr, newStr, callback) {\n return lineDiff.diff(oldStr, newStr, callback);\n }\n function diffTrimmedLines(oldStr, newStr, callback) {\n var options = generateOptions(callback, {\n ignoreWhitespace: true\n });\n return lineDiff.diff(oldStr, newStr, options);\n }\n\n var sentenceDiff = new Diff();\n\n sentenceDiff.tokenize = function (value) {\n return value.split(/(\\S.+?[.!?])(?=\\s+|$)/);\n };\n\n function diffSentences(oldStr, newStr, callback) {\n return sentenceDiff.diff(oldStr, newStr, callback);\n }\n\n var cssDiff = new Diff();\n\n cssDiff.tokenize = function (value) {\n return value.split(/([{}:;,]|\\s+)/);\n };\n\n function diffCss(oldStr, newStr, callback) {\n return cssDiff.diff(oldStr, newStr, callback);\n }\n\n function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n }\n\n function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n }\n\n function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n }\n\n function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n\n function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n var objectPrototypeToString = Object.prototype.toString;\n var jsonDiff = new Diff(); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\n\n jsonDiff.useLongestToken = true;\n jsonDiff.tokenize = lineDiff.tokenize;\n\n jsonDiff.castInput = function (value) {\n var _this$options = this.options,\n undefinedReplacement = _this$options.undefinedReplacement,\n _this$options$stringi = _this$options.stringifyReplacer,\n stringifyReplacer = _this$options$stringi === void 0 ? function (k, v) {\n return typeof v === 'undefined' ? undefinedReplacement : v;\n } : _this$options$stringi;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');\n };\n\n jsonDiff.equals = function (left, right) {\n return Diff.prototype.equals.call(jsonDiff, left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'));\n };\n\n function diffJson(oldObj, newObj, options) {\n return jsonDiff.diff(oldObj, newObj, options);\n } // This function handles the presence of circular references by bailing out when encountering an\n // object that is already on the \"stack\" of items being processed. Accepts an optional replacer\n\n function canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n\n if (replacer) {\n obj = replacer(key, obj);\n }\n\n var i;\n\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n\n var canonicalizedObj;\n\n if ('[object Array]' === objectPrototypeToString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);\n }\n\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n\n if (_typeof(obj) === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n\n var sortedKeys = [],\n _key;\n\n for (_key in obj) {\n /* istanbul ignore else */\n if (obj.hasOwnProperty(_key)) {\n sortedKeys.push(_key);\n }\n }\n\n sortedKeys.sort();\n\n for (i = 0; i < sortedKeys.length; i += 1) {\n _key = sortedKeys[i];\n canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);\n }\n\n stack.pop();\n replacementStack.pop();\n } else {\n canonicalizedObj = obj;\n }\n\n return canonicalizedObj;\n }\n\n var arrayDiff = new Diff();\n\n arrayDiff.tokenize = function (value) {\n return value.slice();\n };\n\n arrayDiff.join = arrayDiff.removeEmpty = function (value) {\n return value;\n };\n\n function diffArrays(oldArr, newArr, callback) {\n return arrayDiff.diff(oldArr, newArr, callback);\n }\n\n function parsePatch(uniDiff) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var diffstr = uniDiff.split(/\\r\\n|[\\n\\v\\f\\r\\x85]/),\n delimiters = uniDiff.match(/\\r\\n|[\\n\\v\\f\\r\\x85]/g) || [],\n list = [],\n i = 0;\n\n function parseIndex() {\n var index = {};\n list.push(index); // Parse diff metadata\n\n while (i < diffstr.length) {\n var line = diffstr[i]; // File header found, end parsing diff metadata\n\n if (/^(\\-\\-\\-|\\+\\+\\+|@@)\\s/.test(line)) {\n break;\n } // Diff index\n\n\n var header = /^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/.exec(line);\n\n if (header) {\n index.index = header[1];\n }\n\n i++;\n } // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n\n\n parseFileHeader(index);\n parseFileHeader(index); // Parse hunks\n\n index.hunks = [];\n\n while (i < diffstr.length) {\n var _line = diffstr[i];\n\n if (/^(Index:|diff|\\-\\-\\-|\\+\\+\\+)\\s/.test(_line)) {\n break;\n } else if (/^@@/.test(_line)) {\n index.hunks.push(parseHunk());\n } else if (_line && options.strict) {\n // Ignore unexpected content unless in strict mode\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));\n } else {\n i++;\n }\n }\n } // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n\n\n function parseFileHeader(index) {\n var fileHeader = /^(---|\\+\\+\\+)\\s+(.*)$/.exec(diffstr[i]);\n\n if (fileHeader) {\n var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';\n var data = fileHeader[2].split('\\t', 2);\n var fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n\n if (/^\".*\"$/.test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n\n index[keyPrefix + 'FileName'] = fileName;\n index[keyPrefix + 'Header'] = (data[1] || '').trim();\n i++;\n }\n } // Parses a hunk\n // This assumes that we are at the start of a hunk.\n\n\n function parseHunk() {\n var chunkHeaderIndex = i,\n chunkHeaderLine = diffstr[i++],\n chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n var hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: [],\n linedelimiters: []\n }; // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n\n var addCount = 0,\n removeCount = 0;\n\n for (; i < diffstr.length; i++) {\n // Lines starting with '---' could be mistaken for the \"remove line\" operation\n // But they could be the header for the next file. Therefore prune such cases out.\n if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {\n break;\n }\n\n var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];\n\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n hunk.linedelimiters.push(delimiters[i] || '\\n');\n\n if (operation === '+') {\n addCount++;\n } else if (operation === '-') {\n removeCount++;\n } else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n } else {\n break;\n }\n } // Handle the empty block count case\n\n\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n } // Perform optional sanity checking\n\n\n if (options.strict) {\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n }\n\n return hunk;\n }\n\n while (i < diffstr.length) {\n parseIndex();\n }\n\n return list;\n }\n\n // Iterator that traverses in the range of [min, max], stepping\n // by distance from a given start position. I.e. for [0, 4], with\n // start of 2, this will iterate 2, 3, 1, 4, 0.\n function distanceIterator (start, minLine, maxLine) {\n var wantForward = true,\n backwardExhausted = false,\n forwardExhausted = false,\n localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n } else {\n wantForward = false;\n } // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n\n\n if (start + localOffset <= maxLine) {\n return localOffset;\n }\n\n forwardExhausted = true;\n }\n\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n } // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n\n\n if (minLine <= start - localOffset) {\n return -localOffset++;\n }\n\n backwardExhausted = true;\n return iterator();\n } // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n\n };\n }\n\n function applyPatch(source, uniDiff) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n\n if (Array.isArray(uniDiff)) {\n if (uniDiff.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n\n uniDiff = uniDiff[0];\n } // Apply the diff to the input\n\n\n var lines = source.split(/\\r\\n|[\\n\\v\\f\\r\\x85]/),\n delimiters = source.match(/\\r\\n|[\\n\\v\\f\\r\\x85]/g) || [],\n hunks = uniDiff.hunks,\n compareLine = options.compareLine || function (lineNumber, line, operation, patchContent) {\n return line === patchContent;\n },\n errorCount = 0,\n fuzzFactor = options.fuzzFactor || 0,\n minLine = 0,\n offset = 0,\n removeEOFNL,\n addEOFNL;\n /**\n * Checks if the hunk exactly fits on the provided location\n */\n\n\n function hunkFits(hunk, toPos) {\n for (var j = 0; j < hunk.lines.length; j++) {\n var line = hunk.lines[j],\n operation = line.length > 0 ? line[0] : ' ',\n content = line.length > 0 ? line.substr(1) : line;\n\n if (operation === ' ' || operation === '-') {\n // Context sanity check\n if (!compareLine(toPos + 1, lines[toPos], operation, content)) {\n errorCount++;\n\n if (errorCount > fuzzFactor) {\n return false;\n }\n }\n\n toPos++;\n }\n }\n\n return true;\n } // Search best fit offsets for each hunk based on the previous ones\n\n\n for (var i = 0; i < hunks.length; i++) {\n var hunk = hunks[i],\n maxLine = lines.length - hunk.oldLines,\n localOffset = 0,\n toPos = offset + hunk.oldStart - 1;\n var iterator = distanceIterator(toPos, minLine, maxLine);\n\n for (; localOffset !== undefined; localOffset = iterator()) {\n if (hunkFits(hunk, toPos + localOffset)) {\n hunk.offset = offset += localOffset;\n break;\n }\n }\n\n if (localOffset === undefined) {\n return false;\n } // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n\n\n minLine = hunk.offset + hunk.oldStart + hunk.oldLines;\n } // Apply patch hunks\n\n\n var diffOffset = 0;\n\n for (var _i = 0; _i < hunks.length; _i++) {\n var _hunk = hunks[_i],\n _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;\n\n diffOffset += _hunk.newLines - _hunk.oldLines;\n\n for (var j = 0; j < _hunk.lines.length; j++) {\n var line = _hunk.lines[j],\n operation = line.length > 0 ? line[0] : ' ',\n content = line.length > 0 ? line.substr(1) : line,\n delimiter = _hunk.linedelimiters[j];\n\n if (operation === ' ') {\n _toPos++;\n } else if (operation === '-') {\n lines.splice(_toPos, 1);\n delimiters.splice(_toPos, 1);\n /* istanbul ignore else */\n } else if (operation === '+') {\n lines.splice(_toPos, 0, content);\n delimiters.splice(_toPos, 0, delimiter);\n _toPos++;\n } else if (operation === '\\\\') {\n var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;\n\n if (previousOperation === '+') {\n removeEOFNL = true;\n } else if (previousOperation === '-') {\n addEOFNL = true;\n }\n }\n }\n } // Handle EOFNL insertion/removal\n\n\n if (removeEOFNL) {\n while (!lines[lines.length - 1]) {\n lines.pop();\n delimiters.pop();\n }\n } else if (addEOFNL) {\n lines.push('');\n delimiters.push('\\n');\n }\n\n for (var _k = 0; _k < lines.length - 1; _k++) {\n lines[_k] = lines[_k] + delimiters[_k];\n }\n\n return lines.join('');\n } // Wrapper that supports multiple file patches via callbacks.\n\n function applyPatches(uniDiff, options) {\n if (typeof uniDiff === 'string') {\n uniDiff = parsePatch(uniDiff);\n }\n\n var currentIndex = 0;\n\n function processIndex() {\n var index = uniDiff[currentIndex++];\n\n if (!index) {\n return options.complete();\n }\n\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n\n var updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n\n processIndex();\n });\n });\n }\n\n processIndex();\n }\n\n function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (!options) {\n options = {};\n }\n\n if (typeof options.context === 'undefined') {\n options.context = 4;\n }\n\n var diff = diffLines(oldStr, newStr, options);\n diff.push({\n value: '',\n lines: []\n }); // Append an empty value to make cleanup easier\n\n function contextLines(lines) {\n return lines.map(function (entry) {\n return ' ' + entry;\n });\n }\n\n var hunks = [];\n var oldRangeStart = 0,\n newRangeStart = 0,\n curRange = [],\n oldLine = 1,\n newLine = 1;\n\n var _loop = function _loop(i) {\n var current = diff[i],\n lines = current.lines || current.value.replace(/\\n$/, '').split('\\n');\n current.lines = lines;\n\n if (current.added || current.removed) {\n var _curRange;\n\n // If we have previous context, start with that\n if (!oldRangeStart) {\n var prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n\n if (prev) {\n curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n } // Output our changes\n\n\n (_curRange = curRange).push.apply(_curRange, _toConsumableArray(lines.map(function (entry) {\n return (current.added ? '+' : '-') + entry;\n }))); // Track the updated file position\n\n\n if (current.added) {\n newLine += lines.length;\n } else {\n oldLine += lines.length;\n }\n } else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= options.context * 2 && i < diff.length - 2) {\n var _curRange2;\n\n // Overlapping\n (_curRange2 = curRange).push.apply(_curRange2, _toConsumableArray(contextLines(lines)));\n } else {\n var _curRange3;\n\n // end the range and output\n var contextSize = Math.min(lines.length, options.context);\n\n (_curRange3 = curRange).push.apply(_curRange3, _toConsumableArray(contextLines(lines.slice(0, contextSize))));\n\n var hunk = {\n oldStart: oldRangeStart,\n oldLines: oldLine - oldRangeStart + contextSize,\n newStart: newRangeStart,\n newLines: newLine - newRangeStart + contextSize,\n lines: curRange\n };\n\n if (i >= diff.length - 2 && lines.length <= options.context) {\n // EOF is inside this hunk\n var oldEOFNewline = /\\n$/.test(oldStr);\n var newEOFNewline = /\\n$/.test(newStr);\n var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;\n\n if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {\n // special case: old has no eol and no trailing context; no-nl can end up before adds\n // however, if the old file is empty, do not output the no-nl line\n curRange.splice(hunk.oldLines, 0, '\\\\ No newline at end of file');\n }\n\n if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {\n curRange.push('\\\\ No newline at end of file');\n }\n }\n\n hunks.push(hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n\n oldLine += lines.length;\n newLine += lines.length;\n }\n };\n\n for (var i = 0; i < diff.length; i++) {\n _loop(i);\n }\n\n return {\n oldFileName: oldFileName,\n newFileName: newFileName,\n oldHeader: oldHeader,\n newHeader: newHeader,\n hunks: hunks\n };\n }\n function formatPatch(diff) {\n var ret = [];\n\n if (diff.oldFileName == diff.newFileName) {\n ret.push('Index: ' + diff.oldFileName);\n }\n\n ret.push('===================================================================');\n ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\\t' + diff.oldHeader));\n ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\\t' + diff.newHeader));\n\n for (var i = 0; i < diff.hunks.length; i++) {\n var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');\n ret.push.apply(ret, hunk.lines);\n }\n\n return ret.join('\\n') + '\\n';\n }\n function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));\n }\n function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n }\n\n function arrayEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n\n return arrayStartsWith(a, b);\n }\n function arrayStartsWith(array, start) {\n if (start.length > array.length) {\n return false;\n }\n\n for (var i = 0; i < start.length; i++) {\n if (start[i] !== array[i]) {\n return false;\n }\n }\n\n return true;\n }\n\n function calcLineCount(hunk) {\n var _calcOldNewLineCount = calcOldNewLineCount(hunk.lines),\n oldLines = _calcOldNewLineCount.oldLines,\n newLines = _calcOldNewLineCount.newLines;\n\n if (oldLines !== undefined) {\n hunk.oldLines = oldLines;\n } else {\n delete hunk.oldLines;\n }\n\n if (newLines !== undefined) {\n hunk.newLines = newLines;\n } else {\n delete hunk.newLines;\n }\n }\n function merge(mine, theirs, base) {\n mine = loadPatch(mine, base);\n theirs = loadPatch(theirs, base);\n var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.\n // Leaving sanity checks on this to the API consumer that may know more about the\n // meaning in their own context.\n\n if (mine.index || theirs.index) {\n ret.index = mine.index || theirs.index;\n }\n\n if (mine.newFileName || theirs.newFileName) {\n if (!fileNameChanged(mine)) {\n // No header or no change in ours, use theirs (and ours if theirs does not exist)\n ret.oldFileName = theirs.oldFileName || mine.oldFileName;\n ret.newFileName = theirs.newFileName || mine.newFileName;\n ret.oldHeader = theirs.oldHeader || mine.oldHeader;\n ret.newHeader = theirs.newHeader || mine.newHeader;\n } else if (!fileNameChanged(theirs)) {\n // No header or no change in theirs, use ours\n ret.oldFileName = mine.oldFileName;\n ret.newFileName = mine.newFileName;\n ret.oldHeader = mine.oldHeader;\n ret.newHeader = mine.newHeader;\n } else {\n // Both changed... figure it out\n ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);\n ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);\n ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);\n ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);\n }\n }\n\n ret.hunks = [];\n var mineIndex = 0,\n theirsIndex = 0,\n mineOffset = 0,\n theirsOffset = 0;\n\n while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {\n var mineCurrent = mine.hunks[mineIndex] || {\n oldStart: Infinity\n },\n theirsCurrent = theirs.hunks[theirsIndex] || {\n oldStart: Infinity\n };\n\n if (hunkBefore(mineCurrent, theirsCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(mineCurrent, mineOffset));\n mineIndex++;\n theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;\n } else if (hunkBefore(theirsCurrent, mineCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));\n theirsIndex++;\n mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;\n } else {\n // Overlap, merge as best we can\n var mergedHunk = {\n oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),\n oldLines: 0,\n newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),\n newLines: 0,\n lines: []\n };\n mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);\n theirsIndex++;\n mineIndex++;\n ret.hunks.push(mergedHunk);\n }\n }\n\n return ret;\n }\n\n function loadPatch(param, base) {\n if (typeof param === 'string') {\n if (/^@@/m.test(param) || /^Index:/m.test(param)) {\n return parsePatch(param)[0];\n }\n\n if (!base) {\n throw new Error('Must provide a base reference or pass in a patch');\n }\n\n return structuredPatch(undefined, undefined, base, param);\n }\n\n return param;\n }\n\n function fileNameChanged(patch) {\n return patch.newFileName && patch.newFileName !== patch.oldFileName;\n }\n\n function selectField(index, mine, theirs) {\n if (mine === theirs) {\n return mine;\n } else {\n index.conflict = true;\n return {\n mine: mine,\n theirs: theirs\n };\n }\n }\n\n function hunkBefore(test, check) {\n return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;\n }\n\n function cloneHunk(hunk, offset) {\n return {\n oldStart: hunk.oldStart,\n oldLines: hunk.oldLines,\n newStart: hunk.newStart + offset,\n newLines: hunk.newLines,\n lines: hunk.lines\n };\n }\n\n function mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {\n // This will generally result in a conflicted hunk, but there are cases where the context\n // is the only overlap where we can successfully merge the content here.\n var mine = {\n offset: mineOffset,\n lines: mineLines,\n index: 0\n },\n their = {\n offset: theirOffset,\n lines: theirLines,\n index: 0\n }; // Handle any leading content\n\n insertLeading(hunk, mine, their);\n insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.\n\n while (mine.index < mine.lines.length && their.index < their.lines.length) {\n var mineCurrent = mine.lines[mine.index],\n theirCurrent = their.lines[their.index];\n\n if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {\n // Both modified ...\n mutualChange(hunk, mine, their);\n } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {\n var _hunk$lines;\n\n // Mine inserted\n (_hunk$lines = hunk.lines).push.apply(_hunk$lines, _toConsumableArray(collectChange(mine)));\n } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {\n var _hunk$lines2;\n\n // Theirs inserted\n (_hunk$lines2 = hunk.lines).push.apply(_hunk$lines2, _toConsumableArray(collectChange(their)));\n } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {\n // Mine removed or edited\n removal(hunk, mine, their);\n } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {\n // Their removed or edited\n removal(hunk, their, mine, true);\n } else if (mineCurrent === theirCurrent) {\n // Context identity\n hunk.lines.push(mineCurrent);\n mine.index++;\n their.index++;\n } else {\n // Context mismatch\n conflict(hunk, collectChange(mine), collectChange(their));\n }\n } // Now push anything that may be remaining\n\n\n insertTrailing(hunk, mine);\n insertTrailing(hunk, their);\n calcLineCount(hunk);\n }\n\n function mutualChange(hunk, mine, their) {\n var myChanges = collectChange(mine),\n theirChanges = collectChange(their);\n\n if (allRemoves(myChanges) && allRemoves(theirChanges)) {\n // Special case for remove changes that are supersets of one another\n if (arrayStartsWith(myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {\n var _hunk$lines3;\n\n (_hunk$lines3 = hunk.lines).push.apply(_hunk$lines3, _toConsumableArray(myChanges));\n\n return;\n } else if (arrayStartsWith(theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {\n var _hunk$lines4;\n\n (_hunk$lines4 = hunk.lines).push.apply(_hunk$lines4, _toConsumableArray(theirChanges));\n\n return;\n }\n } else if (arrayEqual(myChanges, theirChanges)) {\n var _hunk$lines5;\n\n (_hunk$lines5 = hunk.lines).push.apply(_hunk$lines5, _toConsumableArray(myChanges));\n\n return;\n }\n\n conflict(hunk, myChanges, theirChanges);\n }\n\n function removal(hunk, mine, their, swap) {\n var myChanges = collectChange(mine),\n theirChanges = collectContext(their, myChanges);\n\n if (theirChanges.merged) {\n var _hunk$lines6;\n\n (_hunk$lines6 = hunk.lines).push.apply(_hunk$lines6, _toConsumableArray(theirChanges.merged));\n } else {\n conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);\n }\n }\n\n function conflict(hunk, mine, their) {\n hunk.conflict = true;\n hunk.lines.push({\n conflict: true,\n mine: mine,\n theirs: their\n });\n }\n\n function insertLeading(hunk, insert, their) {\n while (insert.offset < their.offset && insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n insert.offset++;\n }\n }\n\n function insertTrailing(hunk, insert) {\n while (insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n }\n }\n\n function collectChange(state) {\n var ret = [],\n operation = state.lines[state.index][0];\n\n while (state.index < state.lines.length) {\n var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one \"atomic\" modify change.\n\n if (operation === '-' && line[0] === '+') {\n operation = '+';\n }\n\n if (operation === line[0]) {\n ret.push(line);\n state.index++;\n } else {\n break;\n }\n }\n\n return ret;\n }\n\n function collectContext(state, matchChanges) {\n var changes = [],\n merged = [],\n matchIndex = 0,\n contextChanges = false,\n conflicted = false;\n\n while (matchIndex < matchChanges.length && state.index < state.lines.length) {\n var change = state.lines[state.index],\n match = matchChanges[matchIndex]; // Once we've hit our add, then we are done\n\n if (match[0] === '+') {\n break;\n }\n\n contextChanges = contextChanges || change[0] !== ' ';\n merged.push(match);\n matchIndex++; // Consume any additions in the other block as a conflict to attempt\n // to pull in the remaining context after this\n\n if (change[0] === '+') {\n conflicted = true;\n\n while (change[0] === '+') {\n changes.push(change);\n change = state.lines[++state.index];\n }\n }\n\n if (match.substr(1) === change.substr(1)) {\n changes.push(change);\n state.index++;\n } else {\n conflicted = true;\n }\n }\n\n if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {\n conflicted = true;\n }\n\n if (conflicted) {\n return changes;\n }\n\n while (matchIndex < matchChanges.length) {\n merged.push(matchChanges[matchIndex++]);\n }\n\n return {\n merged: merged,\n changes: changes\n };\n }\n\n function allRemoves(changes) {\n return changes.reduce(function (prev, change) {\n return prev && change[0] === '-';\n }, true);\n }\n\n function skipRemoveSuperset(state, removeChanges, delta) {\n for (var i = 0; i < delta; i++) {\n var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);\n\n if (state.lines[state.index + i] !== ' ' + changeContent) {\n return false;\n }\n }\n\n state.index += delta;\n return true;\n }\n\n function calcOldNewLineCount(lines) {\n var oldLines = 0;\n var newLines = 0;\n lines.forEach(function (line) {\n if (typeof line !== 'string') {\n var myCount = calcOldNewLineCount(line.mine);\n var theirCount = calcOldNewLineCount(line.theirs);\n\n if (oldLines !== undefined) {\n if (myCount.oldLines === theirCount.oldLines) {\n oldLines += myCount.oldLines;\n } else {\n oldLines = undefined;\n }\n }\n\n if (newLines !== undefined) {\n if (myCount.newLines === theirCount.newLines) {\n newLines += myCount.newLines;\n } else {\n newLines = undefined;\n }\n }\n } else {\n if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {\n newLines++;\n }\n\n if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {\n oldLines++;\n }\n }\n });\n return {\n oldLines: oldLines,\n newLines: newLines\n };\n }\n\n // See: http://code.google.com/p/google-diff-match-patch/wiki/API\n function convertChangesToDMP(changes) {\n var ret = [],\n change,\n operation;\n\n for (var i = 0; i < changes.length; i++) {\n change = changes[i];\n\n if (change.added) {\n operation = 1;\n } else if (change.removed) {\n operation = -1;\n } else {\n operation = 0;\n }\n\n ret.push([operation, change.value]);\n }\n\n return ret;\n }\n\n function convertChangesToXML(changes) {\n var ret = [];\n\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n\n ret.push(escapeHTML(change.value));\n\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n }\n\n return ret.join('');\n }\n\n function escapeHTML(s) {\n var n = s;\n n = n.replace(/&/g, '&');\n n = n.replace(//g, '>');\n n = n.replace(/\"/g, '"');\n return n;\n }\n\n exports.Diff = Diff;\n exports.applyPatch = applyPatch;\n exports.applyPatches = applyPatches;\n exports.canonicalize = canonicalize;\n exports.convertChangesToDMP = convertChangesToDMP;\n exports.convertChangesToXML = convertChangesToXML;\n exports.createPatch = createPatch;\n exports.createTwoFilesPatch = createTwoFilesPatch;\n exports.diffArrays = diffArrays;\n exports.diffChars = diffChars;\n exports.diffCss = diffCss;\n exports.diffJson = diffJson;\n exports.diffLines = diffLines;\n exports.diffSentences = diffSentences;\n exports.diffTrimmedLines = diffTrimmedLines;\n exports.diffWords = diffWords;\n exports.diffWordsWithSpace = diffWordsWithSpace;\n exports.merge = merge;\n exports.parsePatch = parsePatch;\n exports.structuredPatch = structuredPatch;\n\n Object.defineProperty(exports, '__esModule', { value: true });\n\n})));\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","var fails = require('../internals/fails');\n\nmodule.exports = !fails(function () {\n return Object.isExtensible(Object.preventExtensions({}));\n});\n","var hiddenKeys = require('../internals/hidden-keys');\nvar isObject = require('../internals/is-object');\nvar has = require('../internals/has');\nvar defineProperty = require('../internals/object-define-property').f;\nvar uid = require('../internals/uid');\nvar FREEZING = require('../internals/freezing');\n\nvar METADATA = uid('meta');\nvar id = 0;\n\nvar isExtensible = Object.isExtensible || function () {\n return true;\n};\n\nvar setMetadata = function (it) {\n defineProperty(it, METADATA, { value: {\n objectID: 'O' + ++id, // object ID\n weakData: {} // weak collections IDs\n } });\n};\n\nvar fastKey = function (it, create) {\n // return a primitive with prefix\n if (!isObject(it)) return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;\n if (!has(it, METADATA)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return 'F';\n // not necessary to add metadata\n if (!create) return 'E';\n // add missing metadata\n setMetadata(it);\n // return object ID\n } return it[METADATA].objectID;\n};\n\nvar getWeakData = function (it, create) {\n if (!has(it, METADATA)) {\n // can't set metadata to uncaught frozen object\n if (!isExtensible(it)) return true;\n // not necessary to add metadata\n if (!create) return false;\n // add missing metadata\n setMetadata(it);\n // return the store of weak collections IDs\n } return it[METADATA].weakData;\n};\n\n// add metadata on freeze-family methods calling\nvar onFreeze = function (it) {\n if (FREEZING && meta.REQUIRED && isExtensible(it) && !has(it, METADATA)) setMetadata(it);\n return it;\n};\n\nvar meta = module.exports = {\n REQUIRED: false,\n fastKey: fastKey,\n getWeakData: getWeakData,\n onFreeze: onFreeze\n};\n\nhiddenKeys[METADATA] = true;\n","var $ = require('../internals/export');\nvar FREEZING = require('../internals/freezing');\nvar fails = require('../internals/fails');\nvar isObject = require('../internals/is-object');\nvar onFreeze = require('../internals/internal-metadata').onFreeze;\n\nvar nativeFreeze = Object.freeze;\nvar FAILS_ON_PRIMITIVES = fails(function () { nativeFreeze(1); });\n\n// `Object.freeze` method\n// https://tc39.es/ecma262/#sec-object.freeze\n$({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES, sham: !FREEZING }, {\n freeze: function freeze(it) {\n return nativeFreeze && isObject(it) ? nativeFreeze(onFreeze(it)) : it;\n }\n});\n","'use strict';\nvar $ = require('../internals/export');\nvar global = require('../internals/global');\nvar isForced = require('../internals/is-forced');\nvar redefine = require('../internals/redefine');\nvar InternalMetadataModule = require('../internals/internal-metadata');\nvar iterate = require('../internals/iterate');\nvar anInstance = require('../internals/an-instance');\nvar isObject = require('../internals/is-object');\nvar fails = require('../internals/fails');\nvar checkCorrectnessOfIteration = require('../internals/check-correctness-of-iteration');\nvar setToStringTag = require('../internals/set-to-string-tag');\nvar inheritIfRequired = require('../internals/inherit-if-required');\n\nmodule.exports = function (CONSTRUCTOR_NAME, wrapper, common) {\n var IS_MAP = CONSTRUCTOR_NAME.indexOf('Map') !== -1;\n var IS_WEAK = CONSTRUCTOR_NAME.indexOf('Weak') !== -1;\n var ADDER = IS_MAP ? 'set' : 'add';\n var NativeConstructor = global[CONSTRUCTOR_NAME];\n var NativePrototype = NativeConstructor && NativeConstructor.prototype;\n var Constructor = NativeConstructor;\n var exported = {};\n\n var fixMethod = function (KEY) {\n var nativeMethod = NativePrototype[KEY];\n redefine(NativePrototype, KEY,\n KEY == 'add' ? function add(value) {\n nativeMethod.call(this, value === 0 ? 0 : value);\n return this;\n } : KEY == 'delete' ? function (key) {\n return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);\n } : KEY == 'get' ? function get(key) {\n return IS_WEAK && !isObject(key) ? undefined : nativeMethod.call(this, key === 0 ? 0 : key);\n } : KEY == 'has' ? function has(key) {\n return IS_WEAK && !isObject(key) ? false : nativeMethod.call(this, key === 0 ? 0 : key);\n } : function set(key, value) {\n nativeMethod.call(this, key === 0 ? 0 : key, value);\n return this;\n }\n );\n };\n\n // eslint-disable-next-line max-len\n if (isForced(CONSTRUCTOR_NAME, typeof NativeConstructor != 'function' || !(IS_WEAK || NativePrototype.forEach && !fails(function () {\n new NativeConstructor().entries().next();\n })))) {\n // create collection constructor\n Constructor = common.getConstructor(wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER);\n InternalMetadataModule.REQUIRED = true;\n } else if (isForced(CONSTRUCTOR_NAME, true)) {\n var instance = new Constructor();\n // early implementations not supports chaining\n var HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance;\n // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false\n var THROWS_ON_PRIMITIVES = fails(function () { instance.has(1); });\n // most early implementations doesn't supports iterables, most modern - not close it correctly\n // eslint-disable-next-line no-new\n var ACCEPT_ITERABLES = checkCorrectnessOfIteration(function (iterable) { new NativeConstructor(iterable); });\n // for early implementations -0 and +0 not the same\n var BUGGY_ZERO = !IS_WEAK && fails(function () {\n // V8 ~ Chromium 42- fails only with 5+ elements\n var $instance = new NativeConstructor();\n var index = 5;\n while (index--) $instance[ADDER](index, index);\n return !$instance.has(-0);\n });\n\n if (!ACCEPT_ITERABLES) {\n Constructor = wrapper(function (dummy, iterable) {\n anInstance(dummy, Constructor, CONSTRUCTOR_NAME);\n var that = inheritIfRequired(new NativeConstructor(), dummy, Constructor);\n if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });\n return that;\n });\n Constructor.prototype = NativePrototype;\n NativePrototype.constructor = Constructor;\n }\n\n if (THROWS_ON_PRIMITIVES || BUGGY_ZERO) {\n fixMethod('delete');\n fixMethod('has');\n IS_MAP && fixMethod('get');\n }\n\n if (BUGGY_ZERO || HASNT_CHAINING) fixMethod(ADDER);\n\n // weak collections should not contains .clear method\n if (IS_WEAK && NativePrototype.clear) delete NativePrototype.clear;\n }\n\n exported[CONSTRUCTOR_NAME] = Constructor;\n $({ global: true, forced: Constructor != NativeConstructor }, exported);\n\n setToStringTag(Constructor, CONSTRUCTOR_NAME);\n\n if (!IS_WEAK) common.setStrong(Constructor, CONSTRUCTOR_NAME, IS_MAP);\n\n return Constructor;\n};\n","'use strict';\nvar defineProperty = require('../internals/object-define-property').f;\nvar create = require('../internals/object-create');\nvar redefineAll = require('../internals/redefine-all');\nvar bind = require('../internals/function-bind-context');\nvar anInstance = require('../internals/an-instance');\nvar iterate = require('../internals/iterate');\nvar defineIterator = require('../internals/define-iterator');\nvar setSpecies = require('../internals/set-species');\nvar DESCRIPTORS = require('../internals/descriptors');\nvar fastKey = require('../internals/internal-metadata').fastKey;\nvar InternalStateModule = require('../internals/internal-state');\n\nvar setInternalState = InternalStateModule.set;\nvar internalStateGetterFor = InternalStateModule.getterFor;\n\nmodule.exports = {\n getConstructor: function (wrapper, CONSTRUCTOR_NAME, IS_MAP, ADDER) {\n var C = wrapper(function (that, iterable) {\n anInstance(that, C, CONSTRUCTOR_NAME);\n setInternalState(that, {\n type: CONSTRUCTOR_NAME,\n index: create(null),\n first: undefined,\n last: undefined,\n size: 0\n });\n if (!DESCRIPTORS) that.size = 0;\n if (iterable != undefined) iterate(iterable, that[ADDER], { that: that, AS_ENTRIES: IS_MAP });\n });\n\n var getInternalState = internalStateGetterFor(CONSTRUCTOR_NAME);\n\n var define = function (that, key, value) {\n var state = getInternalState(that);\n var entry = getEntry(that, key);\n var previous, index;\n // change existing entry\n if (entry) {\n entry.value = value;\n // create new entry\n } else {\n state.last = entry = {\n index: index = fastKey(key, true),\n key: key,\n value: value,\n previous: previous = state.last,\n next: undefined,\n removed: false\n };\n if (!state.first) state.first = entry;\n if (previous) previous.next = entry;\n if (DESCRIPTORS) state.size++;\n else that.size++;\n // add to index\n if (index !== 'F') state.index[index] = entry;\n } return that;\n };\n\n var getEntry = function (that, key) {\n var state = getInternalState(that);\n // fast case\n var index = fastKey(key);\n var entry;\n if (index !== 'F') return state.index[index];\n // frozen object case\n for (entry = state.first; entry; entry = entry.next) {\n if (entry.key == key) return entry;\n }\n };\n\n redefineAll(C.prototype, {\n // 23.1.3.1 Map.prototype.clear()\n // 23.2.3.2 Set.prototype.clear()\n clear: function clear() {\n var that = this;\n var state = getInternalState(that);\n var data = state.index;\n var entry = state.first;\n while (entry) {\n entry.removed = true;\n if (entry.previous) entry.previous = entry.previous.next = undefined;\n delete data[entry.index];\n entry = entry.next;\n }\n state.first = state.last = undefined;\n if (DESCRIPTORS) state.size = 0;\n else that.size = 0;\n },\n // 23.1.3.3 Map.prototype.delete(key)\n // 23.2.3.4 Set.prototype.delete(value)\n 'delete': function (key) {\n var that = this;\n var state = getInternalState(that);\n var entry = getEntry(that, key);\n if (entry) {\n var next = entry.next;\n var prev = entry.previous;\n delete state.index[entry.index];\n entry.removed = true;\n if (prev) prev.next = next;\n if (next) next.previous = prev;\n if (state.first == entry) state.first = next;\n if (state.last == entry) state.last = prev;\n if (DESCRIPTORS) state.size--;\n else that.size--;\n } return !!entry;\n },\n // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)\n // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)\n forEach: function forEach(callbackfn /* , that = undefined */) {\n var state = getInternalState(this);\n var boundFunction = bind(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3);\n var entry;\n while (entry = entry ? entry.next : state.first) {\n boundFunction(entry.value, entry.key, this);\n // revert to the last existing entry\n while (entry && entry.removed) entry = entry.previous;\n }\n },\n // 23.1.3.7 Map.prototype.has(key)\n // 23.2.3.7 Set.prototype.has(value)\n has: function has(key) {\n return !!getEntry(this, key);\n }\n });\n\n redefineAll(C.prototype, IS_MAP ? {\n // 23.1.3.6 Map.prototype.get(key)\n get: function get(key) {\n var entry = getEntry(this, key);\n return entry && entry.value;\n },\n // 23.1.3.9 Map.prototype.set(key, value)\n set: function set(key, value) {\n return define(this, key === 0 ? 0 : key, value);\n }\n } : {\n // 23.2.3.1 Set.prototype.add(value)\n add: function add(value) {\n return define(this, value = value === 0 ? 0 : value, value);\n }\n });\n if (DESCRIPTORS) defineProperty(C.prototype, 'size', {\n get: function () {\n return getInternalState(this).size;\n }\n });\n return C;\n },\n setStrong: function (C, CONSTRUCTOR_NAME, IS_MAP) {\n var ITERATOR_NAME = CONSTRUCTOR_NAME + ' Iterator';\n var getInternalCollectionState = internalStateGetterFor(CONSTRUCTOR_NAME);\n var getInternalIteratorState = internalStateGetterFor(ITERATOR_NAME);\n // add .keys, .values, .entries, [@@iterator]\n // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11\n defineIterator(C, CONSTRUCTOR_NAME, function (iterated, kind) {\n setInternalState(this, {\n type: ITERATOR_NAME,\n target: iterated,\n state: getInternalCollectionState(iterated),\n kind: kind,\n last: undefined\n });\n }, function () {\n var state = getInternalIteratorState(this);\n var kind = state.kind;\n var entry = state.last;\n // revert to the last existing entry\n while (entry && entry.removed) entry = entry.previous;\n // get next entry\n if (!state.target || !(state.last = entry = entry ? entry.next : state.state.first)) {\n // or finish the iteration\n state.target = undefined;\n return { value: undefined, done: true };\n }\n // return step by kind\n if (kind == 'keys') return { value: entry.key, done: false };\n if (kind == 'values') return { value: entry.value, done: false };\n return { value: [entry.key, entry.value], done: false };\n }, IS_MAP ? 'entries' : 'values', !IS_MAP, true);\n\n // add [@@species], 23.1.2.2, 23.2.2.2\n setSpecies(CONSTRUCTOR_NAME);\n }\n};\n","'use strict';\nvar collection = require('../internals/collection');\nvar collectionStrong = require('../internals/collection-strong');\n\n// `Set` constructor\n// https://tc39.es/ecma262/#sec-set-objects\nmodule.exports = collection('Set', function (init) {\n return function Set() { return init(this, arguments.length ? arguments[0] : undefined); };\n}, collectionStrong);\n","export var browser = true;\n","// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet =\n 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'\n\nlet customAlphabet = (alphabet, size) => {\n return () => {\n let id = ''\n // A compact alternative for `for (var i = 0; i < step; i++)`.\n let i = size\n while (i--) {\n // `| 0` is more compact and faster than `Math.floor()`.\n id += alphabet[(Math.random() * alphabet.length) | 0]\n }\n return id\n }\n}\n\nlet nanoid = (size = 21) => {\n let id = ''\n // A compact alternative for `for (var i = 0; i < step; i++)`.\n let i = size\n while (i--) {\n // `| 0` is more compact and faster than `Math.floor()`.\n id += urlAlphabet[(Math.random() * 64) | 0]\n }\n return id\n}\n\nexport { nanoid, customAlphabet }\n","/*! https://mths.be/he v1.2.0 by @mathias | MIT license */\n;(function(root) {\n\n\t// Detect free variables `exports`.\n\tvar freeExports = typeof exports == 'object' && exports;\n\n\t// Detect free variable `module`.\n\tvar freeModule = typeof module == 'object' && module &&\n\t\tmodule.exports == freeExports && module;\n\n\t// Detect free variable `global`, from Node.js or Browserified code,\n\t// and use it as `root`.\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {\n\t\troot = freeGlobal;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t// All astral symbols.\n\tvar regexAstralSymbols = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n\t// All ASCII symbols (not just printable ASCII) except those listed in the\n\t// first column of the overrides table.\n\t// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides\n\tvar regexAsciiWhitelist = /[\\x01-\\x7F]/g;\n\t// All BMP symbols that are not ASCII newlines, printable ASCII symbols, or\n\t// code points listed in the first column of the overrides table on\n\t// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.\n\tvar regexBmpWhitelist = /[\\x01-\\t\\x0B\\f\\x0E-\\x1F\\x7F\\x81\\x8D\\x8F\\x90\\x9D\\xA0-\\uFFFF]/g;\n\n\tvar regexEncodeNonAscii = /<\\u20D2|=\\u20E5|>\\u20D2|\\u205F\\u200A|\\u219D\\u0338|\\u2202\\u0338|\\u2220\\u20D2|\\u2229\\uFE00|\\u222A\\uFE00|\\u223C\\u20D2|\\u223D\\u0331|\\u223E\\u0333|\\u2242\\u0338|\\u224B\\u0338|\\u224D\\u20D2|\\u224E\\u0338|\\u224F\\u0338|\\u2250\\u0338|\\u2261\\u20E5|\\u2264\\u20D2|\\u2265\\u20D2|\\u2266\\u0338|\\u2267\\u0338|\\u2268\\uFE00|\\u2269\\uFE00|\\u226A\\u0338|\\u226A\\u20D2|\\u226B\\u0338|\\u226B\\u20D2|\\u227F\\u0338|\\u2282\\u20D2|\\u2283\\u20D2|\\u228A\\uFE00|\\u228B\\uFE00|\\u228F\\u0338|\\u2290\\u0338|\\u2293\\uFE00|\\u2294\\uFE00|\\u22B4\\u20D2|\\u22B5\\u20D2|\\u22D8\\u0338|\\u22D9\\u0338|\\u22DA\\uFE00|\\u22DB\\uFE00|\\u22F5\\u0338|\\u22F9\\u0338|\\u2933\\u0338|\\u29CF\\u0338|\\u29D0\\u0338|\\u2A6D\\u0338|\\u2A70\\u0338|\\u2A7D\\u0338|\\u2A7E\\u0338|\\u2AA1\\u0338|\\u2AA2\\u0338|\\u2AAC\\uFE00|\\u2AAD\\uFE00|\\u2AAF\\u0338|\\u2AB0\\u0338|\\u2AC5\\u0338|\\u2AC6\\u0338|\\u2ACB\\uFE00|\\u2ACC\\uFE00|\\u2AFD\\u20E5|[\\xA0-\\u0113\\u0116-\\u0122\\u0124-\\u012B\\u012E-\\u014D\\u0150-\\u017E\\u0192\\u01B5\\u01F5\\u0237\\u02C6\\u02C7\\u02D8-\\u02DD\\u0311\\u0391-\\u03A1\\u03A3-\\u03A9\\u03B1-\\u03C9\\u03D1\\u03D2\\u03D5\\u03D6\\u03DC\\u03DD\\u03F0\\u03F1\\u03F5\\u03F6\\u0401-\\u040C\\u040E-\\u044F\\u0451-\\u045C\\u045E\\u045F\\u2002-\\u2005\\u2007-\\u2010\\u2013-\\u2016\\u2018-\\u201A\\u201C-\\u201E\\u2020-\\u2022\\u2025\\u2026\\u2030-\\u2035\\u2039\\u203A\\u203E\\u2041\\u2043\\u2044\\u204F\\u2057\\u205F-\\u2063\\u20AC\\u20DB\\u20DC\\u2102\\u2105\\u210A-\\u2113\\u2115-\\u211E\\u2122\\u2124\\u2127-\\u2129\\u212C\\u212D\\u212F-\\u2131\\u2133-\\u2138\\u2145-\\u2148\\u2153-\\u215E\\u2190-\\u219B\\u219D-\\u21A7\\u21A9-\\u21AE\\u21B0-\\u21B3\\u21B5-\\u21B7\\u21BA-\\u21DB\\u21DD\\u21E4\\u21E5\\u21F5\\u21FD-\\u2205\\u2207-\\u2209\\u220B\\u220C\\u220F-\\u2214\\u2216-\\u2218\\u221A\\u221D-\\u2238\\u223A-\\u2257\\u2259\\u225A\\u225C\\u225F-\\u2262\\u2264-\\u228B\\u228D-\\u229B\\u229D-\\u22A5\\u22A7-\\u22B0\\u22B2-\\u22BB\\u22BD-\\u22DB\\u22DE-\\u22E3\\u22E6-\\u22F7\\u22F9-\\u22FE\\u2305\\u2306\\u2308-\\u2310\\u2312\\u2313\\u2315\\u2316\\u231C-\\u231F\\u2322\\u2323\\u232D\\u232E\\u2336\\u233D\\u233F\\u237C\\u23B0\\u23B1\\u23B4-\\u23B6\\u23DC-\\u23DF\\u23E2\\u23E7\\u2423\\u24C8\\u2500\\u2502\\u250C\\u2510\\u2514\\u2518\\u251C\\u2524\\u252C\\u2534\\u253C\\u2550-\\u256C\\u2580\\u2584\\u2588\\u2591-\\u2593\\u25A1\\u25AA\\u25AB\\u25AD\\u25AE\\u25B1\\u25B3-\\u25B5\\u25B8\\u25B9\\u25BD-\\u25BF\\u25C2\\u25C3\\u25CA\\u25CB\\u25EC\\u25EF\\u25F8-\\u25FC\\u2605\\u2606\\u260E\\u2640\\u2642\\u2660\\u2663\\u2665\\u2666\\u266A\\u266D-\\u266F\\u2713\\u2717\\u2720\\u2736\\u2758\\u2772\\u2773\\u27C8\\u27C9\\u27E6-\\u27ED\\u27F5-\\u27FA\\u27FC\\u27FF\\u2902-\\u2905\\u290C-\\u2913\\u2916\\u2919-\\u2920\\u2923-\\u292A\\u2933\\u2935-\\u2939\\u293C\\u293D\\u2945\\u2948-\\u294B\\u294E-\\u2976\\u2978\\u2979\\u297B-\\u297F\\u2985\\u2986\\u298B-\\u2996\\u299A\\u299C\\u299D\\u29A4-\\u29B7\\u29B9\\u29BB\\u29BC\\u29BE-\\u29C5\\u29C9\\u29CD-\\u29D0\\u29DC-\\u29DE\\u29E3-\\u29E5\\u29EB\\u29F4\\u29F6\\u2A00-\\u2A02\\u2A04\\u2A06\\u2A0C\\u2A0D\\u2A10-\\u2A17\\u2A22-\\u2A27\\u2A29\\u2A2A\\u2A2D-\\u2A31\\u2A33-\\u2A3C\\u2A3F\\u2A40\\u2A42-\\u2A4D\\u2A50\\u2A53-\\u2A58\\u2A5A-\\u2A5D\\u2A5F\\u2A66\\u2A6A\\u2A6D-\\u2A75\\u2A77-\\u2A9A\\u2A9D-\\u2AA2\\u2AA4-\\u2AB0\\u2AB3-\\u2AC8\\u2ACB\\u2ACC\\u2ACF-\\u2ADB\\u2AE4\\u2AE6-\\u2AE9\\u2AEB-\\u2AF3\\u2AFD\\uFB00-\\uFB04]|\\uD835[\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDCCF\\uDD04\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDD6B]/g;\n\tvar encodeMap = {'\\xAD':'shy','\\u200C':'zwnj','\\u200D':'zwj','\\u200E':'lrm','\\u2063':'ic','\\u2062':'it','\\u2061':'af','\\u200F':'rlm','\\u200B':'ZeroWidthSpace','\\u2060':'NoBreak','\\u0311':'DownBreve','\\u20DB':'tdot','\\u20DC':'DotDot','\\t':'Tab','\\n':'NewLine','\\u2008':'puncsp','\\u205F':'MediumSpace','\\u2009':'thinsp','\\u200A':'hairsp','\\u2004':'emsp13','\\u2002':'ensp','\\u2005':'emsp14','\\u2003':'emsp','\\u2007':'numsp','\\xA0':'nbsp','\\u205F\\u200A':'ThickSpace','\\u203E':'oline','_':'lowbar','\\u2010':'dash','\\u2013':'ndash','\\u2014':'mdash','\\u2015':'horbar',',':'comma',';':'semi','\\u204F':'bsemi',':':'colon','\\u2A74':'Colone','!':'excl','\\xA1':'iexcl','?':'quest','\\xBF':'iquest','.':'period','\\u2025':'nldr','\\u2026':'mldr','\\xB7':'middot','\\'':'apos','\\u2018':'lsquo','\\u2019':'rsquo','\\u201A':'sbquo','\\u2039':'lsaquo','\\u203A':'rsaquo','\"':'quot','\\u201C':'ldquo','\\u201D':'rdquo','\\u201E':'bdquo','\\xAB':'laquo','\\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\\u2308':'lceil','\\u2309':'rceil','\\u230A':'lfloor','\\u230B':'rfloor','\\u2985':'lopar','\\u2986':'ropar','\\u298B':'lbrke','\\u298C':'rbrke','\\u298D':'lbrkslu','\\u298E':'rbrksld','\\u298F':'lbrksld','\\u2990':'rbrkslu','\\u2991':'langd','\\u2992':'rangd','\\u2993':'lparlt','\\u2994':'rpargt','\\u2995':'gtlPar','\\u2996':'ltrPar','\\u27E6':'lobrk','\\u27E7':'robrk','\\u27E8':'lang','\\u27E9':'rang','\\u27EA':'Lang','\\u27EB':'Rang','\\u27EC':'loang','\\u27ED':'roang','\\u2772':'lbbrk','\\u2773':'rbbrk','\\u2016':'Vert','\\xA7':'sect','\\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\\u2030':'permil','\\u2031':'pertenk','\\u2020':'dagger','\\u2021':'Dagger','\\u2022':'bull','\\u2043':'hybull','\\u2032':'prime','\\u2033':'Prime','\\u2034':'tprime','\\u2057':'qprime','\\u2035':'bprime','\\u2041':'caret','`':'grave','\\xB4':'acute','\\u02DC':'tilde','^':'Hat','\\xAF':'macr','\\u02D8':'breve','\\u02D9':'dot','\\xA8':'die','\\u02DA':'ring','\\u02DD':'dblac','\\xB8':'cedil','\\u02DB':'ogon','\\u02C6':'circ','\\u02C7':'caron','\\xB0':'deg','\\xA9':'copy','\\xAE':'reg','\\u2117':'copysr','\\u2118':'wp','\\u211E':'rx','\\u2127':'mho','\\u2129':'iiota','\\u2190':'larr','\\u219A':'nlarr','\\u2192':'rarr','\\u219B':'nrarr','\\u2191':'uarr','\\u2193':'darr','\\u2194':'harr','\\u21AE':'nharr','\\u2195':'varr','\\u2196':'nwarr','\\u2197':'nearr','\\u2198':'searr','\\u2199':'swarr','\\u219D':'rarrw','\\u219D\\u0338':'nrarrw','\\u219E':'Larr','\\u219F':'Uarr','\\u21A0':'Rarr','\\u21A1':'Darr','\\u21A2':'larrtl','\\u21A3':'rarrtl','\\u21A4':'mapstoleft','\\u21A5':'mapstoup','\\u21A6':'map','\\u21A7':'mapstodown','\\u21A9':'larrhk','\\u21AA':'rarrhk','\\u21AB':'larrlp','\\u21AC':'rarrlp','\\u21AD':'harrw','\\u21B0':'lsh','\\u21B1':'rsh','\\u21B2':'ldsh','\\u21B3':'rdsh','\\u21B5':'crarr','\\u21B6':'cularr','\\u21B7':'curarr','\\u21BA':'olarr','\\u21BB':'orarr','\\u21BC':'lharu','\\u21BD':'lhard','\\u21BE':'uharr','\\u21BF':'uharl','\\u21C0':'rharu','\\u21C1':'rhard','\\u21C2':'dharr','\\u21C3':'dharl','\\u21C4':'rlarr','\\u21C5':'udarr','\\u21C6':'lrarr','\\u21C7':'llarr','\\u21C8':'uuarr','\\u21C9':'rrarr','\\u21CA':'ddarr','\\u21CB':'lrhar','\\u21CC':'rlhar','\\u21D0':'lArr','\\u21CD':'nlArr','\\u21D1':'uArr','\\u21D2':'rArr','\\u21CF':'nrArr','\\u21D3':'dArr','\\u21D4':'iff','\\u21CE':'nhArr','\\u21D5':'vArr','\\u21D6':'nwArr','\\u21D7':'neArr','\\u21D8':'seArr','\\u21D9':'swArr','\\u21DA':'lAarr','\\u21DB':'rAarr','\\u21DD':'zigrarr','\\u21E4':'larrb','\\u21E5':'rarrb','\\u21F5':'duarr','\\u21FD':'loarr','\\u21FE':'roarr','\\u21FF':'hoarr','\\u2200':'forall','\\u2201':'comp','\\u2202':'part','\\u2202\\u0338':'npart','\\u2203':'exist','\\u2204':'nexist','\\u2205':'empty','\\u2207':'Del','\\u2208':'in','\\u2209':'notin','\\u220B':'ni','\\u220C':'notni','\\u03F6':'bepsi','\\u220F':'prod','\\u2210':'coprod','\\u2211':'sum','+':'plus','\\xB1':'pm','\\xF7':'div','\\xD7':'times','<':'lt','\\u226E':'nlt','<\\u20D2':'nvlt','=':'equals','\\u2260':'ne','=\\u20E5':'bne','\\u2A75':'Equal','>':'gt','\\u226F':'ngt','>\\u20D2':'nvgt','\\xAC':'not','|':'vert','\\xA6':'brvbar','\\u2212':'minus','\\u2213':'mp','\\u2214':'plusdo','\\u2044':'frasl','\\u2216':'setmn','\\u2217':'lowast','\\u2218':'compfn','\\u221A':'Sqrt','\\u221D':'prop','\\u221E':'infin','\\u221F':'angrt','\\u2220':'ang','\\u2220\\u20D2':'nang','\\u2221':'angmsd','\\u2222':'angsph','\\u2223':'mid','\\u2224':'nmid','\\u2225':'par','\\u2226':'npar','\\u2227':'and','\\u2228':'or','\\u2229':'cap','\\u2229\\uFE00':'caps','\\u222A':'cup','\\u222A\\uFE00':'cups','\\u222B':'int','\\u222C':'Int','\\u222D':'tint','\\u2A0C':'qint','\\u222E':'oint','\\u222F':'Conint','\\u2230':'Cconint','\\u2231':'cwint','\\u2232':'cwconint','\\u2233':'awconint','\\u2234':'there4','\\u2235':'becaus','\\u2236':'ratio','\\u2237':'Colon','\\u2238':'minusd','\\u223A':'mDDot','\\u223B':'homtht','\\u223C':'sim','\\u2241':'nsim','\\u223C\\u20D2':'nvsim','\\u223D':'bsim','\\u223D\\u0331':'race','\\u223E':'ac','\\u223E\\u0333':'acE','\\u223F':'acd','\\u2240':'wr','\\u2242':'esim','\\u2242\\u0338':'nesim','\\u2243':'sime','\\u2244':'nsime','\\u2245':'cong','\\u2247':'ncong','\\u2246':'simne','\\u2248':'ap','\\u2249':'nap','\\u224A':'ape','\\u224B':'apid','\\u224B\\u0338':'napid','\\u224C':'bcong','\\u224D':'CupCap','\\u226D':'NotCupCap','\\u224D\\u20D2':'nvap','\\u224E':'bump','\\u224E\\u0338':'nbump','\\u224F':'bumpe','\\u224F\\u0338':'nbumpe','\\u2250':'doteq','\\u2250\\u0338':'nedot','\\u2251':'eDot','\\u2252':'efDot','\\u2253':'erDot','\\u2254':'colone','\\u2255':'ecolon','\\u2256':'ecir','\\u2257':'cire','\\u2259':'wedgeq','\\u225A':'veeeq','\\u225C':'trie','\\u225F':'equest','\\u2261':'equiv','\\u2262':'nequiv','\\u2261\\u20E5':'bnequiv','\\u2264':'le','\\u2270':'nle','\\u2264\\u20D2':'nvle','\\u2265':'ge','\\u2271':'nge','\\u2265\\u20D2':'nvge','\\u2266':'lE','\\u2266\\u0338':'nlE','\\u2267':'gE','\\u2267\\u0338':'ngE','\\u2268\\uFE00':'lvnE','\\u2268':'lnE','\\u2269':'gnE','\\u2269\\uFE00':'gvnE','\\u226A':'ll','\\u226A\\u0338':'nLtv','\\u226A\\u20D2':'nLt','\\u226B':'gg','\\u226B\\u0338':'nGtv','\\u226B\\u20D2':'nGt','\\u226C':'twixt','\\u2272':'lsim','\\u2274':'nlsim','\\u2273':'gsim','\\u2275':'ngsim','\\u2276':'lg','\\u2278':'ntlg','\\u2277':'gl','\\u2279':'ntgl','\\u227A':'pr','\\u2280':'npr','\\u227B':'sc','\\u2281':'nsc','\\u227C':'prcue','\\u22E0':'nprcue','\\u227D':'sccue','\\u22E1':'nsccue','\\u227E':'prsim','\\u227F':'scsim','\\u227F\\u0338':'NotSucceedsTilde','\\u2282':'sub','\\u2284':'nsub','\\u2282\\u20D2':'vnsub','\\u2283':'sup','\\u2285':'nsup','\\u2283\\u20D2':'vnsup','\\u2286':'sube','\\u2288':'nsube','\\u2287':'supe','\\u2289':'nsupe','\\u228A\\uFE00':'vsubne','\\u228A':'subne','\\u228B\\uFE00':'vsupne','\\u228B':'supne','\\u228D':'cupdot','\\u228E':'uplus','\\u228F':'sqsub','\\u228F\\u0338':'NotSquareSubset','\\u2290':'sqsup','\\u2290\\u0338':'NotSquareSuperset','\\u2291':'sqsube','\\u22E2':'nsqsube','\\u2292':'sqsupe','\\u22E3':'nsqsupe','\\u2293':'sqcap','\\u2293\\uFE00':'sqcaps','\\u2294':'sqcup','\\u2294\\uFE00':'sqcups','\\u2295':'oplus','\\u2296':'ominus','\\u2297':'otimes','\\u2298':'osol','\\u2299':'odot','\\u229A':'ocir','\\u229B':'oast','\\u229D':'odash','\\u229E':'plusb','\\u229F':'minusb','\\u22A0':'timesb','\\u22A1':'sdotb','\\u22A2':'vdash','\\u22AC':'nvdash','\\u22A3':'dashv','\\u22A4':'top','\\u22A5':'bot','\\u22A7':'models','\\u22A8':'vDash','\\u22AD':'nvDash','\\u22A9':'Vdash','\\u22AE':'nVdash','\\u22AA':'Vvdash','\\u22AB':'VDash','\\u22AF':'nVDash','\\u22B0':'prurel','\\u22B2':'vltri','\\u22EA':'nltri','\\u22B3':'vrtri','\\u22EB':'nrtri','\\u22B4':'ltrie','\\u22EC':'nltrie','\\u22B4\\u20D2':'nvltrie','\\u22B5':'rtrie','\\u22ED':'nrtrie','\\u22B5\\u20D2':'nvrtrie','\\u22B6':'origof','\\u22B7':'imof','\\u22B8':'mumap','\\u22B9':'hercon','\\u22BA':'intcal','\\u22BB':'veebar','\\u22BD':'barvee','\\u22BE':'angrtvb','\\u22BF':'lrtri','\\u22C0':'Wedge','\\u22C1':'Vee','\\u22C2':'xcap','\\u22C3':'xcup','\\u22C4':'diam','\\u22C5':'sdot','\\u22C6':'Star','\\u22C7':'divonx','\\u22C8':'bowtie','\\u22C9':'ltimes','\\u22CA':'rtimes','\\u22CB':'lthree','\\u22CC':'rthree','\\u22CD':'bsime','\\u22CE':'cuvee','\\u22CF':'cuwed','\\u22D0':'Sub','\\u22D1':'Sup','\\u22D2':'Cap','\\u22D3':'Cup','\\u22D4':'fork','\\u22D5':'epar','\\u22D6':'ltdot','\\u22D7':'gtdot','\\u22D8':'Ll','\\u22D8\\u0338':'nLl','\\u22D9':'Gg','\\u22D9\\u0338':'nGg','\\u22DA\\uFE00':'lesg','\\u22DA':'leg','\\u22DB':'gel','\\u22DB\\uFE00':'gesl','\\u22DE':'cuepr','\\u22DF':'cuesc','\\u22E6':'lnsim','\\u22E7':'gnsim','\\u22E8':'prnsim','\\u22E9':'scnsim','\\u22EE':'vellip','\\u22EF':'ctdot','\\u22F0':'utdot','\\u22F1':'dtdot','\\u22F2':'disin','\\u22F3':'isinsv','\\u22F4':'isins','\\u22F5':'isindot','\\u22F5\\u0338':'notindot','\\u22F6':'notinvc','\\u22F7':'notinvb','\\u22F9':'isinE','\\u22F9\\u0338':'notinE','\\u22FA':'nisd','\\u22FB':'xnis','\\u22FC':'nis','\\u22FD':'notnivc','\\u22FE':'notnivb','\\u2305':'barwed','\\u2306':'Barwed','\\u230C':'drcrop','\\u230D':'dlcrop','\\u230E':'urcrop','\\u230F':'ulcrop','\\u2310':'bnot','\\u2312':'profline','\\u2313':'profsurf','\\u2315':'telrec','\\u2316':'target','\\u231C':'ulcorn','\\u231D':'urcorn','\\u231E':'dlcorn','\\u231F':'drcorn','\\u2322':'frown','\\u2323':'smile','\\u232D':'cylcty','\\u232E':'profalar','\\u2336':'topbot','\\u233D':'ovbar','\\u233F':'solbar','\\u237C':'angzarr','\\u23B0':'lmoust','\\u23B1':'rmoust','\\u23B4':'tbrk','\\u23B5':'bbrk','\\u23B6':'bbrktbrk','\\u23DC':'OverParenthesis','\\u23DD':'UnderParenthesis','\\u23DE':'OverBrace','\\u23DF':'UnderBrace','\\u23E2':'trpezium','\\u23E7':'elinters','\\u2423':'blank','\\u2500':'boxh','\\u2502':'boxv','\\u250C':'boxdr','\\u2510':'boxdl','\\u2514':'boxur','\\u2518':'boxul','\\u251C':'boxvr','\\u2524':'boxvl','\\u252C':'boxhd','\\u2534':'boxhu','\\u253C':'boxvh','\\u2550':'boxH','\\u2551':'boxV','\\u2552':'boxdR','\\u2553':'boxDr','\\u2554':'boxDR','\\u2555':'boxdL','\\u2556':'boxDl','\\u2557':'boxDL','\\u2558':'boxuR','\\u2559':'boxUr','\\u255A':'boxUR','\\u255B':'boxuL','\\u255C':'boxUl','\\u255D':'boxUL','\\u255E':'boxvR','\\u255F':'boxVr','\\u2560':'boxVR','\\u2561':'boxvL','\\u2562':'boxVl','\\u2563':'boxVL','\\u2564':'boxHd','\\u2565':'boxhD','\\u2566':'boxHD','\\u2567':'boxHu','\\u2568':'boxhU','\\u2569':'boxHU','\\u256A':'boxvH','\\u256B':'boxVh','\\u256C':'boxVH','\\u2580':'uhblk','\\u2584':'lhblk','\\u2588':'block','\\u2591':'blk14','\\u2592':'blk12','\\u2593':'blk34','\\u25A1':'squ','\\u25AA':'squf','\\u25AB':'EmptyVerySmallSquare','\\u25AD':'rect','\\u25AE':'marker','\\u25B1':'fltns','\\u25B3':'xutri','\\u25B4':'utrif','\\u25B5':'utri','\\u25B8':'rtrif','\\u25B9':'rtri','\\u25BD':'xdtri','\\u25BE':'dtrif','\\u25BF':'dtri','\\u25C2':'ltrif','\\u25C3':'ltri','\\u25CA':'loz','\\u25CB':'cir','\\u25EC':'tridot','\\u25EF':'xcirc','\\u25F8':'ultri','\\u25F9':'urtri','\\u25FA':'lltri','\\u25FB':'EmptySmallSquare','\\u25FC':'FilledSmallSquare','\\u2605':'starf','\\u2606':'star','\\u260E':'phone','\\u2640':'female','\\u2642':'male','\\u2660':'spades','\\u2663':'clubs','\\u2665':'hearts','\\u2666':'diams','\\u266A':'sung','\\u2713':'check','\\u2717':'cross','\\u2720':'malt','\\u2736':'sext','\\u2758':'VerticalSeparator','\\u27C8':'bsolhsub','\\u27C9':'suphsol','\\u27F5':'xlarr','\\u27F6':'xrarr','\\u27F7':'xharr','\\u27F8':'xlArr','\\u27F9':'xrArr','\\u27FA':'xhArr','\\u27FC':'xmap','\\u27FF':'dzigrarr','\\u2902':'nvlArr','\\u2903':'nvrArr','\\u2904':'nvHarr','\\u2905':'Map','\\u290C':'lbarr','\\u290D':'rbarr','\\u290E':'lBarr','\\u290F':'rBarr','\\u2910':'RBarr','\\u2911':'DDotrahd','\\u2912':'UpArrowBar','\\u2913':'DownArrowBar','\\u2916':'Rarrtl','\\u2919':'latail','\\u291A':'ratail','\\u291B':'lAtail','\\u291C':'rAtail','\\u291D':'larrfs','\\u291E':'rarrfs','\\u291F':'larrbfs','\\u2920':'rarrbfs','\\u2923':'nwarhk','\\u2924':'nearhk','\\u2925':'searhk','\\u2926':'swarhk','\\u2927':'nwnear','\\u2928':'toea','\\u2929':'tosa','\\u292A':'swnwar','\\u2933':'rarrc','\\u2933\\u0338':'nrarrc','\\u2935':'cudarrr','\\u2936':'ldca','\\u2937':'rdca','\\u2938':'cudarrl','\\u2939':'larrpl','\\u293C':'curarrm','\\u293D':'cularrp','\\u2945':'rarrpl','\\u2948':'harrcir','\\u2949':'Uarrocir','\\u294A':'lurdshar','\\u294B':'ldrushar','\\u294E':'LeftRightVector','\\u294F':'RightUpDownVector','\\u2950':'DownLeftRightVector','\\u2951':'LeftUpDownVector','\\u2952':'LeftVectorBar','\\u2953':'RightVectorBar','\\u2954':'RightUpVectorBar','\\u2955':'RightDownVectorBar','\\u2956':'DownLeftVectorBar','\\u2957':'DownRightVectorBar','\\u2958':'LeftUpVectorBar','\\u2959':'LeftDownVectorBar','\\u295A':'LeftTeeVector','\\u295B':'RightTeeVector','\\u295C':'RightUpTeeVector','\\u295D':'RightDownTeeVector','\\u295E':'DownLeftTeeVector','\\u295F':'DownRightTeeVector','\\u2960':'LeftUpTeeVector','\\u2961':'LeftDownTeeVector','\\u2962':'lHar','\\u2963':'uHar','\\u2964':'rHar','\\u2965':'dHar','\\u2966':'luruhar','\\u2967':'ldrdhar','\\u2968':'ruluhar','\\u2969':'rdldhar','\\u296A':'lharul','\\u296B':'llhard','\\u296C':'rharul','\\u296D':'lrhard','\\u296E':'udhar','\\u296F':'duhar','\\u2970':'RoundImplies','\\u2971':'erarr','\\u2972':'simrarr','\\u2973':'larrsim','\\u2974':'rarrsim','\\u2975':'rarrap','\\u2976':'ltlarr','\\u2978':'gtrarr','\\u2979':'subrarr','\\u297B':'suplarr','\\u297C':'lfisht','\\u297D':'rfisht','\\u297E':'ufisht','\\u297F':'dfisht','\\u299A':'vzigzag','\\u299C':'vangrt','\\u299D':'angrtvbd','\\u29A4':'ange','\\u29A5':'range','\\u29A6':'dwangle','\\u29A7':'uwangle','\\u29A8':'angmsdaa','\\u29A9':'angmsdab','\\u29AA':'angmsdac','\\u29AB':'angmsdad','\\u29AC':'angmsdae','\\u29AD':'angmsdaf','\\u29AE':'angmsdag','\\u29AF':'angmsdah','\\u29B0':'bemptyv','\\u29B1':'demptyv','\\u29B2':'cemptyv','\\u29B3':'raemptyv','\\u29B4':'laemptyv','\\u29B5':'ohbar','\\u29B6':'omid','\\u29B7':'opar','\\u29B9':'operp','\\u29BB':'olcross','\\u29BC':'odsold','\\u29BE':'olcir','\\u29BF':'ofcir','\\u29C0':'olt','\\u29C1':'ogt','\\u29C2':'cirscir','\\u29C3':'cirE','\\u29C4':'solb','\\u29C5':'bsolb','\\u29C9':'boxbox','\\u29CD':'trisb','\\u29CE':'rtriltri','\\u29CF':'LeftTriangleBar','\\u29CF\\u0338':'NotLeftTriangleBar','\\u29D0':'RightTriangleBar','\\u29D0\\u0338':'NotRightTriangleBar','\\u29DC':'iinfin','\\u29DD':'infintie','\\u29DE':'nvinfin','\\u29E3':'eparsl','\\u29E4':'smeparsl','\\u29E5':'eqvparsl','\\u29EB':'lozf','\\u29F4':'RuleDelayed','\\u29F6':'dsol','\\u2A00':'xodot','\\u2A01':'xoplus','\\u2A02':'xotime','\\u2A04':'xuplus','\\u2A06':'xsqcup','\\u2A0D':'fpartint','\\u2A10':'cirfnint','\\u2A11':'awint','\\u2A12':'rppolint','\\u2A13':'scpolint','\\u2A14':'npolint','\\u2A15':'pointint','\\u2A16':'quatint','\\u2A17':'intlarhk','\\u2A22':'pluscir','\\u2A23':'plusacir','\\u2A24':'simplus','\\u2A25':'plusdu','\\u2A26':'plussim','\\u2A27':'plustwo','\\u2A29':'mcomma','\\u2A2A':'minusdu','\\u2A2D':'loplus','\\u2A2E':'roplus','\\u2A2F':'Cross','\\u2A30':'timesd','\\u2A31':'timesbar','\\u2A33':'smashp','\\u2A34':'lotimes','\\u2A35':'rotimes','\\u2A36':'otimesas','\\u2A37':'Otimes','\\u2A38':'odiv','\\u2A39':'triplus','\\u2A3A':'triminus','\\u2A3B':'tritime','\\u2A3C':'iprod','\\u2A3F':'amalg','\\u2A40':'capdot','\\u2A42':'ncup','\\u2A43':'ncap','\\u2A44':'capand','\\u2A45':'cupor','\\u2A46':'cupcap','\\u2A47':'capcup','\\u2A48':'cupbrcap','\\u2A49':'capbrcup','\\u2A4A':'cupcup','\\u2A4B':'capcap','\\u2A4C':'ccups','\\u2A4D':'ccaps','\\u2A50':'ccupssm','\\u2A53':'And','\\u2A54':'Or','\\u2A55':'andand','\\u2A56':'oror','\\u2A57':'orslope','\\u2A58':'andslope','\\u2A5A':'andv','\\u2A5B':'orv','\\u2A5C':'andd','\\u2A5D':'ord','\\u2A5F':'wedbar','\\u2A66':'sdote','\\u2A6A':'simdot','\\u2A6D':'congdot','\\u2A6D\\u0338':'ncongdot','\\u2A6E':'easter','\\u2A6F':'apacir','\\u2A70':'apE','\\u2A70\\u0338':'napE','\\u2A71':'eplus','\\u2A72':'pluse','\\u2A73':'Esim','\\u2A77':'eDDot','\\u2A78':'equivDD','\\u2A79':'ltcir','\\u2A7A':'gtcir','\\u2A7B':'ltquest','\\u2A7C':'gtquest','\\u2A7D':'les','\\u2A7D\\u0338':'nles','\\u2A7E':'ges','\\u2A7E\\u0338':'nges','\\u2A7F':'lesdot','\\u2A80':'gesdot','\\u2A81':'lesdoto','\\u2A82':'gesdoto','\\u2A83':'lesdotor','\\u2A84':'gesdotol','\\u2A85':'lap','\\u2A86':'gap','\\u2A87':'lne','\\u2A88':'gne','\\u2A89':'lnap','\\u2A8A':'gnap','\\u2A8B':'lEg','\\u2A8C':'gEl','\\u2A8D':'lsime','\\u2A8E':'gsime','\\u2A8F':'lsimg','\\u2A90':'gsiml','\\u2A91':'lgE','\\u2A92':'glE','\\u2A93':'lesges','\\u2A94':'gesles','\\u2A95':'els','\\u2A96':'egs','\\u2A97':'elsdot','\\u2A98':'egsdot','\\u2A99':'el','\\u2A9A':'eg','\\u2A9D':'siml','\\u2A9E':'simg','\\u2A9F':'simlE','\\u2AA0':'simgE','\\u2AA1':'LessLess','\\u2AA1\\u0338':'NotNestedLessLess','\\u2AA2':'GreaterGreater','\\u2AA2\\u0338':'NotNestedGreaterGreater','\\u2AA4':'glj','\\u2AA5':'gla','\\u2AA6':'ltcc','\\u2AA7':'gtcc','\\u2AA8':'lescc','\\u2AA9':'gescc','\\u2AAA':'smt','\\u2AAB':'lat','\\u2AAC':'smte','\\u2AAC\\uFE00':'smtes','\\u2AAD':'late','\\u2AAD\\uFE00':'lates','\\u2AAE':'bumpE','\\u2AAF':'pre','\\u2AAF\\u0338':'npre','\\u2AB0':'sce','\\u2AB0\\u0338':'nsce','\\u2AB3':'prE','\\u2AB4':'scE','\\u2AB5':'prnE','\\u2AB6':'scnE','\\u2AB7':'prap','\\u2AB8':'scap','\\u2AB9':'prnap','\\u2ABA':'scnap','\\u2ABB':'Pr','\\u2ABC':'Sc','\\u2ABD':'subdot','\\u2ABE':'supdot','\\u2ABF':'subplus','\\u2AC0':'supplus','\\u2AC1':'submult','\\u2AC2':'supmult','\\u2AC3':'subedot','\\u2AC4':'supedot','\\u2AC5':'subE','\\u2AC5\\u0338':'nsubE','\\u2AC6':'supE','\\u2AC6\\u0338':'nsupE','\\u2AC7':'subsim','\\u2AC8':'supsim','\\u2ACB\\uFE00':'vsubnE','\\u2ACB':'subnE','\\u2ACC\\uFE00':'vsupnE','\\u2ACC':'supnE','\\u2ACF':'csub','\\u2AD0':'csup','\\u2AD1':'csube','\\u2AD2':'csupe','\\u2AD3':'subsup','\\u2AD4':'supsub','\\u2AD5':'subsub','\\u2AD6':'supsup','\\u2AD7':'suphsub','\\u2AD8':'supdsub','\\u2AD9':'forkv','\\u2ADA':'topfork','\\u2ADB':'mlcp','\\u2AE4':'Dashv','\\u2AE6':'Vdashl','\\u2AE7':'Barv','\\u2AE8':'vBar','\\u2AE9':'vBarv','\\u2AEB':'Vbar','\\u2AEC':'Not','\\u2AED':'bNot','\\u2AEE':'rnmid','\\u2AEF':'cirmid','\\u2AF0':'midcir','\\u2AF1':'topcir','\\u2AF2':'nhpar','\\u2AF3':'parsim','\\u2AFD':'parsl','\\u2AFD\\u20E5':'nparsl','\\u266D':'flat','\\u266E':'natur','\\u266F':'sharp','\\xA4':'curren','\\xA2':'cent','$':'dollar','\\xA3':'pound','\\xA5':'yen','\\u20AC':'euro','\\xB9':'sup1','\\xBD':'half','\\u2153':'frac13','\\xBC':'frac14','\\u2155':'frac15','\\u2159':'frac16','\\u215B':'frac18','\\xB2':'sup2','\\u2154':'frac23','\\u2156':'frac25','\\xB3':'sup3','\\xBE':'frac34','\\u2157':'frac35','\\u215C':'frac38','\\u2158':'frac45','\\u215A':'frac56','\\u215D':'frac58','\\u215E':'frac78','\\uD835\\uDCB6':'ascr','\\uD835\\uDD52':'aopf','\\uD835\\uDD1E':'afr','\\uD835\\uDD38':'Aopf','\\uD835\\uDD04':'Afr','\\uD835\\uDC9C':'Ascr','\\xAA':'ordf','\\xE1':'aacute','\\xC1':'Aacute','\\xE0':'agrave','\\xC0':'Agrave','\\u0103':'abreve','\\u0102':'Abreve','\\xE2':'acirc','\\xC2':'Acirc','\\xE5':'aring','\\xC5':'angst','\\xE4':'auml','\\xC4':'Auml','\\xE3':'atilde','\\xC3':'Atilde','\\u0105':'aogon','\\u0104':'Aogon','\\u0101':'amacr','\\u0100':'Amacr','\\xE6':'aelig','\\xC6':'AElig','\\uD835\\uDCB7':'bscr','\\uD835\\uDD53':'bopf','\\uD835\\uDD1F':'bfr','\\uD835\\uDD39':'Bopf','\\u212C':'Bscr','\\uD835\\uDD05':'Bfr','\\uD835\\uDD20':'cfr','\\uD835\\uDCB8':'cscr','\\uD835\\uDD54':'copf','\\u212D':'Cfr','\\uD835\\uDC9E':'Cscr','\\u2102':'Copf','\\u0107':'cacute','\\u0106':'Cacute','\\u0109':'ccirc','\\u0108':'Ccirc','\\u010D':'ccaron','\\u010C':'Ccaron','\\u010B':'cdot','\\u010A':'Cdot','\\xE7':'ccedil','\\xC7':'Ccedil','\\u2105':'incare','\\uD835\\uDD21':'dfr','\\u2146':'dd','\\uD835\\uDD55':'dopf','\\uD835\\uDCB9':'dscr','\\uD835\\uDC9F':'Dscr','\\uD835\\uDD07':'Dfr','\\u2145':'DD','\\uD835\\uDD3B':'Dopf','\\u010F':'dcaron','\\u010E':'Dcaron','\\u0111':'dstrok','\\u0110':'Dstrok','\\xF0':'eth','\\xD0':'ETH','\\u2147':'ee','\\u212F':'escr','\\uD835\\uDD22':'efr','\\uD835\\uDD56':'eopf','\\u2130':'Escr','\\uD835\\uDD08':'Efr','\\uD835\\uDD3C':'Eopf','\\xE9':'eacute','\\xC9':'Eacute','\\xE8':'egrave','\\xC8':'Egrave','\\xEA':'ecirc','\\xCA':'Ecirc','\\u011B':'ecaron','\\u011A':'Ecaron','\\xEB':'euml','\\xCB':'Euml','\\u0117':'edot','\\u0116':'Edot','\\u0119':'eogon','\\u0118':'Eogon','\\u0113':'emacr','\\u0112':'Emacr','\\uD835\\uDD23':'ffr','\\uD835\\uDD57':'fopf','\\uD835\\uDCBB':'fscr','\\uD835\\uDD09':'Ffr','\\uD835\\uDD3D':'Fopf','\\u2131':'Fscr','\\uFB00':'fflig','\\uFB03':'ffilig','\\uFB04':'ffllig','\\uFB01':'filig','fj':'fjlig','\\uFB02':'fllig','\\u0192':'fnof','\\u210A':'gscr','\\uD835\\uDD58':'gopf','\\uD835\\uDD24':'gfr','\\uD835\\uDCA2':'Gscr','\\uD835\\uDD3E':'Gopf','\\uD835\\uDD0A':'Gfr','\\u01F5':'gacute','\\u011F':'gbreve','\\u011E':'Gbreve','\\u011D':'gcirc','\\u011C':'Gcirc','\\u0121':'gdot','\\u0120':'Gdot','\\u0122':'Gcedil','\\uD835\\uDD25':'hfr','\\u210E':'planckh','\\uD835\\uDCBD':'hscr','\\uD835\\uDD59':'hopf','\\u210B':'Hscr','\\u210C':'Hfr','\\u210D':'Hopf','\\u0125':'hcirc','\\u0124':'Hcirc','\\u210F':'hbar','\\u0127':'hstrok','\\u0126':'Hstrok','\\uD835\\uDD5A':'iopf','\\uD835\\uDD26':'ifr','\\uD835\\uDCBE':'iscr','\\u2148':'ii','\\uD835\\uDD40':'Iopf','\\u2110':'Iscr','\\u2111':'Im','\\xED':'iacute','\\xCD':'Iacute','\\xEC':'igrave','\\xCC':'Igrave','\\xEE':'icirc','\\xCE':'Icirc','\\xEF':'iuml','\\xCF':'Iuml','\\u0129':'itilde','\\u0128':'Itilde','\\u0130':'Idot','\\u012F':'iogon','\\u012E':'Iogon','\\u012B':'imacr','\\u012A':'Imacr','\\u0133':'ijlig','\\u0132':'IJlig','\\u0131':'imath','\\uD835\\uDCBF':'jscr','\\uD835\\uDD5B':'jopf','\\uD835\\uDD27':'jfr','\\uD835\\uDCA5':'Jscr','\\uD835\\uDD0D':'Jfr','\\uD835\\uDD41':'Jopf','\\u0135':'jcirc','\\u0134':'Jcirc','\\u0237':'jmath','\\uD835\\uDD5C':'kopf','\\uD835\\uDCC0':'kscr','\\uD835\\uDD28':'kfr','\\uD835\\uDCA6':'Kscr','\\uD835\\uDD42':'Kopf','\\uD835\\uDD0E':'Kfr','\\u0137':'kcedil','\\u0136':'Kcedil','\\uD835\\uDD29':'lfr','\\uD835\\uDCC1':'lscr','\\u2113':'ell','\\uD835\\uDD5D':'lopf','\\u2112':'Lscr','\\uD835\\uDD0F':'Lfr','\\uD835\\uDD43':'Lopf','\\u013A':'lacute','\\u0139':'Lacute','\\u013E':'lcaron','\\u013D':'Lcaron','\\u013C':'lcedil','\\u013B':'Lcedil','\\u0142':'lstrok','\\u0141':'Lstrok','\\u0140':'lmidot','\\u013F':'Lmidot','\\uD835\\uDD2A':'mfr','\\uD835\\uDD5E':'mopf','\\uD835\\uDCC2':'mscr','\\uD835\\uDD10':'Mfr','\\uD835\\uDD44':'Mopf','\\u2133':'Mscr','\\uD835\\uDD2B':'nfr','\\uD835\\uDD5F':'nopf','\\uD835\\uDCC3':'nscr','\\u2115':'Nopf','\\uD835\\uDCA9':'Nscr','\\uD835\\uDD11':'Nfr','\\u0144':'nacute','\\u0143':'Nacute','\\u0148':'ncaron','\\u0147':'Ncaron','\\xF1':'ntilde','\\xD1':'Ntilde','\\u0146':'ncedil','\\u0145':'Ncedil','\\u2116':'numero','\\u014B':'eng','\\u014A':'ENG','\\uD835\\uDD60':'oopf','\\uD835\\uDD2C':'ofr','\\u2134':'oscr','\\uD835\\uDCAA':'Oscr','\\uD835\\uDD12':'Ofr','\\uD835\\uDD46':'Oopf','\\xBA':'ordm','\\xF3':'oacute','\\xD3':'Oacute','\\xF2':'ograve','\\xD2':'Ograve','\\xF4':'ocirc','\\xD4':'Ocirc','\\xF6':'ouml','\\xD6':'Ouml','\\u0151':'odblac','\\u0150':'Odblac','\\xF5':'otilde','\\xD5':'Otilde','\\xF8':'oslash','\\xD8':'Oslash','\\u014D':'omacr','\\u014C':'Omacr','\\u0153':'oelig','\\u0152':'OElig','\\uD835\\uDD2D':'pfr','\\uD835\\uDCC5':'pscr','\\uD835\\uDD61':'popf','\\u2119':'Popf','\\uD835\\uDD13':'Pfr','\\uD835\\uDCAB':'Pscr','\\uD835\\uDD62':'qopf','\\uD835\\uDD2E':'qfr','\\uD835\\uDCC6':'qscr','\\uD835\\uDCAC':'Qscr','\\uD835\\uDD14':'Qfr','\\u211A':'Qopf','\\u0138':'kgreen','\\uD835\\uDD2F':'rfr','\\uD835\\uDD63':'ropf','\\uD835\\uDCC7':'rscr','\\u211B':'Rscr','\\u211C':'Re','\\u211D':'Ropf','\\u0155':'racute','\\u0154':'Racute','\\u0159':'rcaron','\\u0158':'Rcaron','\\u0157':'rcedil','\\u0156':'Rcedil','\\uD835\\uDD64':'sopf','\\uD835\\uDCC8':'sscr','\\uD835\\uDD30':'sfr','\\uD835\\uDD4A':'Sopf','\\uD835\\uDD16':'Sfr','\\uD835\\uDCAE':'Sscr','\\u24C8':'oS','\\u015B':'sacute','\\u015A':'Sacute','\\u015D':'scirc','\\u015C':'Scirc','\\u0161':'scaron','\\u0160':'Scaron','\\u015F':'scedil','\\u015E':'Scedil','\\xDF':'szlig','\\uD835\\uDD31':'tfr','\\uD835\\uDCC9':'tscr','\\uD835\\uDD65':'topf','\\uD835\\uDCAF':'Tscr','\\uD835\\uDD17':'Tfr','\\uD835\\uDD4B':'Topf','\\u0165':'tcaron','\\u0164':'Tcaron','\\u0163':'tcedil','\\u0162':'Tcedil','\\u2122':'trade','\\u0167':'tstrok','\\u0166':'Tstrok','\\uD835\\uDCCA':'uscr','\\uD835\\uDD66':'uopf','\\uD835\\uDD32':'ufr','\\uD835\\uDD4C':'Uopf','\\uD835\\uDD18':'Ufr','\\uD835\\uDCB0':'Uscr','\\xFA':'uacute','\\xDA':'Uacute','\\xF9':'ugrave','\\xD9':'Ugrave','\\u016D':'ubreve','\\u016C':'Ubreve','\\xFB':'ucirc','\\xDB':'Ucirc','\\u016F':'uring','\\u016E':'Uring','\\xFC':'uuml','\\xDC':'Uuml','\\u0171':'udblac','\\u0170':'Udblac','\\u0169':'utilde','\\u0168':'Utilde','\\u0173':'uogon','\\u0172':'Uogon','\\u016B':'umacr','\\u016A':'Umacr','\\uD835\\uDD33':'vfr','\\uD835\\uDD67':'vopf','\\uD835\\uDCCB':'vscr','\\uD835\\uDD19':'Vfr','\\uD835\\uDD4D':'Vopf','\\uD835\\uDCB1':'Vscr','\\uD835\\uDD68':'wopf','\\uD835\\uDCCC':'wscr','\\uD835\\uDD34':'wfr','\\uD835\\uDCB2':'Wscr','\\uD835\\uDD4E':'Wopf','\\uD835\\uDD1A':'Wfr','\\u0175':'wcirc','\\u0174':'Wcirc','\\uD835\\uDD35':'xfr','\\uD835\\uDCCD':'xscr','\\uD835\\uDD69':'xopf','\\uD835\\uDD4F':'Xopf','\\uD835\\uDD1B':'Xfr','\\uD835\\uDCB3':'Xscr','\\uD835\\uDD36':'yfr','\\uD835\\uDCCE':'yscr','\\uD835\\uDD6A':'yopf','\\uD835\\uDCB4':'Yscr','\\uD835\\uDD1C':'Yfr','\\uD835\\uDD50':'Yopf','\\xFD':'yacute','\\xDD':'Yacute','\\u0177':'ycirc','\\u0176':'Ycirc','\\xFF':'yuml','\\u0178':'Yuml','\\uD835\\uDCCF':'zscr','\\uD835\\uDD37':'zfr','\\uD835\\uDD6B':'zopf','\\u2128':'Zfr','\\u2124':'Zopf','\\uD835\\uDCB5':'Zscr','\\u017A':'zacute','\\u0179':'Zacute','\\u017E':'zcaron','\\u017D':'Zcaron','\\u017C':'zdot','\\u017B':'Zdot','\\u01B5':'imped','\\xFE':'thorn','\\xDE':'THORN','\\u0149':'napos','\\u03B1':'alpha','\\u0391':'Alpha','\\u03B2':'beta','\\u0392':'Beta','\\u03B3':'gamma','\\u0393':'Gamma','\\u03B4':'delta','\\u0394':'Delta','\\u03B5':'epsi','\\u03F5':'epsiv','\\u0395':'Epsilon','\\u03DD':'gammad','\\u03DC':'Gammad','\\u03B6':'zeta','\\u0396':'Zeta','\\u03B7':'eta','\\u0397':'Eta','\\u03B8':'theta','\\u03D1':'thetav','\\u0398':'Theta','\\u03B9':'iota','\\u0399':'Iota','\\u03BA':'kappa','\\u03F0':'kappav','\\u039A':'Kappa','\\u03BB':'lambda','\\u039B':'Lambda','\\u03BC':'mu','\\xB5':'micro','\\u039C':'Mu','\\u03BD':'nu','\\u039D':'Nu','\\u03BE':'xi','\\u039E':'Xi','\\u03BF':'omicron','\\u039F':'Omicron','\\u03C0':'pi','\\u03D6':'piv','\\u03A0':'Pi','\\u03C1':'rho','\\u03F1':'rhov','\\u03A1':'Rho','\\u03C3':'sigma','\\u03A3':'Sigma','\\u03C2':'sigmaf','\\u03C4':'tau','\\u03A4':'Tau','\\u03C5':'upsi','\\u03A5':'Upsilon','\\u03D2':'Upsi','\\u03C6':'phi','\\u03D5':'phiv','\\u03A6':'Phi','\\u03C7':'chi','\\u03A7':'Chi','\\u03C8':'psi','\\u03A8':'Psi','\\u03C9':'omega','\\u03A9':'ohm','\\u0430':'acy','\\u0410':'Acy','\\u0431':'bcy','\\u0411':'Bcy','\\u0432':'vcy','\\u0412':'Vcy','\\u0433':'gcy','\\u0413':'Gcy','\\u0453':'gjcy','\\u0403':'GJcy','\\u0434':'dcy','\\u0414':'Dcy','\\u0452':'djcy','\\u0402':'DJcy','\\u0435':'iecy','\\u0415':'IEcy','\\u0451':'iocy','\\u0401':'IOcy','\\u0454':'jukcy','\\u0404':'Jukcy','\\u0436':'zhcy','\\u0416':'ZHcy','\\u0437':'zcy','\\u0417':'Zcy','\\u0455':'dscy','\\u0405':'DScy','\\u0438':'icy','\\u0418':'Icy','\\u0456':'iukcy','\\u0406':'Iukcy','\\u0457':'yicy','\\u0407':'YIcy','\\u0439':'jcy','\\u0419':'Jcy','\\u0458':'jsercy','\\u0408':'Jsercy','\\u043A':'kcy','\\u041A':'Kcy','\\u045C':'kjcy','\\u040C':'KJcy','\\u043B':'lcy','\\u041B':'Lcy','\\u0459':'ljcy','\\u0409':'LJcy','\\u043C':'mcy','\\u041C':'Mcy','\\u043D':'ncy','\\u041D':'Ncy','\\u045A':'njcy','\\u040A':'NJcy','\\u043E':'ocy','\\u041E':'Ocy','\\u043F':'pcy','\\u041F':'Pcy','\\u0440':'rcy','\\u0420':'Rcy','\\u0441':'scy','\\u0421':'Scy','\\u0442':'tcy','\\u0422':'Tcy','\\u045B':'tshcy','\\u040B':'TSHcy','\\u0443':'ucy','\\u0423':'Ucy','\\u045E':'ubrcy','\\u040E':'Ubrcy','\\u0444':'fcy','\\u0424':'Fcy','\\u0445':'khcy','\\u0425':'KHcy','\\u0446':'tscy','\\u0426':'TScy','\\u0447':'chcy','\\u0427':'CHcy','\\u045F':'dzcy','\\u040F':'DZcy','\\u0448':'shcy','\\u0428':'SHcy','\\u0449':'shchcy','\\u0429':'SHCHcy','\\u044A':'hardcy','\\u042A':'HARDcy','\\u044B':'ycy','\\u042B':'Ycy','\\u044C':'softcy','\\u042C':'SOFTcy','\\u044D':'ecy','\\u042D':'Ecy','\\u044E':'yucy','\\u042E':'YUcy','\\u044F':'yacy','\\u042F':'YAcy','\\u2135':'aleph','\\u2136':'beth','\\u2137':'gimel','\\u2138':'daleth'};\n\n\tvar regexEscape = /[\"&'<>`]/g;\n\tvar escapeMap = {\n\t\t'\"': '"',\n\t\t'&': '&',\n\t\t'\\'': ''',\n\t\t'<': '<',\n\t\t// See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the\n\t\t// following is not strictly necessary unless it’s part of a tag or an\n\t\t// unquoted attribute value. We’re only escaping it to support those\n\t\t// situations, and for XML support.\n\t\t'>': '>',\n\t\t// In Internet Explorer ≤ 8, the backtick character can be used\n\t\t// to break out of (un)quoted attribute values or HTML comments.\n\t\t// See http://html5sec.org/#102, http://html5sec.org/#108, and\n\t\t// http://html5sec.org/#133.\n\t\t'`': '`'\n\t};\n\n\tvar regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;\n\tvar regexInvalidRawCodePoint = /[\\0-\\x08\\x0B\\x0E-\\x1F\\x7F-\\x9F\\uFDD0-\\uFDEF\\uFFFE\\uFFFF]|[\\uD83F\\uD87F\\uD8BF\\uD8FF\\uD93F\\uD97F\\uD9BF\\uD9FF\\uDA3F\\uDA7F\\uDABF\\uDAFF\\uDB3F\\uDB7F\\uDBBF\\uDBFF][\\uDFFE\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n\tvar regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gjcy|tint|gesl|mid|Sfr|ggg|top|ges|gla|glE|glj|geq|gne|gEl|gel|gnE|Gcy|gcy|gap|Tfr|tfr|Tcy|tcy|Hat|Tau|Ffr|tau|Tab|hfr|Hfr|ffr|Fcy|fcy|icy|Icy|iff|ETH|eth|ifr|Ifr|Eta|eta|int|Int|Sup|sup|ucy|Ucy|Sum|sum|jcy|ENG|ufr|Ufr|eng|Jcy|jfr|els|ell|egs|Efr|efr|Jfr|uml|kcy|Kcy|Ecy|ecy|kfr|Kfr|lap|Sub|sub|lat|lcy|Lcy|leg|Dot|dot|lEg|leq|les|squ|div|die|lfr|Lfr|lgE|Dfr|dfr|Del|deg|Dcy|dcy|lne|lnE|sol|loz|smt|Cup|lrm|cup|lsh|Lsh|sim|shy|map|Map|mcy|Mcy|mfr|Mfr|mho|gfr|Gfr|sfr|cir|Chi|chi|nap|Cfr|vcy|Vcy|cfr|Scy|scy|ncy|Ncy|vee|Vee|Cap|cap|nfr|scE|sce|Nfr|nge|ngE|nGg|vfr|Vfr|ngt|bot|nGt|nis|niv|Rsh|rsh|nle|nlE|bne|Bfr|bfr|nLl|nlt|nLt|Bcy|bcy|not|Not|rlm|wfr|Wfr|npr|nsc|num|ocy|ast|Ocy|ofr|xfr|Xfr|Ofr|ogt|ohm|apE|olt|Rho|ape|rho|Rfr|rfr|ord|REG|ang|reg|orv|And|and|AMP|Rcy|amp|Afr|ycy|Ycy|yen|yfr|Yfr|rcy|par|pcy|Pcy|pfr|Pfr|phi|Phi|afr|Acy|acy|zcy|Zcy|piv|acE|acd|zfr|Zfr|pre|prE|psi|Psi|qfr|Qfr|zwj|Or|ge|Gg|gt|gg|el|oS|lt|Lt|LT|Re|lg|gl|eg|ne|Im|it|le|DD|wp|wr|nu|Nu|dd|lE|Sc|sc|pi|Pi|ee|af|ll|Ll|rx|gE|xi|pm|Xi|ic|pr|Pr|in|ni|mp|mu|ac|Mu|or|ap|Gt|GT|ii);|&(Aacute|Agrave|Atilde|Ccedil|Eacute|Egrave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;\n\tvar decodeMap = {'aacute':'\\xE1','Aacute':'\\xC1','abreve':'\\u0103','Abreve':'\\u0102','ac':'\\u223E','acd':'\\u223F','acE':'\\u223E\\u0333','acirc':'\\xE2','Acirc':'\\xC2','acute':'\\xB4','acy':'\\u0430','Acy':'\\u0410','aelig':'\\xE6','AElig':'\\xC6','af':'\\u2061','afr':'\\uD835\\uDD1E','Afr':'\\uD835\\uDD04','agrave':'\\xE0','Agrave':'\\xC0','alefsym':'\\u2135','aleph':'\\u2135','alpha':'\\u03B1','Alpha':'\\u0391','amacr':'\\u0101','Amacr':'\\u0100','amalg':'\\u2A3F','amp':'&','AMP':'&','and':'\\u2227','And':'\\u2A53','andand':'\\u2A55','andd':'\\u2A5C','andslope':'\\u2A58','andv':'\\u2A5A','ang':'\\u2220','ange':'\\u29A4','angle':'\\u2220','angmsd':'\\u2221','angmsdaa':'\\u29A8','angmsdab':'\\u29A9','angmsdac':'\\u29AA','angmsdad':'\\u29AB','angmsdae':'\\u29AC','angmsdaf':'\\u29AD','angmsdag':'\\u29AE','angmsdah':'\\u29AF','angrt':'\\u221F','angrtvb':'\\u22BE','angrtvbd':'\\u299D','angsph':'\\u2222','angst':'\\xC5','angzarr':'\\u237C','aogon':'\\u0105','Aogon':'\\u0104','aopf':'\\uD835\\uDD52','Aopf':'\\uD835\\uDD38','ap':'\\u2248','apacir':'\\u2A6F','ape':'\\u224A','apE':'\\u2A70','apid':'\\u224B','apos':'\\'','ApplyFunction':'\\u2061','approx':'\\u2248','approxeq':'\\u224A','aring':'\\xE5','Aring':'\\xC5','ascr':'\\uD835\\uDCB6','Ascr':'\\uD835\\uDC9C','Assign':'\\u2254','ast':'*','asymp':'\\u2248','asympeq':'\\u224D','atilde':'\\xE3','Atilde':'\\xC3','auml':'\\xE4','Auml':'\\xC4','awconint':'\\u2233','awint':'\\u2A11','backcong':'\\u224C','backepsilon':'\\u03F6','backprime':'\\u2035','backsim':'\\u223D','backsimeq':'\\u22CD','Backslash':'\\u2216','Barv':'\\u2AE7','barvee':'\\u22BD','barwed':'\\u2305','Barwed':'\\u2306','barwedge':'\\u2305','bbrk':'\\u23B5','bbrktbrk':'\\u23B6','bcong':'\\u224C','bcy':'\\u0431','Bcy':'\\u0411','bdquo':'\\u201E','becaus':'\\u2235','because':'\\u2235','Because':'\\u2235','bemptyv':'\\u29B0','bepsi':'\\u03F6','bernou':'\\u212C','Bernoullis':'\\u212C','beta':'\\u03B2','Beta':'\\u0392','beth':'\\u2136','between':'\\u226C','bfr':'\\uD835\\uDD1F','Bfr':'\\uD835\\uDD05','bigcap':'\\u22C2','bigcirc':'\\u25EF','bigcup':'\\u22C3','bigodot':'\\u2A00','bigoplus':'\\u2A01','bigotimes':'\\u2A02','bigsqcup':'\\u2A06','bigstar':'\\u2605','bigtriangledown':'\\u25BD','bigtriangleup':'\\u25B3','biguplus':'\\u2A04','bigvee':'\\u22C1','bigwedge':'\\u22C0','bkarow':'\\u290D','blacklozenge':'\\u29EB','blacksquare':'\\u25AA','blacktriangle':'\\u25B4','blacktriangledown':'\\u25BE','blacktriangleleft':'\\u25C2','blacktriangleright':'\\u25B8','blank':'\\u2423','blk12':'\\u2592','blk14':'\\u2591','blk34':'\\u2593','block':'\\u2588','bne':'=\\u20E5','bnequiv':'\\u2261\\u20E5','bnot':'\\u2310','bNot':'\\u2AED','bopf':'\\uD835\\uDD53','Bopf':'\\uD835\\uDD39','bot':'\\u22A5','bottom':'\\u22A5','bowtie':'\\u22C8','boxbox':'\\u29C9','boxdl':'\\u2510','boxdL':'\\u2555','boxDl':'\\u2556','boxDL':'\\u2557','boxdr':'\\u250C','boxdR':'\\u2552','boxDr':'\\u2553','boxDR':'\\u2554','boxh':'\\u2500','boxH':'\\u2550','boxhd':'\\u252C','boxhD':'\\u2565','boxHd':'\\u2564','boxHD':'\\u2566','boxhu':'\\u2534','boxhU':'\\u2568','boxHu':'\\u2567','boxHU':'\\u2569','boxminus':'\\u229F','boxplus':'\\u229E','boxtimes':'\\u22A0','boxul':'\\u2518','boxuL':'\\u255B','boxUl':'\\u255C','boxUL':'\\u255D','boxur':'\\u2514','boxuR':'\\u2558','boxUr':'\\u2559','boxUR':'\\u255A','boxv':'\\u2502','boxV':'\\u2551','boxvh':'\\u253C','boxvH':'\\u256A','boxVh':'\\u256B','boxVH':'\\u256C','boxvl':'\\u2524','boxvL':'\\u2561','boxVl':'\\u2562','boxVL':'\\u2563','boxvr':'\\u251C','boxvR':'\\u255E','boxVr':'\\u255F','boxVR':'\\u2560','bprime':'\\u2035','breve':'\\u02D8','Breve':'\\u02D8','brvbar':'\\xA6','bscr':'\\uD835\\uDCB7','Bscr':'\\u212C','bsemi':'\\u204F','bsim':'\\u223D','bsime':'\\u22CD','bsol':'\\\\','bsolb':'\\u29C5','bsolhsub':'\\u27C8','bull':'\\u2022','bullet':'\\u2022','bump':'\\u224E','bumpe':'\\u224F','bumpE':'\\u2AAE','bumpeq':'\\u224F','Bumpeq':'\\u224E','cacute':'\\u0107','Cacute':'\\u0106','cap':'\\u2229','Cap':'\\u22D2','capand':'\\u2A44','capbrcup':'\\u2A49','capcap':'\\u2A4B','capcup':'\\u2A47','capdot':'\\u2A40','CapitalDifferentialD':'\\u2145','caps':'\\u2229\\uFE00','caret':'\\u2041','caron':'\\u02C7','Cayleys':'\\u212D','ccaps':'\\u2A4D','ccaron':'\\u010D','Ccaron':'\\u010C','ccedil':'\\xE7','Ccedil':'\\xC7','ccirc':'\\u0109','Ccirc':'\\u0108','Cconint':'\\u2230','ccups':'\\u2A4C','ccupssm':'\\u2A50','cdot':'\\u010B','Cdot':'\\u010A','cedil':'\\xB8','Cedilla':'\\xB8','cemptyv':'\\u29B2','cent':'\\xA2','centerdot':'\\xB7','CenterDot':'\\xB7','cfr':'\\uD835\\uDD20','Cfr':'\\u212D','chcy':'\\u0447','CHcy':'\\u0427','check':'\\u2713','checkmark':'\\u2713','chi':'\\u03C7','Chi':'\\u03A7','cir':'\\u25CB','circ':'\\u02C6','circeq':'\\u2257','circlearrowleft':'\\u21BA','circlearrowright':'\\u21BB','circledast':'\\u229B','circledcirc':'\\u229A','circleddash':'\\u229D','CircleDot':'\\u2299','circledR':'\\xAE','circledS':'\\u24C8','CircleMinus':'\\u2296','CirclePlus':'\\u2295','CircleTimes':'\\u2297','cire':'\\u2257','cirE':'\\u29C3','cirfnint':'\\u2A10','cirmid':'\\u2AEF','cirscir':'\\u29C2','ClockwiseContourIntegral':'\\u2232','CloseCurlyDoubleQuote':'\\u201D','CloseCurlyQuote':'\\u2019','clubs':'\\u2663','clubsuit':'\\u2663','colon':':','Colon':'\\u2237','colone':'\\u2254','Colone':'\\u2A74','coloneq':'\\u2254','comma':',','commat':'@','comp':'\\u2201','compfn':'\\u2218','complement':'\\u2201','complexes':'\\u2102','cong':'\\u2245','congdot':'\\u2A6D','Congruent':'\\u2261','conint':'\\u222E','Conint':'\\u222F','ContourIntegral':'\\u222E','copf':'\\uD835\\uDD54','Copf':'\\u2102','coprod':'\\u2210','Coproduct':'\\u2210','copy':'\\xA9','COPY':'\\xA9','copysr':'\\u2117','CounterClockwiseContourIntegral':'\\u2233','crarr':'\\u21B5','cross':'\\u2717','Cross':'\\u2A2F','cscr':'\\uD835\\uDCB8','Cscr':'\\uD835\\uDC9E','csub':'\\u2ACF','csube':'\\u2AD1','csup':'\\u2AD0','csupe':'\\u2AD2','ctdot':'\\u22EF','cudarrl':'\\u2938','cudarrr':'\\u2935','cuepr':'\\u22DE','cuesc':'\\u22DF','cularr':'\\u21B6','cularrp':'\\u293D','cup':'\\u222A','Cup':'\\u22D3','cupbrcap':'\\u2A48','cupcap':'\\u2A46','CupCap':'\\u224D','cupcup':'\\u2A4A','cupdot':'\\u228D','cupor':'\\u2A45','cups':'\\u222A\\uFE00','curarr':'\\u21B7','curarrm':'\\u293C','curlyeqprec':'\\u22DE','curlyeqsucc':'\\u22DF','curlyvee':'\\u22CE','curlywedge':'\\u22CF','curren':'\\xA4','curvearrowleft':'\\u21B6','curvearrowright':'\\u21B7','cuvee':'\\u22CE','cuwed':'\\u22CF','cwconint':'\\u2232','cwint':'\\u2231','cylcty':'\\u232D','dagger':'\\u2020','Dagger':'\\u2021','daleth':'\\u2138','darr':'\\u2193','dArr':'\\u21D3','Darr':'\\u21A1','dash':'\\u2010','dashv':'\\u22A3','Dashv':'\\u2AE4','dbkarow':'\\u290F','dblac':'\\u02DD','dcaron':'\\u010F','Dcaron':'\\u010E','dcy':'\\u0434','Dcy':'\\u0414','dd':'\\u2146','DD':'\\u2145','ddagger':'\\u2021','ddarr':'\\u21CA','DDotrahd':'\\u2911','ddotseq':'\\u2A77','deg':'\\xB0','Del':'\\u2207','delta':'\\u03B4','Delta':'\\u0394','demptyv':'\\u29B1','dfisht':'\\u297F','dfr':'\\uD835\\uDD21','Dfr':'\\uD835\\uDD07','dHar':'\\u2965','dharl':'\\u21C3','dharr':'\\u21C2','DiacriticalAcute':'\\xB4','DiacriticalDot':'\\u02D9','DiacriticalDoubleAcute':'\\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\\u02DC','diam':'\\u22C4','diamond':'\\u22C4','Diamond':'\\u22C4','diamondsuit':'\\u2666','diams':'\\u2666','die':'\\xA8','DifferentialD':'\\u2146','digamma':'\\u03DD','disin':'\\u22F2','div':'\\xF7','divide':'\\xF7','divideontimes':'\\u22C7','divonx':'\\u22C7','djcy':'\\u0452','DJcy':'\\u0402','dlcorn':'\\u231E','dlcrop':'\\u230D','dollar':'$','dopf':'\\uD835\\uDD55','Dopf':'\\uD835\\uDD3B','dot':'\\u02D9','Dot':'\\xA8','DotDot':'\\u20DC','doteq':'\\u2250','doteqdot':'\\u2251','DotEqual':'\\u2250','dotminus':'\\u2238','dotplus':'\\u2214','dotsquare':'\\u22A1','doublebarwedge':'\\u2306','DoubleContourIntegral':'\\u222F','DoubleDot':'\\xA8','DoubleDownArrow':'\\u21D3','DoubleLeftArrow':'\\u21D0','DoubleLeftRightArrow':'\\u21D4','DoubleLeftTee':'\\u2AE4','DoubleLongLeftArrow':'\\u27F8','DoubleLongLeftRightArrow':'\\u27FA','DoubleLongRightArrow':'\\u27F9','DoubleRightArrow':'\\u21D2','DoubleRightTee':'\\u22A8','DoubleUpArrow':'\\u21D1','DoubleUpDownArrow':'\\u21D5','DoubleVerticalBar':'\\u2225','downarrow':'\\u2193','Downarrow':'\\u21D3','DownArrow':'\\u2193','DownArrowBar':'\\u2913','DownArrowUpArrow':'\\u21F5','DownBreve':'\\u0311','downdownarrows':'\\u21CA','downharpoonleft':'\\u21C3','downharpoonright':'\\u21C2','DownLeftRightVector':'\\u2950','DownLeftTeeVector':'\\u295E','DownLeftVector':'\\u21BD','DownLeftVectorBar':'\\u2956','DownRightTeeVector':'\\u295F','DownRightVector':'\\u21C1','DownRightVectorBar':'\\u2957','DownTee':'\\u22A4','DownTeeArrow':'\\u21A7','drbkarow':'\\u2910','drcorn':'\\u231F','drcrop':'\\u230C','dscr':'\\uD835\\uDCB9','Dscr':'\\uD835\\uDC9F','dscy':'\\u0455','DScy':'\\u0405','dsol':'\\u29F6','dstrok':'\\u0111','Dstrok':'\\u0110','dtdot':'\\u22F1','dtri':'\\u25BF','dtrif':'\\u25BE','duarr':'\\u21F5','duhar':'\\u296F','dwangle':'\\u29A6','dzcy':'\\u045F','DZcy':'\\u040F','dzigrarr':'\\u27FF','eacute':'\\xE9','Eacute':'\\xC9','easter':'\\u2A6E','ecaron':'\\u011B','Ecaron':'\\u011A','ecir':'\\u2256','ecirc':'\\xEA','Ecirc':'\\xCA','ecolon':'\\u2255','ecy':'\\u044D','Ecy':'\\u042D','eDDot':'\\u2A77','edot':'\\u0117','eDot':'\\u2251','Edot':'\\u0116','ee':'\\u2147','efDot':'\\u2252','efr':'\\uD835\\uDD22','Efr':'\\uD835\\uDD08','eg':'\\u2A9A','egrave':'\\xE8','Egrave':'\\xC8','egs':'\\u2A96','egsdot':'\\u2A98','el':'\\u2A99','Element':'\\u2208','elinters':'\\u23E7','ell':'\\u2113','els':'\\u2A95','elsdot':'\\u2A97','emacr':'\\u0113','Emacr':'\\u0112','empty':'\\u2205','emptyset':'\\u2205','EmptySmallSquare':'\\u25FB','emptyv':'\\u2205','EmptyVerySmallSquare':'\\u25AB','emsp':'\\u2003','emsp13':'\\u2004','emsp14':'\\u2005','eng':'\\u014B','ENG':'\\u014A','ensp':'\\u2002','eogon':'\\u0119','Eogon':'\\u0118','eopf':'\\uD835\\uDD56','Eopf':'\\uD835\\uDD3C','epar':'\\u22D5','eparsl':'\\u29E3','eplus':'\\u2A71','epsi':'\\u03B5','epsilon':'\\u03B5','Epsilon':'\\u0395','epsiv':'\\u03F5','eqcirc':'\\u2256','eqcolon':'\\u2255','eqsim':'\\u2242','eqslantgtr':'\\u2A96','eqslantless':'\\u2A95','Equal':'\\u2A75','equals':'=','EqualTilde':'\\u2242','equest':'\\u225F','Equilibrium':'\\u21CC','equiv':'\\u2261','equivDD':'\\u2A78','eqvparsl':'\\u29E5','erarr':'\\u2971','erDot':'\\u2253','escr':'\\u212F','Escr':'\\u2130','esdot':'\\u2250','esim':'\\u2242','Esim':'\\u2A73','eta':'\\u03B7','Eta':'\\u0397','eth':'\\xF0','ETH':'\\xD0','euml':'\\xEB','Euml':'\\xCB','euro':'\\u20AC','excl':'!','exist':'\\u2203','Exists':'\\u2203','expectation':'\\u2130','exponentiale':'\\u2147','ExponentialE':'\\u2147','fallingdotseq':'\\u2252','fcy':'\\u0444','Fcy':'\\u0424','female':'\\u2640','ffilig':'\\uFB03','fflig':'\\uFB00','ffllig':'\\uFB04','ffr':'\\uD835\\uDD23','Ffr':'\\uD835\\uDD09','filig':'\\uFB01','FilledSmallSquare':'\\u25FC','FilledVerySmallSquare':'\\u25AA','fjlig':'fj','flat':'\\u266D','fllig':'\\uFB02','fltns':'\\u25B1','fnof':'\\u0192','fopf':'\\uD835\\uDD57','Fopf':'\\uD835\\uDD3D','forall':'\\u2200','ForAll':'\\u2200','fork':'\\u22D4','forkv':'\\u2AD9','Fouriertrf':'\\u2131','fpartint':'\\u2A0D','frac12':'\\xBD','frac13':'\\u2153','frac14':'\\xBC','frac15':'\\u2155','frac16':'\\u2159','frac18':'\\u215B','frac23':'\\u2154','frac25':'\\u2156','frac34':'\\xBE','frac35':'\\u2157','frac38':'\\u215C','frac45':'\\u2158','frac56':'\\u215A','frac58':'\\u215D','frac78':'\\u215E','frasl':'\\u2044','frown':'\\u2322','fscr':'\\uD835\\uDCBB','Fscr':'\\u2131','gacute':'\\u01F5','gamma':'\\u03B3','Gamma':'\\u0393','gammad':'\\u03DD','Gammad':'\\u03DC','gap':'\\u2A86','gbreve':'\\u011F','Gbreve':'\\u011E','Gcedil':'\\u0122','gcirc':'\\u011D','Gcirc':'\\u011C','gcy':'\\u0433','Gcy':'\\u0413','gdot':'\\u0121','Gdot':'\\u0120','ge':'\\u2265','gE':'\\u2267','gel':'\\u22DB','gEl':'\\u2A8C','geq':'\\u2265','geqq':'\\u2267','geqslant':'\\u2A7E','ges':'\\u2A7E','gescc':'\\u2AA9','gesdot':'\\u2A80','gesdoto':'\\u2A82','gesdotol':'\\u2A84','gesl':'\\u22DB\\uFE00','gesles':'\\u2A94','gfr':'\\uD835\\uDD24','Gfr':'\\uD835\\uDD0A','gg':'\\u226B','Gg':'\\u22D9','ggg':'\\u22D9','gimel':'\\u2137','gjcy':'\\u0453','GJcy':'\\u0403','gl':'\\u2277','gla':'\\u2AA5','glE':'\\u2A92','glj':'\\u2AA4','gnap':'\\u2A8A','gnapprox':'\\u2A8A','gne':'\\u2A88','gnE':'\\u2269','gneq':'\\u2A88','gneqq':'\\u2269','gnsim':'\\u22E7','gopf':'\\uD835\\uDD58','Gopf':'\\uD835\\uDD3E','grave':'`','GreaterEqual':'\\u2265','GreaterEqualLess':'\\u22DB','GreaterFullEqual':'\\u2267','GreaterGreater':'\\u2AA2','GreaterLess':'\\u2277','GreaterSlantEqual':'\\u2A7E','GreaterTilde':'\\u2273','gscr':'\\u210A','Gscr':'\\uD835\\uDCA2','gsim':'\\u2273','gsime':'\\u2A8E','gsiml':'\\u2A90','gt':'>','Gt':'\\u226B','GT':'>','gtcc':'\\u2AA7','gtcir':'\\u2A7A','gtdot':'\\u22D7','gtlPar':'\\u2995','gtquest':'\\u2A7C','gtrapprox':'\\u2A86','gtrarr':'\\u2978','gtrdot':'\\u22D7','gtreqless':'\\u22DB','gtreqqless':'\\u2A8C','gtrless':'\\u2277','gtrsim':'\\u2273','gvertneqq':'\\u2269\\uFE00','gvnE':'\\u2269\\uFE00','Hacek':'\\u02C7','hairsp':'\\u200A','half':'\\xBD','hamilt':'\\u210B','hardcy':'\\u044A','HARDcy':'\\u042A','harr':'\\u2194','hArr':'\\u21D4','harrcir':'\\u2948','harrw':'\\u21AD','Hat':'^','hbar':'\\u210F','hcirc':'\\u0125','Hcirc':'\\u0124','hearts':'\\u2665','heartsuit':'\\u2665','hellip':'\\u2026','hercon':'\\u22B9','hfr':'\\uD835\\uDD25','Hfr':'\\u210C','HilbertSpace':'\\u210B','hksearow':'\\u2925','hkswarow':'\\u2926','hoarr':'\\u21FF','homtht':'\\u223B','hookleftarrow':'\\u21A9','hookrightarrow':'\\u21AA','hopf':'\\uD835\\uDD59','Hopf':'\\u210D','horbar':'\\u2015','HorizontalLine':'\\u2500','hscr':'\\uD835\\uDCBD','Hscr':'\\u210B','hslash':'\\u210F','hstrok':'\\u0127','Hstrok':'\\u0126','HumpDownHump':'\\u224E','HumpEqual':'\\u224F','hybull':'\\u2043','hyphen':'\\u2010','iacute':'\\xED','Iacute':'\\xCD','ic':'\\u2063','icirc':'\\xEE','Icirc':'\\xCE','icy':'\\u0438','Icy':'\\u0418','Idot':'\\u0130','iecy':'\\u0435','IEcy':'\\u0415','iexcl':'\\xA1','iff':'\\u21D4','ifr':'\\uD835\\uDD26','Ifr':'\\u2111','igrave':'\\xEC','Igrave':'\\xCC','ii':'\\u2148','iiiint':'\\u2A0C','iiint':'\\u222D','iinfin':'\\u29DC','iiota':'\\u2129','ijlig':'\\u0133','IJlig':'\\u0132','Im':'\\u2111','imacr':'\\u012B','Imacr':'\\u012A','image':'\\u2111','ImaginaryI':'\\u2148','imagline':'\\u2110','imagpart':'\\u2111','imath':'\\u0131','imof':'\\u22B7','imped':'\\u01B5','Implies':'\\u21D2','in':'\\u2208','incare':'\\u2105','infin':'\\u221E','infintie':'\\u29DD','inodot':'\\u0131','int':'\\u222B','Int':'\\u222C','intcal':'\\u22BA','integers':'\\u2124','Integral':'\\u222B','intercal':'\\u22BA','Intersection':'\\u22C2','intlarhk':'\\u2A17','intprod':'\\u2A3C','InvisibleComma':'\\u2063','InvisibleTimes':'\\u2062','iocy':'\\u0451','IOcy':'\\u0401','iogon':'\\u012F','Iogon':'\\u012E','iopf':'\\uD835\\uDD5A','Iopf':'\\uD835\\uDD40','iota':'\\u03B9','Iota':'\\u0399','iprod':'\\u2A3C','iquest':'\\xBF','iscr':'\\uD835\\uDCBE','Iscr':'\\u2110','isin':'\\u2208','isindot':'\\u22F5','isinE':'\\u22F9','isins':'\\u22F4','isinsv':'\\u22F3','isinv':'\\u2208','it':'\\u2062','itilde':'\\u0129','Itilde':'\\u0128','iukcy':'\\u0456','Iukcy':'\\u0406','iuml':'\\xEF','Iuml':'\\xCF','jcirc':'\\u0135','Jcirc':'\\u0134','jcy':'\\u0439','Jcy':'\\u0419','jfr':'\\uD835\\uDD27','Jfr':'\\uD835\\uDD0D','jmath':'\\u0237','jopf':'\\uD835\\uDD5B','Jopf':'\\uD835\\uDD41','jscr':'\\uD835\\uDCBF','Jscr':'\\uD835\\uDCA5','jsercy':'\\u0458','Jsercy':'\\u0408','jukcy':'\\u0454','Jukcy':'\\u0404','kappa':'\\u03BA','Kappa':'\\u039A','kappav':'\\u03F0','kcedil':'\\u0137','Kcedil':'\\u0136','kcy':'\\u043A','Kcy':'\\u041A','kfr':'\\uD835\\uDD28','Kfr':'\\uD835\\uDD0E','kgreen':'\\u0138','khcy':'\\u0445','KHcy':'\\u0425','kjcy':'\\u045C','KJcy':'\\u040C','kopf':'\\uD835\\uDD5C','Kopf':'\\uD835\\uDD42','kscr':'\\uD835\\uDCC0','Kscr':'\\uD835\\uDCA6','lAarr':'\\u21DA','lacute':'\\u013A','Lacute':'\\u0139','laemptyv':'\\u29B4','lagran':'\\u2112','lambda':'\\u03BB','Lambda':'\\u039B','lang':'\\u27E8','Lang':'\\u27EA','langd':'\\u2991','langle':'\\u27E8','lap':'\\u2A85','Laplacetrf':'\\u2112','laquo':'\\xAB','larr':'\\u2190','lArr':'\\u21D0','Larr':'\\u219E','larrb':'\\u21E4','larrbfs':'\\u291F','larrfs':'\\u291D','larrhk':'\\u21A9','larrlp':'\\u21AB','larrpl':'\\u2939','larrsim':'\\u2973','larrtl':'\\u21A2','lat':'\\u2AAB','latail':'\\u2919','lAtail':'\\u291B','late':'\\u2AAD','lates':'\\u2AAD\\uFE00','lbarr':'\\u290C','lBarr':'\\u290E','lbbrk':'\\u2772','lbrace':'{','lbrack':'[','lbrke':'\\u298B','lbrksld':'\\u298F','lbrkslu':'\\u298D','lcaron':'\\u013E','Lcaron':'\\u013D','lcedil':'\\u013C','Lcedil':'\\u013B','lceil':'\\u2308','lcub':'{','lcy':'\\u043B','Lcy':'\\u041B','ldca':'\\u2936','ldquo':'\\u201C','ldquor':'\\u201E','ldrdhar':'\\u2967','ldrushar':'\\u294B','ldsh':'\\u21B2','le':'\\u2264','lE':'\\u2266','LeftAngleBracket':'\\u27E8','leftarrow':'\\u2190','Leftarrow':'\\u21D0','LeftArrow':'\\u2190','LeftArrowBar':'\\u21E4','LeftArrowRightArrow':'\\u21C6','leftarrowtail':'\\u21A2','LeftCeiling':'\\u2308','LeftDoubleBracket':'\\u27E6','LeftDownTeeVector':'\\u2961','LeftDownVector':'\\u21C3','LeftDownVectorBar':'\\u2959','LeftFloor':'\\u230A','leftharpoondown':'\\u21BD','leftharpoonup':'\\u21BC','leftleftarrows':'\\u21C7','leftrightarrow':'\\u2194','Leftrightarrow':'\\u21D4','LeftRightArrow':'\\u2194','leftrightarrows':'\\u21C6','leftrightharpoons':'\\u21CB','leftrightsquigarrow':'\\u21AD','LeftRightVector':'\\u294E','LeftTee':'\\u22A3','LeftTeeArrow':'\\u21A4','LeftTeeVector':'\\u295A','leftthreetimes':'\\u22CB','LeftTriangle':'\\u22B2','LeftTriangleBar':'\\u29CF','LeftTriangleEqual':'\\u22B4','LeftUpDownVector':'\\u2951','LeftUpTeeVector':'\\u2960','LeftUpVector':'\\u21BF','LeftUpVectorBar':'\\u2958','LeftVector':'\\u21BC','LeftVectorBar':'\\u2952','leg':'\\u22DA','lEg':'\\u2A8B','leq':'\\u2264','leqq':'\\u2266','leqslant':'\\u2A7D','les':'\\u2A7D','lescc':'\\u2AA8','lesdot':'\\u2A7F','lesdoto':'\\u2A81','lesdotor':'\\u2A83','lesg':'\\u22DA\\uFE00','lesges':'\\u2A93','lessapprox':'\\u2A85','lessdot':'\\u22D6','lesseqgtr':'\\u22DA','lesseqqgtr':'\\u2A8B','LessEqualGreater':'\\u22DA','LessFullEqual':'\\u2266','LessGreater':'\\u2276','lessgtr':'\\u2276','LessLess':'\\u2AA1','lesssim':'\\u2272','LessSlantEqual':'\\u2A7D','LessTilde':'\\u2272','lfisht':'\\u297C','lfloor':'\\u230A','lfr':'\\uD835\\uDD29','Lfr':'\\uD835\\uDD0F','lg':'\\u2276','lgE':'\\u2A91','lHar':'\\u2962','lhard':'\\u21BD','lharu':'\\u21BC','lharul':'\\u296A','lhblk':'\\u2584','ljcy':'\\u0459','LJcy':'\\u0409','ll':'\\u226A','Ll':'\\u22D8','llarr':'\\u21C7','llcorner':'\\u231E','Lleftarrow':'\\u21DA','llhard':'\\u296B','lltri':'\\u25FA','lmidot':'\\u0140','Lmidot':'\\u013F','lmoust':'\\u23B0','lmoustache':'\\u23B0','lnap':'\\u2A89','lnapprox':'\\u2A89','lne':'\\u2A87','lnE':'\\u2268','lneq':'\\u2A87','lneqq':'\\u2268','lnsim':'\\u22E6','loang':'\\u27EC','loarr':'\\u21FD','lobrk':'\\u27E6','longleftarrow':'\\u27F5','Longleftarrow':'\\u27F8','LongLeftArrow':'\\u27F5','longleftrightarrow':'\\u27F7','Longleftrightarrow':'\\u27FA','LongLeftRightArrow':'\\u27F7','longmapsto':'\\u27FC','longrightarrow':'\\u27F6','Longrightarrow':'\\u27F9','LongRightArrow':'\\u27F6','looparrowleft':'\\u21AB','looparrowright':'\\u21AC','lopar':'\\u2985','lopf':'\\uD835\\uDD5D','Lopf':'\\uD835\\uDD43','loplus':'\\u2A2D','lotimes':'\\u2A34','lowast':'\\u2217','lowbar':'_','LowerLeftArrow':'\\u2199','LowerRightArrow':'\\u2198','loz':'\\u25CA','lozenge':'\\u25CA','lozf':'\\u29EB','lpar':'(','lparlt':'\\u2993','lrarr':'\\u21C6','lrcorner':'\\u231F','lrhar':'\\u21CB','lrhard':'\\u296D','lrm':'\\u200E','lrtri':'\\u22BF','lsaquo':'\\u2039','lscr':'\\uD835\\uDCC1','Lscr':'\\u2112','lsh':'\\u21B0','Lsh':'\\u21B0','lsim':'\\u2272','lsime':'\\u2A8D','lsimg':'\\u2A8F','lsqb':'[','lsquo':'\\u2018','lsquor':'\\u201A','lstrok':'\\u0142','Lstrok':'\\u0141','lt':'<','Lt':'\\u226A','LT':'<','ltcc':'\\u2AA6','ltcir':'\\u2A79','ltdot':'\\u22D6','lthree':'\\u22CB','ltimes':'\\u22C9','ltlarr':'\\u2976','ltquest':'\\u2A7B','ltri':'\\u25C3','ltrie':'\\u22B4','ltrif':'\\u25C2','ltrPar':'\\u2996','lurdshar':'\\u294A','luruhar':'\\u2966','lvertneqq':'\\u2268\\uFE00','lvnE':'\\u2268\\uFE00','macr':'\\xAF','male':'\\u2642','malt':'\\u2720','maltese':'\\u2720','map':'\\u21A6','Map':'\\u2905','mapsto':'\\u21A6','mapstodown':'\\u21A7','mapstoleft':'\\u21A4','mapstoup':'\\u21A5','marker':'\\u25AE','mcomma':'\\u2A29','mcy':'\\u043C','Mcy':'\\u041C','mdash':'\\u2014','mDDot':'\\u223A','measuredangle':'\\u2221','MediumSpace':'\\u205F','Mellintrf':'\\u2133','mfr':'\\uD835\\uDD2A','Mfr':'\\uD835\\uDD10','mho':'\\u2127','micro':'\\xB5','mid':'\\u2223','midast':'*','midcir':'\\u2AF0','middot':'\\xB7','minus':'\\u2212','minusb':'\\u229F','minusd':'\\u2238','minusdu':'\\u2A2A','MinusPlus':'\\u2213','mlcp':'\\u2ADB','mldr':'\\u2026','mnplus':'\\u2213','models':'\\u22A7','mopf':'\\uD835\\uDD5E','Mopf':'\\uD835\\uDD44','mp':'\\u2213','mscr':'\\uD835\\uDCC2','Mscr':'\\u2133','mstpos':'\\u223E','mu':'\\u03BC','Mu':'\\u039C','multimap':'\\u22B8','mumap':'\\u22B8','nabla':'\\u2207','nacute':'\\u0144','Nacute':'\\u0143','nang':'\\u2220\\u20D2','nap':'\\u2249','napE':'\\u2A70\\u0338','napid':'\\u224B\\u0338','napos':'\\u0149','napprox':'\\u2249','natur':'\\u266E','natural':'\\u266E','naturals':'\\u2115','nbsp':'\\xA0','nbump':'\\u224E\\u0338','nbumpe':'\\u224F\\u0338','ncap':'\\u2A43','ncaron':'\\u0148','Ncaron':'\\u0147','ncedil':'\\u0146','Ncedil':'\\u0145','ncong':'\\u2247','ncongdot':'\\u2A6D\\u0338','ncup':'\\u2A42','ncy':'\\u043D','Ncy':'\\u041D','ndash':'\\u2013','ne':'\\u2260','nearhk':'\\u2924','nearr':'\\u2197','neArr':'\\u21D7','nearrow':'\\u2197','nedot':'\\u2250\\u0338','NegativeMediumSpace':'\\u200B','NegativeThickSpace':'\\u200B','NegativeThinSpace':'\\u200B','NegativeVeryThinSpace':'\\u200B','nequiv':'\\u2262','nesear':'\\u2928','nesim':'\\u2242\\u0338','NestedGreaterGreater':'\\u226B','NestedLessLess':'\\u226A','NewLine':'\\n','nexist':'\\u2204','nexists':'\\u2204','nfr':'\\uD835\\uDD2B','Nfr':'\\uD835\\uDD11','nge':'\\u2271','ngE':'\\u2267\\u0338','ngeq':'\\u2271','ngeqq':'\\u2267\\u0338','ngeqslant':'\\u2A7E\\u0338','nges':'\\u2A7E\\u0338','nGg':'\\u22D9\\u0338','ngsim':'\\u2275','ngt':'\\u226F','nGt':'\\u226B\\u20D2','ngtr':'\\u226F','nGtv':'\\u226B\\u0338','nharr':'\\u21AE','nhArr':'\\u21CE','nhpar':'\\u2AF2','ni':'\\u220B','nis':'\\u22FC','nisd':'\\u22FA','niv':'\\u220B','njcy':'\\u045A','NJcy':'\\u040A','nlarr':'\\u219A','nlArr':'\\u21CD','nldr':'\\u2025','nle':'\\u2270','nlE':'\\u2266\\u0338','nleftarrow':'\\u219A','nLeftarrow':'\\u21CD','nleftrightarrow':'\\u21AE','nLeftrightarrow':'\\u21CE','nleq':'\\u2270','nleqq':'\\u2266\\u0338','nleqslant':'\\u2A7D\\u0338','nles':'\\u2A7D\\u0338','nless':'\\u226E','nLl':'\\u22D8\\u0338','nlsim':'\\u2274','nlt':'\\u226E','nLt':'\\u226A\\u20D2','nltri':'\\u22EA','nltrie':'\\u22EC','nLtv':'\\u226A\\u0338','nmid':'\\u2224','NoBreak':'\\u2060','NonBreakingSpace':'\\xA0','nopf':'\\uD835\\uDD5F','Nopf':'\\u2115','not':'\\xAC','Not':'\\u2AEC','NotCongruent':'\\u2262','NotCupCap':'\\u226D','NotDoubleVerticalBar':'\\u2226','NotElement':'\\u2209','NotEqual':'\\u2260','NotEqualTilde':'\\u2242\\u0338','NotExists':'\\u2204','NotGreater':'\\u226F','NotGreaterEqual':'\\u2271','NotGreaterFullEqual':'\\u2267\\u0338','NotGreaterGreater':'\\u226B\\u0338','NotGreaterLess':'\\u2279','NotGreaterSlantEqual':'\\u2A7E\\u0338','NotGreaterTilde':'\\u2275','NotHumpDownHump':'\\u224E\\u0338','NotHumpEqual':'\\u224F\\u0338','notin':'\\u2209','notindot':'\\u22F5\\u0338','notinE':'\\u22F9\\u0338','notinva':'\\u2209','notinvb':'\\u22F7','notinvc':'\\u22F6','NotLeftTriangle':'\\u22EA','NotLeftTriangleBar':'\\u29CF\\u0338','NotLeftTriangleEqual':'\\u22EC','NotLess':'\\u226E','NotLessEqual':'\\u2270','NotLessGreater':'\\u2278','NotLessLess':'\\u226A\\u0338','NotLessSlantEqual':'\\u2A7D\\u0338','NotLessTilde':'\\u2274','NotNestedGreaterGreater':'\\u2AA2\\u0338','NotNestedLessLess':'\\u2AA1\\u0338','notni':'\\u220C','notniva':'\\u220C','notnivb':'\\u22FE','notnivc':'\\u22FD','NotPrecedes':'\\u2280','NotPrecedesEqual':'\\u2AAF\\u0338','NotPrecedesSlantEqual':'\\u22E0','NotReverseElement':'\\u220C','NotRightTriangle':'\\u22EB','NotRightTriangleBar':'\\u29D0\\u0338','NotRightTriangleEqual':'\\u22ED','NotSquareSubset':'\\u228F\\u0338','NotSquareSubsetEqual':'\\u22E2','NotSquareSuperset':'\\u2290\\u0338','NotSquareSupersetEqual':'\\u22E3','NotSubset':'\\u2282\\u20D2','NotSubsetEqual':'\\u2288','NotSucceeds':'\\u2281','NotSucceedsEqual':'\\u2AB0\\u0338','NotSucceedsSlantEqual':'\\u22E1','NotSucceedsTilde':'\\u227F\\u0338','NotSuperset':'\\u2283\\u20D2','NotSupersetEqual':'\\u2289','NotTilde':'\\u2241','NotTildeEqual':'\\u2244','NotTildeFullEqual':'\\u2247','NotTildeTilde':'\\u2249','NotVerticalBar':'\\u2224','npar':'\\u2226','nparallel':'\\u2226','nparsl':'\\u2AFD\\u20E5','npart':'\\u2202\\u0338','npolint':'\\u2A14','npr':'\\u2280','nprcue':'\\u22E0','npre':'\\u2AAF\\u0338','nprec':'\\u2280','npreceq':'\\u2AAF\\u0338','nrarr':'\\u219B','nrArr':'\\u21CF','nrarrc':'\\u2933\\u0338','nrarrw':'\\u219D\\u0338','nrightarrow':'\\u219B','nRightarrow':'\\u21CF','nrtri':'\\u22EB','nrtrie':'\\u22ED','nsc':'\\u2281','nsccue':'\\u22E1','nsce':'\\u2AB0\\u0338','nscr':'\\uD835\\uDCC3','Nscr':'\\uD835\\uDCA9','nshortmid':'\\u2224','nshortparallel':'\\u2226','nsim':'\\u2241','nsime':'\\u2244','nsimeq':'\\u2244','nsmid':'\\u2224','nspar':'\\u2226','nsqsube':'\\u22E2','nsqsupe':'\\u22E3','nsub':'\\u2284','nsube':'\\u2288','nsubE':'\\u2AC5\\u0338','nsubset':'\\u2282\\u20D2','nsubseteq':'\\u2288','nsubseteqq':'\\u2AC5\\u0338','nsucc':'\\u2281','nsucceq':'\\u2AB0\\u0338','nsup':'\\u2285','nsupe':'\\u2289','nsupE':'\\u2AC6\\u0338','nsupset':'\\u2283\\u20D2','nsupseteq':'\\u2289','nsupseteqq':'\\u2AC6\\u0338','ntgl':'\\u2279','ntilde':'\\xF1','Ntilde':'\\xD1','ntlg':'\\u2278','ntriangleleft':'\\u22EA','ntrianglelefteq':'\\u22EC','ntriangleright':'\\u22EB','ntrianglerighteq':'\\u22ED','nu':'\\u03BD','Nu':'\\u039D','num':'#','numero':'\\u2116','numsp':'\\u2007','nvap':'\\u224D\\u20D2','nvdash':'\\u22AC','nvDash':'\\u22AD','nVdash':'\\u22AE','nVDash':'\\u22AF','nvge':'\\u2265\\u20D2','nvgt':'>\\u20D2','nvHarr':'\\u2904','nvinfin':'\\u29DE','nvlArr':'\\u2902','nvle':'\\u2264\\u20D2','nvlt':'<\\u20D2','nvltrie':'\\u22B4\\u20D2','nvrArr':'\\u2903','nvrtrie':'\\u22B5\\u20D2','nvsim':'\\u223C\\u20D2','nwarhk':'\\u2923','nwarr':'\\u2196','nwArr':'\\u21D6','nwarrow':'\\u2196','nwnear':'\\u2927','oacute':'\\xF3','Oacute':'\\xD3','oast':'\\u229B','ocir':'\\u229A','ocirc':'\\xF4','Ocirc':'\\xD4','ocy':'\\u043E','Ocy':'\\u041E','odash':'\\u229D','odblac':'\\u0151','Odblac':'\\u0150','odiv':'\\u2A38','odot':'\\u2299','odsold':'\\u29BC','oelig':'\\u0153','OElig':'\\u0152','ofcir':'\\u29BF','ofr':'\\uD835\\uDD2C','Ofr':'\\uD835\\uDD12','ogon':'\\u02DB','ograve':'\\xF2','Ograve':'\\xD2','ogt':'\\u29C1','ohbar':'\\u29B5','ohm':'\\u03A9','oint':'\\u222E','olarr':'\\u21BA','olcir':'\\u29BE','olcross':'\\u29BB','oline':'\\u203E','olt':'\\u29C0','omacr':'\\u014D','Omacr':'\\u014C','omega':'\\u03C9','Omega':'\\u03A9','omicron':'\\u03BF','Omicron':'\\u039F','omid':'\\u29B6','ominus':'\\u2296','oopf':'\\uD835\\uDD60','Oopf':'\\uD835\\uDD46','opar':'\\u29B7','OpenCurlyDoubleQuote':'\\u201C','OpenCurlyQuote':'\\u2018','operp':'\\u29B9','oplus':'\\u2295','or':'\\u2228','Or':'\\u2A54','orarr':'\\u21BB','ord':'\\u2A5D','order':'\\u2134','orderof':'\\u2134','ordf':'\\xAA','ordm':'\\xBA','origof':'\\u22B6','oror':'\\u2A56','orslope':'\\u2A57','orv':'\\u2A5B','oS':'\\u24C8','oscr':'\\u2134','Oscr':'\\uD835\\uDCAA','oslash':'\\xF8','Oslash':'\\xD8','osol':'\\u2298','otilde':'\\xF5','Otilde':'\\xD5','otimes':'\\u2297','Otimes':'\\u2A37','otimesas':'\\u2A36','ouml':'\\xF6','Ouml':'\\xD6','ovbar':'\\u233D','OverBar':'\\u203E','OverBrace':'\\u23DE','OverBracket':'\\u23B4','OverParenthesis':'\\u23DC','par':'\\u2225','para':'\\xB6','parallel':'\\u2225','parsim':'\\u2AF3','parsl':'\\u2AFD','part':'\\u2202','PartialD':'\\u2202','pcy':'\\u043F','Pcy':'\\u041F','percnt':'%','period':'.','permil':'\\u2030','perp':'\\u22A5','pertenk':'\\u2031','pfr':'\\uD835\\uDD2D','Pfr':'\\uD835\\uDD13','phi':'\\u03C6','Phi':'\\u03A6','phiv':'\\u03D5','phmmat':'\\u2133','phone':'\\u260E','pi':'\\u03C0','Pi':'\\u03A0','pitchfork':'\\u22D4','piv':'\\u03D6','planck':'\\u210F','planckh':'\\u210E','plankv':'\\u210F','plus':'+','plusacir':'\\u2A23','plusb':'\\u229E','pluscir':'\\u2A22','plusdo':'\\u2214','plusdu':'\\u2A25','pluse':'\\u2A72','PlusMinus':'\\xB1','plusmn':'\\xB1','plussim':'\\u2A26','plustwo':'\\u2A27','pm':'\\xB1','Poincareplane':'\\u210C','pointint':'\\u2A15','popf':'\\uD835\\uDD61','Popf':'\\u2119','pound':'\\xA3','pr':'\\u227A','Pr':'\\u2ABB','prap':'\\u2AB7','prcue':'\\u227C','pre':'\\u2AAF','prE':'\\u2AB3','prec':'\\u227A','precapprox':'\\u2AB7','preccurlyeq':'\\u227C','Precedes':'\\u227A','PrecedesEqual':'\\u2AAF','PrecedesSlantEqual':'\\u227C','PrecedesTilde':'\\u227E','preceq':'\\u2AAF','precnapprox':'\\u2AB9','precneqq':'\\u2AB5','precnsim':'\\u22E8','precsim':'\\u227E','prime':'\\u2032','Prime':'\\u2033','primes':'\\u2119','prnap':'\\u2AB9','prnE':'\\u2AB5','prnsim':'\\u22E8','prod':'\\u220F','Product':'\\u220F','profalar':'\\u232E','profline':'\\u2312','profsurf':'\\u2313','prop':'\\u221D','Proportion':'\\u2237','Proportional':'\\u221D','propto':'\\u221D','prsim':'\\u227E','prurel':'\\u22B0','pscr':'\\uD835\\uDCC5','Pscr':'\\uD835\\uDCAB','psi':'\\u03C8','Psi':'\\u03A8','puncsp':'\\u2008','qfr':'\\uD835\\uDD2E','Qfr':'\\uD835\\uDD14','qint':'\\u2A0C','qopf':'\\uD835\\uDD62','Qopf':'\\u211A','qprime':'\\u2057','qscr':'\\uD835\\uDCC6','Qscr':'\\uD835\\uDCAC','quaternions':'\\u210D','quatint':'\\u2A16','quest':'?','questeq':'\\u225F','quot':'\"','QUOT':'\"','rAarr':'\\u21DB','race':'\\u223D\\u0331','racute':'\\u0155','Racute':'\\u0154','radic':'\\u221A','raemptyv':'\\u29B3','rang':'\\u27E9','Rang':'\\u27EB','rangd':'\\u2992','range':'\\u29A5','rangle':'\\u27E9','raquo':'\\xBB','rarr':'\\u2192','rArr':'\\u21D2','Rarr':'\\u21A0','rarrap':'\\u2975','rarrb':'\\u21E5','rarrbfs':'\\u2920','rarrc':'\\u2933','rarrfs':'\\u291E','rarrhk':'\\u21AA','rarrlp':'\\u21AC','rarrpl':'\\u2945','rarrsim':'\\u2974','rarrtl':'\\u21A3','Rarrtl':'\\u2916','rarrw':'\\u219D','ratail':'\\u291A','rAtail':'\\u291C','ratio':'\\u2236','rationals':'\\u211A','rbarr':'\\u290D','rBarr':'\\u290F','RBarr':'\\u2910','rbbrk':'\\u2773','rbrace':'}','rbrack':']','rbrke':'\\u298C','rbrksld':'\\u298E','rbrkslu':'\\u2990','rcaron':'\\u0159','Rcaron':'\\u0158','rcedil':'\\u0157','Rcedil':'\\u0156','rceil':'\\u2309','rcub':'}','rcy':'\\u0440','Rcy':'\\u0420','rdca':'\\u2937','rdldhar':'\\u2969','rdquo':'\\u201D','rdquor':'\\u201D','rdsh':'\\u21B3','Re':'\\u211C','real':'\\u211C','realine':'\\u211B','realpart':'\\u211C','reals':'\\u211D','rect':'\\u25AD','reg':'\\xAE','REG':'\\xAE','ReverseElement':'\\u220B','ReverseEquilibrium':'\\u21CB','ReverseUpEquilibrium':'\\u296F','rfisht':'\\u297D','rfloor':'\\u230B','rfr':'\\uD835\\uDD2F','Rfr':'\\u211C','rHar':'\\u2964','rhard':'\\u21C1','rharu':'\\u21C0','rharul':'\\u296C','rho':'\\u03C1','Rho':'\\u03A1','rhov':'\\u03F1','RightAngleBracket':'\\u27E9','rightarrow':'\\u2192','Rightarrow':'\\u21D2','RightArrow':'\\u2192','RightArrowBar':'\\u21E5','RightArrowLeftArrow':'\\u21C4','rightarrowtail':'\\u21A3','RightCeiling':'\\u2309','RightDoubleBracket':'\\u27E7','RightDownTeeVector':'\\u295D','RightDownVector':'\\u21C2','RightDownVectorBar':'\\u2955','RightFloor':'\\u230B','rightharpoondown':'\\u21C1','rightharpoonup':'\\u21C0','rightleftarrows':'\\u21C4','rightleftharpoons':'\\u21CC','rightrightarrows':'\\u21C9','rightsquigarrow':'\\u219D','RightTee':'\\u22A2','RightTeeArrow':'\\u21A6','RightTeeVector':'\\u295B','rightthreetimes':'\\u22CC','RightTriangle':'\\u22B3','RightTriangleBar':'\\u29D0','RightTriangleEqual':'\\u22B5','RightUpDownVector':'\\u294F','RightUpTeeVector':'\\u295C','RightUpVector':'\\u21BE','RightUpVectorBar':'\\u2954','RightVector':'\\u21C0','RightVectorBar':'\\u2953','ring':'\\u02DA','risingdotseq':'\\u2253','rlarr':'\\u21C4','rlhar':'\\u21CC','rlm':'\\u200F','rmoust':'\\u23B1','rmoustache':'\\u23B1','rnmid':'\\u2AEE','roang':'\\u27ED','roarr':'\\u21FE','robrk':'\\u27E7','ropar':'\\u2986','ropf':'\\uD835\\uDD63','Ropf':'\\u211D','roplus':'\\u2A2E','rotimes':'\\u2A35','RoundImplies':'\\u2970','rpar':')','rpargt':'\\u2994','rppolint':'\\u2A12','rrarr':'\\u21C9','Rrightarrow':'\\u21DB','rsaquo':'\\u203A','rscr':'\\uD835\\uDCC7','Rscr':'\\u211B','rsh':'\\u21B1','Rsh':'\\u21B1','rsqb':']','rsquo':'\\u2019','rsquor':'\\u2019','rthree':'\\u22CC','rtimes':'\\u22CA','rtri':'\\u25B9','rtrie':'\\u22B5','rtrif':'\\u25B8','rtriltri':'\\u29CE','RuleDelayed':'\\u29F4','ruluhar':'\\u2968','rx':'\\u211E','sacute':'\\u015B','Sacute':'\\u015A','sbquo':'\\u201A','sc':'\\u227B','Sc':'\\u2ABC','scap':'\\u2AB8','scaron':'\\u0161','Scaron':'\\u0160','sccue':'\\u227D','sce':'\\u2AB0','scE':'\\u2AB4','scedil':'\\u015F','Scedil':'\\u015E','scirc':'\\u015D','Scirc':'\\u015C','scnap':'\\u2ABA','scnE':'\\u2AB6','scnsim':'\\u22E9','scpolint':'\\u2A13','scsim':'\\u227F','scy':'\\u0441','Scy':'\\u0421','sdot':'\\u22C5','sdotb':'\\u22A1','sdote':'\\u2A66','searhk':'\\u2925','searr':'\\u2198','seArr':'\\u21D8','searrow':'\\u2198','sect':'\\xA7','semi':';','seswar':'\\u2929','setminus':'\\u2216','setmn':'\\u2216','sext':'\\u2736','sfr':'\\uD835\\uDD30','Sfr':'\\uD835\\uDD16','sfrown':'\\u2322','sharp':'\\u266F','shchcy':'\\u0449','SHCHcy':'\\u0429','shcy':'\\u0448','SHcy':'\\u0428','ShortDownArrow':'\\u2193','ShortLeftArrow':'\\u2190','shortmid':'\\u2223','shortparallel':'\\u2225','ShortRightArrow':'\\u2192','ShortUpArrow':'\\u2191','shy':'\\xAD','sigma':'\\u03C3','Sigma':'\\u03A3','sigmaf':'\\u03C2','sigmav':'\\u03C2','sim':'\\u223C','simdot':'\\u2A6A','sime':'\\u2243','simeq':'\\u2243','simg':'\\u2A9E','simgE':'\\u2AA0','siml':'\\u2A9D','simlE':'\\u2A9F','simne':'\\u2246','simplus':'\\u2A24','simrarr':'\\u2972','slarr':'\\u2190','SmallCircle':'\\u2218','smallsetminus':'\\u2216','smashp':'\\u2A33','smeparsl':'\\u29E4','smid':'\\u2223','smile':'\\u2323','smt':'\\u2AAA','smte':'\\u2AAC','smtes':'\\u2AAC\\uFE00','softcy':'\\u044C','SOFTcy':'\\u042C','sol':'/','solb':'\\u29C4','solbar':'\\u233F','sopf':'\\uD835\\uDD64','Sopf':'\\uD835\\uDD4A','spades':'\\u2660','spadesuit':'\\u2660','spar':'\\u2225','sqcap':'\\u2293','sqcaps':'\\u2293\\uFE00','sqcup':'\\u2294','sqcups':'\\u2294\\uFE00','Sqrt':'\\u221A','sqsub':'\\u228F','sqsube':'\\u2291','sqsubset':'\\u228F','sqsubseteq':'\\u2291','sqsup':'\\u2290','sqsupe':'\\u2292','sqsupset':'\\u2290','sqsupseteq':'\\u2292','squ':'\\u25A1','square':'\\u25A1','Square':'\\u25A1','SquareIntersection':'\\u2293','SquareSubset':'\\u228F','SquareSubsetEqual':'\\u2291','SquareSuperset':'\\u2290','SquareSupersetEqual':'\\u2292','SquareUnion':'\\u2294','squarf':'\\u25AA','squf':'\\u25AA','srarr':'\\u2192','sscr':'\\uD835\\uDCC8','Sscr':'\\uD835\\uDCAE','ssetmn':'\\u2216','ssmile':'\\u2323','sstarf':'\\u22C6','star':'\\u2606','Star':'\\u22C6','starf':'\\u2605','straightepsilon':'\\u03F5','straightphi':'\\u03D5','strns':'\\xAF','sub':'\\u2282','Sub':'\\u22D0','subdot':'\\u2ABD','sube':'\\u2286','subE':'\\u2AC5','subedot':'\\u2AC3','submult':'\\u2AC1','subne':'\\u228A','subnE':'\\u2ACB','subplus':'\\u2ABF','subrarr':'\\u2979','subset':'\\u2282','Subset':'\\u22D0','subseteq':'\\u2286','subseteqq':'\\u2AC5','SubsetEqual':'\\u2286','subsetneq':'\\u228A','subsetneqq':'\\u2ACB','subsim':'\\u2AC7','subsub':'\\u2AD5','subsup':'\\u2AD3','succ':'\\u227B','succapprox':'\\u2AB8','succcurlyeq':'\\u227D','Succeeds':'\\u227B','SucceedsEqual':'\\u2AB0','SucceedsSlantEqual':'\\u227D','SucceedsTilde':'\\u227F','succeq':'\\u2AB0','succnapprox':'\\u2ABA','succneqq':'\\u2AB6','succnsim':'\\u22E9','succsim':'\\u227F','SuchThat':'\\u220B','sum':'\\u2211','Sum':'\\u2211','sung':'\\u266A','sup':'\\u2283','Sup':'\\u22D1','sup1':'\\xB9','sup2':'\\xB2','sup3':'\\xB3','supdot':'\\u2ABE','supdsub':'\\u2AD8','supe':'\\u2287','supE':'\\u2AC6','supedot':'\\u2AC4','Superset':'\\u2283','SupersetEqual':'\\u2287','suphsol':'\\u27C9','suphsub':'\\u2AD7','suplarr':'\\u297B','supmult':'\\u2AC2','supne':'\\u228B','supnE':'\\u2ACC','supplus':'\\u2AC0','supset':'\\u2283','Supset':'\\u22D1','supseteq':'\\u2287','supseteqq':'\\u2AC6','supsetneq':'\\u228B','supsetneqq':'\\u2ACC','supsim':'\\u2AC8','supsub':'\\u2AD4','supsup':'\\u2AD6','swarhk':'\\u2926','swarr':'\\u2199','swArr':'\\u21D9','swarrow':'\\u2199','swnwar':'\\u292A','szlig':'\\xDF','Tab':'\\t','target':'\\u2316','tau':'\\u03C4','Tau':'\\u03A4','tbrk':'\\u23B4','tcaron':'\\u0165','Tcaron':'\\u0164','tcedil':'\\u0163','Tcedil':'\\u0162','tcy':'\\u0442','Tcy':'\\u0422','tdot':'\\u20DB','telrec':'\\u2315','tfr':'\\uD835\\uDD31','Tfr':'\\uD835\\uDD17','there4':'\\u2234','therefore':'\\u2234','Therefore':'\\u2234','theta':'\\u03B8','Theta':'\\u0398','thetasym':'\\u03D1','thetav':'\\u03D1','thickapprox':'\\u2248','thicksim':'\\u223C','ThickSpace':'\\u205F\\u200A','thinsp':'\\u2009','ThinSpace':'\\u2009','thkap':'\\u2248','thksim':'\\u223C','thorn':'\\xFE','THORN':'\\xDE','tilde':'\\u02DC','Tilde':'\\u223C','TildeEqual':'\\u2243','TildeFullEqual':'\\u2245','TildeTilde':'\\u2248','times':'\\xD7','timesb':'\\u22A0','timesbar':'\\u2A31','timesd':'\\u2A30','tint':'\\u222D','toea':'\\u2928','top':'\\u22A4','topbot':'\\u2336','topcir':'\\u2AF1','topf':'\\uD835\\uDD65','Topf':'\\uD835\\uDD4B','topfork':'\\u2ADA','tosa':'\\u2929','tprime':'\\u2034','trade':'\\u2122','TRADE':'\\u2122','triangle':'\\u25B5','triangledown':'\\u25BF','triangleleft':'\\u25C3','trianglelefteq':'\\u22B4','triangleq':'\\u225C','triangleright':'\\u25B9','trianglerighteq':'\\u22B5','tridot':'\\u25EC','trie':'\\u225C','triminus':'\\u2A3A','TripleDot':'\\u20DB','triplus':'\\u2A39','trisb':'\\u29CD','tritime':'\\u2A3B','trpezium':'\\u23E2','tscr':'\\uD835\\uDCC9','Tscr':'\\uD835\\uDCAF','tscy':'\\u0446','TScy':'\\u0426','tshcy':'\\u045B','TSHcy':'\\u040B','tstrok':'\\u0167','Tstrok':'\\u0166','twixt':'\\u226C','twoheadleftarrow':'\\u219E','twoheadrightarrow':'\\u21A0','uacute':'\\xFA','Uacute':'\\xDA','uarr':'\\u2191','uArr':'\\u21D1','Uarr':'\\u219F','Uarrocir':'\\u2949','ubrcy':'\\u045E','Ubrcy':'\\u040E','ubreve':'\\u016D','Ubreve':'\\u016C','ucirc':'\\xFB','Ucirc':'\\xDB','ucy':'\\u0443','Ucy':'\\u0423','udarr':'\\u21C5','udblac':'\\u0171','Udblac':'\\u0170','udhar':'\\u296E','ufisht':'\\u297E','ufr':'\\uD835\\uDD32','Ufr':'\\uD835\\uDD18','ugrave':'\\xF9','Ugrave':'\\xD9','uHar':'\\u2963','uharl':'\\u21BF','uharr':'\\u21BE','uhblk':'\\u2580','ulcorn':'\\u231C','ulcorner':'\\u231C','ulcrop':'\\u230F','ultri':'\\u25F8','umacr':'\\u016B','Umacr':'\\u016A','uml':'\\xA8','UnderBar':'_','UnderBrace':'\\u23DF','UnderBracket':'\\u23B5','UnderParenthesis':'\\u23DD','Union':'\\u22C3','UnionPlus':'\\u228E','uogon':'\\u0173','Uogon':'\\u0172','uopf':'\\uD835\\uDD66','Uopf':'\\uD835\\uDD4C','uparrow':'\\u2191','Uparrow':'\\u21D1','UpArrow':'\\u2191','UpArrowBar':'\\u2912','UpArrowDownArrow':'\\u21C5','updownarrow':'\\u2195','Updownarrow':'\\u21D5','UpDownArrow':'\\u2195','UpEquilibrium':'\\u296E','upharpoonleft':'\\u21BF','upharpoonright':'\\u21BE','uplus':'\\u228E','UpperLeftArrow':'\\u2196','UpperRightArrow':'\\u2197','upsi':'\\u03C5','Upsi':'\\u03D2','upsih':'\\u03D2','upsilon':'\\u03C5','Upsilon':'\\u03A5','UpTee':'\\u22A5','UpTeeArrow':'\\u21A5','upuparrows':'\\u21C8','urcorn':'\\u231D','urcorner':'\\u231D','urcrop':'\\u230E','uring':'\\u016F','Uring':'\\u016E','urtri':'\\u25F9','uscr':'\\uD835\\uDCCA','Uscr':'\\uD835\\uDCB0','utdot':'\\u22F0','utilde':'\\u0169','Utilde':'\\u0168','utri':'\\u25B5','utrif':'\\u25B4','uuarr':'\\u21C8','uuml':'\\xFC','Uuml':'\\xDC','uwangle':'\\u29A7','vangrt':'\\u299C','varepsilon':'\\u03F5','varkappa':'\\u03F0','varnothing':'\\u2205','varphi':'\\u03D5','varpi':'\\u03D6','varpropto':'\\u221D','varr':'\\u2195','vArr':'\\u21D5','varrho':'\\u03F1','varsigma':'\\u03C2','varsubsetneq':'\\u228A\\uFE00','varsubsetneqq':'\\u2ACB\\uFE00','varsupsetneq':'\\u228B\\uFE00','varsupsetneqq':'\\u2ACC\\uFE00','vartheta':'\\u03D1','vartriangleleft':'\\u22B2','vartriangleright':'\\u22B3','vBar':'\\u2AE8','Vbar':'\\u2AEB','vBarv':'\\u2AE9','vcy':'\\u0432','Vcy':'\\u0412','vdash':'\\u22A2','vDash':'\\u22A8','Vdash':'\\u22A9','VDash':'\\u22AB','Vdashl':'\\u2AE6','vee':'\\u2228','Vee':'\\u22C1','veebar':'\\u22BB','veeeq':'\\u225A','vellip':'\\u22EE','verbar':'|','Verbar':'\\u2016','vert':'|','Vert':'\\u2016','VerticalBar':'\\u2223','VerticalLine':'|','VerticalSeparator':'\\u2758','VerticalTilde':'\\u2240','VeryThinSpace':'\\u200A','vfr':'\\uD835\\uDD33','Vfr':'\\uD835\\uDD19','vltri':'\\u22B2','vnsub':'\\u2282\\u20D2','vnsup':'\\u2283\\u20D2','vopf':'\\uD835\\uDD67','Vopf':'\\uD835\\uDD4D','vprop':'\\u221D','vrtri':'\\u22B3','vscr':'\\uD835\\uDCCB','Vscr':'\\uD835\\uDCB1','vsubne':'\\u228A\\uFE00','vsubnE':'\\u2ACB\\uFE00','vsupne':'\\u228B\\uFE00','vsupnE':'\\u2ACC\\uFE00','Vvdash':'\\u22AA','vzigzag':'\\u299A','wcirc':'\\u0175','Wcirc':'\\u0174','wedbar':'\\u2A5F','wedge':'\\u2227','Wedge':'\\u22C0','wedgeq':'\\u2259','weierp':'\\u2118','wfr':'\\uD835\\uDD34','Wfr':'\\uD835\\uDD1A','wopf':'\\uD835\\uDD68','Wopf':'\\uD835\\uDD4E','wp':'\\u2118','wr':'\\u2240','wreath':'\\u2240','wscr':'\\uD835\\uDCCC','Wscr':'\\uD835\\uDCB2','xcap':'\\u22C2','xcirc':'\\u25EF','xcup':'\\u22C3','xdtri':'\\u25BD','xfr':'\\uD835\\uDD35','Xfr':'\\uD835\\uDD1B','xharr':'\\u27F7','xhArr':'\\u27FA','xi':'\\u03BE','Xi':'\\u039E','xlarr':'\\u27F5','xlArr':'\\u27F8','xmap':'\\u27FC','xnis':'\\u22FB','xodot':'\\u2A00','xopf':'\\uD835\\uDD69','Xopf':'\\uD835\\uDD4F','xoplus':'\\u2A01','xotime':'\\u2A02','xrarr':'\\u27F6','xrArr':'\\u27F9','xscr':'\\uD835\\uDCCD','Xscr':'\\uD835\\uDCB3','xsqcup':'\\u2A06','xuplus':'\\u2A04','xutri':'\\u25B3','xvee':'\\u22C1','xwedge':'\\u22C0','yacute':'\\xFD','Yacute':'\\xDD','yacy':'\\u044F','YAcy':'\\u042F','ycirc':'\\u0177','Ycirc':'\\u0176','ycy':'\\u044B','Ycy':'\\u042B','yen':'\\xA5','yfr':'\\uD835\\uDD36','Yfr':'\\uD835\\uDD1C','yicy':'\\u0457','YIcy':'\\u0407','yopf':'\\uD835\\uDD6A','Yopf':'\\uD835\\uDD50','yscr':'\\uD835\\uDCCE','Yscr':'\\uD835\\uDCB4','yucy':'\\u044E','YUcy':'\\u042E','yuml':'\\xFF','Yuml':'\\u0178','zacute':'\\u017A','Zacute':'\\u0179','zcaron':'\\u017E','Zcaron':'\\u017D','zcy':'\\u0437','Zcy':'\\u0417','zdot':'\\u017C','Zdot':'\\u017B','zeetrf':'\\u2128','ZeroWidthSpace':'\\u200B','zeta':'\\u03B6','Zeta':'\\u0396','zfr':'\\uD835\\uDD37','Zfr':'\\u2128','zhcy':'\\u0436','ZHcy':'\\u0416','zigrarr':'\\u21DD','zopf':'\\uD835\\uDD6B','Zopf':'\\u2124','zscr':'\\uD835\\uDCCF','Zscr':'\\uD835\\uDCB5','zwj':'\\u200D','zwnj':'\\u200C'};\n\tvar decodeMapLegacy = {'aacute':'\\xE1','Aacute':'\\xC1','acirc':'\\xE2','Acirc':'\\xC2','acute':'\\xB4','aelig':'\\xE6','AElig':'\\xC6','agrave':'\\xE0','Agrave':'\\xC0','amp':'&','AMP':'&','aring':'\\xE5','Aring':'\\xC5','atilde':'\\xE3','Atilde':'\\xC3','auml':'\\xE4','Auml':'\\xC4','brvbar':'\\xA6','ccedil':'\\xE7','Ccedil':'\\xC7','cedil':'\\xB8','cent':'\\xA2','copy':'\\xA9','COPY':'\\xA9','curren':'\\xA4','deg':'\\xB0','divide':'\\xF7','eacute':'\\xE9','Eacute':'\\xC9','ecirc':'\\xEA','Ecirc':'\\xCA','egrave':'\\xE8','Egrave':'\\xC8','eth':'\\xF0','ETH':'\\xD0','euml':'\\xEB','Euml':'\\xCB','frac12':'\\xBD','frac14':'\\xBC','frac34':'\\xBE','gt':'>','GT':'>','iacute':'\\xED','Iacute':'\\xCD','icirc':'\\xEE','Icirc':'\\xCE','iexcl':'\\xA1','igrave':'\\xEC','Igrave':'\\xCC','iquest':'\\xBF','iuml':'\\xEF','Iuml':'\\xCF','laquo':'\\xAB','lt':'<','LT':'<','macr':'\\xAF','micro':'\\xB5','middot':'\\xB7','nbsp':'\\xA0','not':'\\xAC','ntilde':'\\xF1','Ntilde':'\\xD1','oacute':'\\xF3','Oacute':'\\xD3','ocirc':'\\xF4','Ocirc':'\\xD4','ograve':'\\xF2','Ograve':'\\xD2','ordf':'\\xAA','ordm':'\\xBA','oslash':'\\xF8','Oslash':'\\xD8','otilde':'\\xF5','Otilde':'\\xD5','ouml':'\\xF6','Ouml':'\\xD6','para':'\\xB6','plusmn':'\\xB1','pound':'\\xA3','quot':'\"','QUOT':'\"','raquo':'\\xBB','reg':'\\xAE','REG':'\\xAE','sect':'\\xA7','shy':'\\xAD','sup1':'\\xB9','sup2':'\\xB2','sup3':'\\xB3','szlig':'\\xDF','thorn':'\\xFE','THORN':'\\xDE','times':'\\xD7','uacute':'\\xFA','Uacute':'\\xDA','ucirc':'\\xFB','Ucirc':'\\xDB','ugrave':'\\xF9','Ugrave':'\\xD9','uml':'\\xA8','uuml':'\\xFC','Uuml':'\\xDC','yacute':'\\xFD','Yacute':'\\xDD','yen':'\\xA5','yuml':'\\xFF'};\n\tvar decodeMapNumeric = {'0':'\\uFFFD','128':'\\u20AC','130':'\\u201A','131':'\\u0192','132':'\\u201E','133':'\\u2026','134':'\\u2020','135':'\\u2021','136':'\\u02C6','137':'\\u2030','138':'\\u0160','139':'\\u2039','140':'\\u0152','142':'\\u017D','145':'\\u2018','146':'\\u2019','147':'\\u201C','148':'\\u201D','149':'\\u2022','150':'\\u2013','151':'\\u2014','152':'\\u02DC','153':'\\u2122','154':'\\u0161','155':'\\u203A','156':'\\u0153','158':'\\u017E','159':'\\u0178'};\n\tvar invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar stringFromCharCode = String.fromCharCode;\n\n\tvar object = {};\n\tvar hasOwnProperty = object.hasOwnProperty;\n\tvar has = function(object, propertyName) {\n\t\treturn hasOwnProperty.call(object, propertyName);\n\t};\n\n\tvar contains = function(array, value) {\n\t\tvar index = -1;\n\t\tvar length = array.length;\n\t\twhile (++index < length) {\n\t\t\tif (array[index] == value) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\n\tvar merge = function(options, defaults) {\n\t\tif (!options) {\n\t\t\treturn defaults;\n\t\t}\n\t\tvar result = {};\n\t\tvar key;\n\t\tfor (key in defaults) {\n\t\t\t// A `hasOwnProperty` check is not needed here, since only recognized\n\t\t\t// option names are used anyway. Any others are ignored.\n\t\t\tresult[key] = has(options, key) ? options[key] : defaults[key];\n\t\t}\n\t\treturn result;\n\t};\n\n\t// Modified version of `ucs2encode`; see https://mths.be/punycode.\n\tvar codePointToSymbol = function(codePoint, strict) {\n\t\tvar output = '';\n\t\tif ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {\n\t\t\t// See issue #4:\n\t\t\t// “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is\n\t\t\t// greater than 0x10FFFF, then this is a parse error. Return a U+FFFD\n\t\t\t// REPLACEMENT CHARACTER.”\n\t\t\tif (strict) {\n\t\t\t\tparseError('character reference outside the permissible Unicode range');\n\t\t\t}\n\t\t\treturn '\\uFFFD';\n\t\t}\n\t\tif (has(decodeMapNumeric, codePoint)) {\n\t\t\tif (strict) {\n\t\t\t\tparseError('disallowed character reference');\n\t\t\t}\n\t\t\treturn decodeMapNumeric[codePoint];\n\t\t}\n\t\tif (strict && contains(invalidReferenceCodePoints, codePoint)) {\n\t\t\tparseError('disallowed character reference');\n\t\t}\n\t\tif (codePoint > 0xFFFF) {\n\t\t\tcodePoint -= 0x10000;\n\t\t\toutput += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);\n\t\t\tcodePoint = 0xDC00 | codePoint & 0x3FF;\n\t\t}\n\t\toutput += stringFromCharCode(codePoint);\n\t\treturn output;\n\t};\n\n\tvar hexEscape = function(codePoint) {\n\t\treturn '&#x' + codePoint.toString(16).toUpperCase() + ';';\n\t};\n\n\tvar decEscape = function(codePoint) {\n\t\treturn '&#' + codePoint + ';';\n\t};\n\n\tvar parseError = function(message) {\n\t\tthrow Error('Parse error: ' + message);\n\t};\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar encode = function(string, options) {\n\t\toptions = merge(options, encode.options);\n\t\tvar strict = options.strict;\n\t\tif (strict && regexInvalidRawCodePoint.test(string)) {\n\t\t\tparseError('forbidden code point');\n\t\t}\n\t\tvar encodeEverything = options.encodeEverything;\n\t\tvar useNamedReferences = options.useNamedReferences;\n\t\tvar allowUnsafeSymbols = options.allowUnsafeSymbols;\n\t\tvar escapeCodePoint = options.decimal ? decEscape : hexEscape;\n\n\t\tvar escapeBmpSymbol = function(symbol) {\n\t\t\treturn escapeCodePoint(symbol.charCodeAt(0));\n\t\t};\n\n\t\tif (encodeEverything) {\n\t\t\t// Encode ASCII symbols.\n\t\t\tstring = string.replace(regexAsciiWhitelist, function(symbol) {\n\t\t\t\t// Use named references if requested & possible.\n\t\t\t\tif (useNamedReferences && has(encodeMap, symbol)) {\n\t\t\t\t\treturn '&' + encodeMap[symbol] + ';';\n\t\t\t\t}\n\t\t\t\treturn escapeBmpSymbol(symbol);\n\t\t\t});\n\t\t\t// Shorten a few escapes that represent two symbols, of which at least one\n\t\t\t// is within the ASCII range.\n\t\t\tif (useNamedReferences) {\n\t\t\t\tstring = string\n\t\t\t\t\t.replace(/>\\u20D2/g, '>⃒')\n\t\t\t\t\t.replace(/<\\u20D2/g, '<⃒')\n\t\t\t\t\t.replace(/fj/g, 'fj');\n\t\t\t}\n\t\t\t// Encode non-ASCII symbols.\n\t\t\tif (useNamedReferences) {\n\t\t\t\t// Encode non-ASCII symbols that can be replaced with a named reference.\n\t\t\t\tstring = string.replace(regexEncodeNonAscii, function(string) {\n\t\t\t\t\t// Note: there is no need to check `has(encodeMap, string)` here.\n\t\t\t\t\treturn '&' + encodeMap[string] + ';';\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Note: any remaining non-ASCII symbols are handled outside of the `if`.\n\t\t} else if (useNamedReferences) {\n\t\t\t// Apply named character references.\n\t\t\t// Encode `<>\"'&` using named character references.\n\t\t\tif (!allowUnsafeSymbols) {\n\t\t\t\tstring = string.replace(regexEscape, function(string) {\n\t\t\t\t\treturn '&' + encodeMap[string] + ';'; // no need to check `has()` here\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Shorten escapes that represent two symbols, of which at least one is\n\t\t\t// `<>\"'&`.\n\t\t\tstring = string\n\t\t\t\t.replace(/>\\u20D2/g, '>⃒')\n\t\t\t\t.replace(/<\\u20D2/g, '<⃒');\n\t\t\t// Encode non-ASCII symbols that can be replaced with a named reference.\n\t\t\tstring = string.replace(regexEncodeNonAscii, function(string) {\n\t\t\t\t// Note: there is no need to check `has(encodeMap, string)` here.\n\t\t\t\treturn '&' + encodeMap[string] + ';';\n\t\t\t});\n\t\t} else if (!allowUnsafeSymbols) {\n\t\t\t// Encode `<>\"'&` using hexadecimal escapes, now that they’re not handled\n\t\t\t// using named character references.\n\t\t\tstring = string.replace(regexEscape, escapeBmpSymbol);\n\t\t}\n\t\treturn string\n\t\t\t// Encode astral symbols.\n\t\t\t.replace(regexAstralSymbols, function($0) {\n\t\t\t\t// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n\t\t\t\tvar high = $0.charCodeAt(0);\n\t\t\t\tvar low = $0.charCodeAt(1);\n\t\t\t\tvar codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;\n\t\t\t\treturn escapeCodePoint(codePoint);\n\t\t\t})\n\t\t\t// Encode any remaining BMP symbols that are not printable ASCII symbols\n\t\t\t// using a hexadecimal escape.\n\t\t\t.replace(regexBmpWhitelist, escapeBmpSymbol);\n\t};\n\t// Expose default options (so they can be overridden globally).\n\tencode.options = {\n\t\t'allowUnsafeSymbols': false,\n\t\t'encodeEverything': false,\n\t\t'strict': false,\n\t\t'useNamedReferences': false,\n\t\t'decimal' : false\n\t};\n\n\tvar decode = function(html, options) {\n\t\toptions = merge(options, decode.options);\n\t\tvar strict = options.strict;\n\t\tif (strict && regexInvalidEntity.test(html)) {\n\t\t\tparseError('malformed character reference');\n\t\t}\n\t\treturn html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {\n\t\t\tvar codePoint;\n\t\t\tvar semicolon;\n\t\t\tvar decDigits;\n\t\t\tvar hexDigits;\n\t\t\tvar reference;\n\t\t\tvar next;\n\n\t\t\tif ($1) {\n\t\t\t\treference = $1;\n\t\t\t\t// Note: there is no need to check `has(decodeMap, reference)`.\n\t\t\t\treturn decodeMap[reference];\n\t\t\t}\n\n\t\t\tif ($2) {\n\t\t\t\t// Decode named character references without trailing `;`, e.g. `&`.\n\t\t\t\t// This is only a parse error if it gets converted to `&`, or if it is\n\t\t\t\t// followed by `=` in an attribute context.\n\t\t\t\treference = $2;\n\t\t\t\tnext = $3;\n\t\t\t\tif (next && options.isAttributeValue) {\n\t\t\t\t\tif (strict && next == '=') {\n\t\t\t\t\t\tparseError('`&` did not start a character reference');\n\t\t\t\t\t}\n\t\t\t\t\treturn $0;\n\t\t\t\t} else {\n\t\t\t\t\tif (strict) {\n\t\t\t\t\t\tparseError(\n\t\t\t\t\t\t\t'named character reference was not terminated by a semicolon'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Note: there is no need to check `has(decodeMapLegacy, reference)`.\n\t\t\t\t\treturn decodeMapLegacy[reference] + (next || '');\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($4) {\n\t\t\t\t// Decode decimal escapes, e.g. `𝌆`.\n\t\t\t\tdecDigits = $4;\n\t\t\t\tsemicolon = $5;\n\t\t\t\tif (strict && !semicolon) {\n\t\t\t\t\tparseError('character reference was not terminated by a semicolon');\n\t\t\t\t}\n\t\t\t\tcodePoint = parseInt(decDigits, 10);\n\t\t\t\treturn codePointToSymbol(codePoint, strict);\n\t\t\t}\n\n\t\t\tif ($6) {\n\t\t\t\t// Decode hexadecimal escapes, e.g. `𝌆`.\n\t\t\t\thexDigits = $6;\n\t\t\t\tsemicolon = $7;\n\t\t\t\tif (strict && !semicolon) {\n\t\t\t\t\tparseError('character reference was not terminated by a semicolon');\n\t\t\t\t}\n\t\t\t\tcodePoint = parseInt(hexDigits, 16);\n\t\t\t\treturn codePointToSymbol(codePoint, strict);\n\t\t\t}\n\n\t\t\t// If we’re still here, `if ($7)` is implied; it’s an ambiguous\n\t\t\t// ampersand for sure. https://mths.be/notes/ambiguous-ampersands\n\t\t\tif (strict) {\n\t\t\t\tparseError(\n\t\t\t\t\t'named character reference was not terminated by a semicolon'\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn $0;\n\t\t});\n\t};\n\t// Expose default options (so they can be overridden globally).\n\tdecode.options = {\n\t\t'isAttributeValue': false,\n\t\t'strict': false\n\t};\n\n\tvar escape = function(string) {\n\t\treturn string.replace(regexEscape, function($0) {\n\t\t\t// Note: there is no need to check `has(escapeMap, $0)` here.\n\t\t\treturn escapeMap[$0];\n\t\t});\n\t};\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar he = {\n\t\t'version': '1.2.0',\n\t\t'encode': encode,\n\t\t'decode': decode,\n\t\t'escape': escape,\n\t\t'unescape': decode\n\t};\n\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine(function() {\n\t\t\treturn he;\n\t\t});\n\t}\telse if (freeExports && !freeExports.nodeType) {\n\t\tif (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = he;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (var key in he) {\n\t\t\t\thas(he, key) && (freeExports[key] = he[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.he = he;\n\t}\n\n}(this));\n","var DESCRIPTORS = require('../internals/descriptors');\nvar objectKeys = require('../internals/object-keys');\nvar toIndexedObject = require('../internals/to-indexed-object');\nvar propertyIsEnumerable = require('../internals/object-property-is-enumerable').f;\n\n// `Object.{ entries, values }` methods implementation\nvar createMethod = function (TO_ENTRIES) {\n return function (it) {\n var O = toIndexedObject(it);\n var keys = objectKeys(O);\n var length = keys.length;\n var i = 0;\n var result = [];\n var key;\n while (length > i) {\n key = keys[i++];\n if (!DESCRIPTORS || propertyIsEnumerable.call(O, key)) {\n result.push(TO_ENTRIES ? [key, O[key]] : O[key]);\n }\n }\n return result;\n };\n};\n\nmodule.exports = {\n // `Object.entries` method\n // https://tc39.es/ecma262/#sec-object.entries\n entries: createMethod(true),\n // `Object.values` method\n // https://tc39.es/ecma262/#sec-object.values\n values: createMethod(false)\n};\n","var $ = require('../internals/export');\nvar $values = require('../internals/object-to-array').values;\n\n// `Object.values` method\n// https://tc39.es/ecma262/#sec-object.values\n$({ target: 'Object', stat: true }, {\n values: function values(O) {\n return $values(O);\n }\n});\n","'use strict';\n\nconst {format} = require('util');\n\n/**\n * Contains error codes, factory functions to create throwable error objects,\n * and warning/deprecation functions.\n * @module\n */\n\n/**\n * process.emitWarning or a polyfill\n * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options\n * @ignore\n */\nconst emitWarning = (msg, type) => {\n if (process.emitWarning) {\n process.emitWarning(msg, type);\n } else {\n /* istanbul ignore next */\n process.nextTick(function() {\n console.warn(type + ': ' + msg);\n });\n }\n};\n\n/**\n * Show a deprecation warning. Each distinct message is only displayed once.\n * Ignores empty messages.\n *\n * @param {string} [msg] - Warning to print\n * @private\n */\nconst deprecate = msg => {\n msg = String(msg);\n if (msg && !deprecate.cache[msg]) {\n deprecate.cache[msg] = true;\n emitWarning(msg, 'DeprecationWarning');\n }\n};\ndeprecate.cache = {};\n\n/**\n * Show a generic warning.\n * Ignores empty messages.\n *\n * @param {string} [msg] - Warning to print\n * @private\n */\nconst warn = msg => {\n if (msg) {\n emitWarning(msg);\n }\n};\n\n/**\n * When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`.\n * @public\n * @namespace\n * @memberof module:lib/errors\n */\nvar constants = {\n /**\n * An unrecoverable error.\n * @constant\n * @default\n */\n FATAL: 'ERR_MOCHA_FATAL',\n\n /**\n * The type of an argument to a function call is invalid\n * @constant\n * @default\n */\n INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE',\n\n /**\n * The value of an argument to a function call is invalid\n * @constant\n * @default\n */\n INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE',\n\n /**\n * Something was thrown, but it wasn't an `Error`\n * @constant\n * @default\n */\n INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION',\n\n /**\n * An interface (e.g., `Mocha.interfaces`) is unknown or invalid\n * @constant\n * @default\n */\n INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE',\n\n /**\n * A reporter (.e.g, `Mocha.reporters`) is unknown or invalid\n * @constant\n * @default\n */\n INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER',\n\n /**\n * `done()` was called twice in a `Test` or `Hook` callback\n * @constant\n * @default\n */\n MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE',\n\n /**\n * No files matched the pattern provided by the user\n * @constant\n * @default\n */\n NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN',\n\n /**\n * Known, but unsupported behavior of some kind\n * @constant\n * @default\n */\n UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED',\n\n /**\n * Invalid state transition occurring in `Mocha` instance\n * @constant\n * @default\n */\n INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',\n\n /**\n * Invalid state transition occurring in `Mocha` instance\n * @constant\n * @default\n */\n INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',\n\n /**\n * Use of `only()` w/ `--forbid-only` results in this error.\n * @constant\n * @default\n */\n FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY',\n\n /**\n * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid\n * @constant\n * @default\n */\n INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION',\n\n /**\n * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid\n * @constant\n * @default\n */\n INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION',\n\n /**\n * When a runnable exceeds its allowed run time.\n * @constant\n * @default\n */\n TIMEOUT: 'ERR_MOCHA_TIMEOUT',\n\n /**\n * Input file is not able to be parsed\n * @constant\n * @default\n */\n UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE'\n};\n\n/**\n * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}.\n * @private\n */\nconst MOCHA_ERRORS = new Set(Object.values(constants));\n\n/**\n * Creates an error object to be thrown when no files to be tested could be found using specified pattern.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} pattern - User-specified argument value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createNoFilesMatchPatternError(message, pattern) {\n var err = new Error(message);\n err.code = constants.NO_FILES_MATCH_PATTERN;\n err.pattern = pattern;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when the reporter specified in the options was not found.\n *\n * @public\n * @param {string} message - Error message to be displayed.\n * @param {string} reporter - User-specified reporter value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidReporterError(message, reporter) {\n var err = new TypeError(message);\n err.code = constants.INVALID_REPORTER;\n err.reporter = reporter;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when the interface specified in the options was not found.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} ui - User-specified interface value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidInterfaceError(message, ui) {\n var err = new Error(message);\n err.code = constants.INVALID_INTERFACE;\n err.interface = ui;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a behavior, option, or parameter is unsupported.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createUnsupportedError(message) {\n var err = new Error(message);\n err.code = constants.UNSUPPORTED;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an argument is missing.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} expected - Expected argument datatype.\n * @returns {Error} instance detailing the error condition\n */\nfunction createMissingArgumentError(message, argument, expected) {\n return createInvalidArgumentTypeError(message, argument, expected);\n}\n\n/**\n * Creates an error object to be thrown when an argument did not use the supported type\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} expected - Expected argument datatype.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidArgumentTypeError(message, argument, expected) {\n var err = new TypeError(message);\n err.code = constants.INVALID_ARG_TYPE;\n err.argument = argument;\n err.expected = expected;\n err.actual = typeof argument;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an argument did not use the supported value\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} value - Argument value.\n * @param {string} [reason] - Why value is invalid.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidArgumentValueError(message, argument, value, reason) {\n var err = new TypeError(message);\n err.code = constants.INVALID_ARG_VALUE;\n err.argument = argument;\n err.value = value;\n err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidExceptionError(message, value) {\n var err = new Error(message);\n err.code = constants.INVALID_EXCEPTION;\n err.valueType = typeof value;\n err.value = value;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an unrecoverable error occurs.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createFatalError(message, value) {\n var err = new Error(message);\n err.code = constants.FATAL;\n err.valueType = typeof value;\n err.value = value;\n return err;\n}\n\n/**\n * Dynamically creates a plugin-type-specific error based on plugin type\n * @param {string} message - Error message\n * @param {\"reporter\"|\"interface\"} pluginType - Plugin type. Future: expand as needed\n * @param {string} [pluginId] - Name/path of plugin, if any\n * @throws When `pluginType` is not known\n * @public\n * @static\n * @returns {Error}\n */\nfunction createInvalidLegacyPluginError(message, pluginType, pluginId) {\n switch (pluginType) {\n case 'reporter':\n return createInvalidReporterError(message, pluginId);\n case 'interface':\n return createInvalidInterfaceError(message, pluginId);\n default:\n throw new Error('unknown pluginType \"' + pluginType + '\"');\n }\n}\n\n/**\n * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type\n * @deprecated\n * @param {string} message - Error message\n * @param {\"reporter\"|\"interface\"} pluginType - Plugin type. Future: expand as needed\n * @param {string} [pluginId] - Name/path of plugin, if any\n * @throws When `pluginType` is not known\n * @public\n * @static\n * @returns {Error}\n */\nfunction createInvalidPluginError(...args) {\n deprecate('Use createInvalidLegacyPluginError() instead');\n return createInvalidLegacyPluginError(...args);\n}\n\n/**\n * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed.\n * @param {string} message The error message to be displayed.\n * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun`\n * @param {Mocha} instance the mocha instance that throw this error\n * @static\n */\nfunction createMochaInstanceAlreadyDisposedError(\n message,\n cleanReferencesAfterRun,\n instance\n) {\n var err = new Error(message);\n err.code = constants.INSTANCE_ALREADY_DISPOSED;\n err.cleanReferencesAfterRun = cleanReferencesAfterRun;\n err.instance = instance;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress.\n * @param {string} message The error message to be displayed.\n * @static\n * @public\n */\nfunction createMochaInstanceAlreadyRunningError(message, instance) {\n var err = new Error(message);\n err.code = constants.INSTANCE_ALREADY_RUNNING;\n err.instance = instance;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when done() is called multiple times in a test\n *\n * @public\n * @param {Runnable} runnable - Original runnable\n * @param {Error} [originalErr] - Original error, if any\n * @returns {Error} instance detailing the error condition\n * @static\n */\nfunction createMultipleDoneError(runnable, originalErr) {\n var title;\n try {\n title = format('<%s>', runnable.fullTitle());\n if (runnable.parent.root) {\n title += ' (of root suite)';\n }\n } catch (ignored) {\n title = format('<%s> (of unknown suite)', runnable.title);\n }\n var message = format(\n 'done() called multiple times in %s %s',\n runnable.type ? runnable.type : 'unknown runnable',\n title\n );\n if (runnable.file) {\n message += format(' of file %s', runnable.file);\n }\n if (originalErr) {\n message += format('; in addition, done() received error: %s', originalErr);\n }\n\n var err = new Error(message);\n err.code = constants.MULTIPLE_DONE;\n err.valueType = typeof originalErr;\n err.value = originalErr;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when `.only()` is used with\n * `--forbid-only`.\n * @static\n * @public\n * @param {Mocha} mocha - Mocha instance\n * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY}\n */\nfunction createForbiddenExclusivityError(mocha) {\n var err = new Error(\n mocha.isWorker\n ? '`.only` is not supported in parallel mode'\n : '`.only` forbidden by --forbid-only'\n );\n err.code = constants.FORBIDDEN_EXCLUSIVITY;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a plugin definition is invalid\n * @static\n * @param {string} msg - Error message\n * @param {PluginDefinition} [pluginDef] - Problematic plugin definition\n * @public\n * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}\n */\nfunction createInvalidPluginDefinitionError(msg, pluginDef) {\n const err = new Error(msg);\n err.code = constants.INVALID_PLUGIN_DEFINITION;\n err.pluginDef = pluginDef;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a plugin implementation (user code) is invalid\n * @static\n * @param {string} msg - Error message\n * @param {Object} [opts] - Plugin definition and user-supplied implementation\n * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition\n * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied)\n * @public\n * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}\n */\nfunction createInvalidPluginImplementationError(\n msg,\n {pluginDef, pluginImpl} = {}\n) {\n const err = new Error(msg);\n err.code = constants.INVALID_PLUGIN_IMPLEMENTATION;\n err.pluginDef = pluginDef;\n err.pluginImpl = pluginImpl;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a runnable exceeds its allowed run time.\n * @static\n * @param {string} msg - Error message\n * @param {number} [timeout] - Timeout in ms\n * @param {string} [file] - File, if given\n * @returns {MochaTimeoutError}\n */\nfunction createTimeoutError(msg, timeout, file) {\n const err = new Error(msg);\n err.code = constants.TIMEOUT;\n err.timeout = timeout;\n err.file = file;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when file is unparsable\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} filename - File name\n * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE}\n */\nfunction createUnparsableFileError(message, filename) {\n var err = new Error(message);\n err.code = constants.UNPARSABLE_FILE;\n return err;\n}\n\n/**\n * Returns `true` if an error came out of Mocha.\n * _Can suffer from false negatives, but not false positives._\n * @static\n * @public\n * @param {*} err - Error, or anything\n * @returns {boolean}\n */\nconst isMochaError = err =>\n Boolean(err && typeof err === 'object' && MOCHA_ERRORS.has(err.code));\n\nmodule.exports = {\n constants,\n createFatalError,\n createForbiddenExclusivityError,\n createInvalidArgumentTypeError,\n createInvalidArgumentValueError,\n createInvalidExceptionError,\n createInvalidInterfaceError,\n createInvalidLegacyPluginError,\n createInvalidPluginDefinitionError,\n createInvalidPluginError,\n createInvalidPluginImplementationError,\n createInvalidReporterError,\n createMissingArgumentError,\n createMochaInstanceAlreadyDisposedError,\n createMochaInstanceAlreadyRunningError,\n createMultipleDoneError,\n createNoFilesMatchPatternError,\n createTimeoutError,\n createUnparsableFileError,\n createUnsupportedError,\n deprecate,\n isMochaError,\n warn\n};\n\n/**\n * The error thrown when a Runnable times out\n * @memberof module:lib/errors\n * @typedef {Error} MochaTimeoutError\n * @property {constants.TIMEOUT} code - Error code\n * @property {number?} timeout Timeout in ms\n * @property {string?} file Filepath, if given\n */\n","'use strict';\n\n/**\n * Various utility functions used throughout Mocha's codebase.\n * @module utils\n */\n\n/**\n * Module dependencies.\n */\n\nconst {nanoid} = require('nanoid/non-secure');\nvar path = require('path');\nvar util = require('util');\nvar he = require('he');\nconst errors = require('./errors');\n\nconst MOCHA_ID_PROP_NAME = '__mocha_id__';\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * @param {function} ctor - Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor - Constructor function to inherit prototype from.\n * @throws {TypeError} if either constructor is null, or if super constructor\n * lacks a prototype.\n */\nexports.inherits = util.inherits;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @private\n * @param {string} html\n * @return {string}\n */\nexports.escape = function(html) {\n return he.encode(String(html), {useNamedReferences: false});\n};\n\n/**\n * Test if the given obj is type of string.\n *\n * @private\n * @param {Object} obj\n * @return {boolean}\n */\nexports.isString = function(obj) {\n return typeof obj === 'string';\n};\n\n/**\n * Compute a slug from the given `str`.\n *\n * @private\n * @param {string} str\n * @return {string}\n */\nexports.slug = function(str) {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^-\\w]/g, '')\n .replace(/-{2,}/g, '-');\n};\n\n/**\n * Strip the function definition from `str`, and re-indent for pre whitespace.\n *\n * @param {string} str\n * @return {string}\n */\nexports.clean = function(str) {\n str = str\n .replace(/\\r\\n?|[\\n\\u2028\\u2029]/g, '\\n')\n .replace(/^\\uFEFF/, '')\n // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content\n .replace(\n /^function(?:\\s*|\\s+[^(]*)\\([^)]*\\)\\s*\\{((?:.|\\n)*?)\\s*\\}$|^\\([^)]*\\)\\s*=>\\s*(?:\\{((?:.|\\n)*?)\\s*\\}|((?:.|\\n)*))$/,\n '$1$2$3'\n );\n\n var spaces = str.match(/^\\n?( *)/)[1].length;\n var tabs = str.match(/^\\n?(\\t*)/)[1].length;\n var re = new RegExp(\n '^\\n?' + (tabs ? '\\t' : ' ') + '{' + (tabs || spaces) + '}',\n 'gm'\n );\n\n str = str.replace(re, '');\n\n return str.trim();\n};\n\n/**\n * If a value could have properties, and has none, this function is called,\n * which returns a string representation of the empty value.\n *\n * Functions w/ no properties return `'[Function]'`\n * Arrays w/ length === 0 return `'[]'`\n * Objects w/ no properties return `'{}'`\n * All else: return result of `value.toString()`\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} typeHint The type of the value\n * @returns {string}\n */\nfunction emptyRepresentation(value, typeHint) {\n switch (typeHint) {\n case 'function':\n return '[Function]';\n case 'object':\n return '{}';\n case 'array':\n return '[]';\n default:\n return value.toString();\n }\n}\n\n/**\n * Takes some variable and asks `Object.prototype.toString()` what it thinks it\n * is.\n *\n * @private\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString\n * @param {*} value The value to test.\n * @returns {string} Computed type\n * @example\n * canonicalType({}) // 'object'\n * canonicalType([]) // 'array'\n * canonicalType(1) // 'number'\n * canonicalType(false) // 'boolean'\n * canonicalType(Infinity) // 'number'\n * canonicalType(null) // 'null'\n * canonicalType(new Date()) // 'date'\n * canonicalType(/foo/) // 'regexp'\n * canonicalType('type') // 'string'\n * canonicalType(global) // 'global'\n * canonicalType(new String('foo') // 'object'\n * canonicalType(async function() {}) // 'asyncfunction'\n * canonicalType(await import(name)) // 'module'\n */\nvar canonicalType = (exports.canonicalType = function canonicalType(value) {\n if (value === undefined) {\n return 'undefined';\n } else if (value === null) {\n return 'null';\n } else if (Buffer.isBuffer(value)) {\n return 'buffer';\n }\n return Object.prototype.toString\n .call(value)\n .replace(/^\\[.+\\s(.+?)]$/, '$1')\n .toLowerCase();\n});\n\n/**\n *\n * Returns a general type or data structure of a variable\n * @private\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures\n * @param {*} value The value to test.\n * @returns {string} One of undefined, boolean, number, string, bigint, symbol, object\n * @example\n * type({}) // 'object'\n * type([]) // 'array'\n * type(1) // 'number'\n * type(false) // 'boolean'\n * type(Infinity) // 'number'\n * type(null) // 'null'\n * type(new Date()) // 'object'\n * type(/foo/) // 'object'\n * type('type') // 'string'\n * type(global) // 'object'\n * type(new String('foo') // 'string'\n */\nexports.type = function type(value) {\n // Null is special\n if (value === null) return 'null';\n const primitives = new Set([\n 'undefined',\n 'boolean',\n 'number',\n 'string',\n 'bigint',\n 'symbol'\n ]);\n const _type = typeof value;\n if (_type === 'function') return _type;\n if (primitives.has(_type)) return _type;\n if (value instanceof String) return 'string';\n if (value instanceof Error) return 'error';\n if (Array.isArray(value)) return 'array';\n\n return _type;\n};\n\n/**\n * Stringify `value`. Different behavior depending on type of value:\n *\n * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.\n * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.\n * - If `value` is an *empty* object, function, or array, return result of function\n * {@link emptyRepresentation}.\n * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of\n * JSON.stringify().\n *\n * @private\n * @see exports.type\n * @param {*} value\n * @return {string}\n */\nexports.stringify = function(value) {\n var typeHint = canonicalType(value);\n\n if (!~['object', 'array', 'function'].indexOf(typeHint)) {\n if (typeHint === 'buffer') {\n var json = Buffer.prototype.toJSON.call(value);\n // Based on the toJSON result\n return jsonStringify(\n json.data && json.type ? json.data : json,\n 2\n ).replace(/,(\\n|$)/g, '$1');\n }\n\n // IE7/IE8 has a bizarre String constructor; needs to be coerced\n // into an array and back to obj.\n if (typeHint === 'string' && typeof value === 'object') {\n value = value.split('').reduce(function(acc, char, idx) {\n acc[idx] = char;\n return acc;\n }, {});\n typeHint = 'object';\n } else {\n return jsonStringify(value);\n }\n }\n\n for (var prop in value) {\n if (Object.prototype.hasOwnProperty.call(value, prop)) {\n return jsonStringify(\n exports.canonicalize(value, null, typeHint),\n 2\n ).replace(/,(\\n|$)/g, '$1');\n }\n }\n\n return emptyRepresentation(value, typeHint);\n};\n\n/**\n * like JSON.stringify but more sense.\n *\n * @private\n * @param {Object} object\n * @param {number=} spaces\n * @param {number=} depth\n * @returns {*}\n */\nfunction jsonStringify(object, spaces, depth) {\n if (typeof spaces === 'undefined') {\n // primitive types\n return _stringify(object);\n }\n\n depth = depth || 1;\n var space = spaces * depth;\n var str = Array.isArray(object) ? '[' : '{';\n var end = Array.isArray(object) ? ']' : '}';\n var length =\n typeof object.length === 'number'\n ? object.length\n : Object.keys(object).length;\n // `.repeat()` polyfill\n function repeat(s, n) {\n return new Array(n).join(s);\n }\n\n function _stringify(val) {\n switch (canonicalType(val)) {\n case 'null':\n case 'undefined':\n val = '[' + val + ']';\n break;\n case 'array':\n case 'object':\n val = jsonStringify(val, spaces, depth + 1);\n break;\n case 'boolean':\n case 'regexp':\n case 'symbol':\n case 'number':\n val =\n val === 0 && 1 / val === -Infinity // `-0`\n ? '-0'\n : val.toString();\n break;\n case 'bigint':\n val = val.toString() + 'n';\n break;\n case 'date':\n var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();\n val = '[Date: ' + sDate + ']';\n break;\n case 'buffer':\n var json = val.toJSON();\n // Based on the toJSON result\n json = json.data && json.type ? json.data : json;\n val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';\n break;\n default:\n val =\n val === '[Function]' || val === '[Circular]'\n ? val\n : JSON.stringify(val); // string\n }\n return val;\n }\n\n for (var i in object) {\n if (!Object.prototype.hasOwnProperty.call(object, i)) {\n continue; // not my business\n }\n --length;\n str +=\n '\\n ' +\n repeat(' ', space) +\n (Array.isArray(object) ? '' : '\"' + i + '\": ') + // key\n _stringify(object[i]) + // value\n (length ? ',' : ''); // comma\n }\n\n return (\n str +\n // [], {}\n (str.length !== 1 ? '\\n' + repeat(' ', --space) + end : end)\n );\n}\n\n/**\n * Return a new Thing that has the keys in sorted order. Recursive.\n *\n * If the Thing...\n * - has already been seen, return string `'[Circular]'`\n * - is `undefined`, return string `'[undefined]'`\n * - is `null`, return value `null`\n * - is some other primitive, return the value\n * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method\n * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.\n * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`\n *\n * @private\n * @see {@link exports.stringify}\n * @param {*} value Thing to inspect. May or may not have properties.\n * @param {Array} [stack=[]] Stack of seen values\n * @param {string} [typeHint] Type hint\n * @return {(Object|Array|Function|string|undefined)}\n */\nexports.canonicalize = function canonicalize(value, stack, typeHint) {\n var canonicalizedObj;\n /* eslint-disable no-unused-vars */\n var prop;\n /* eslint-enable no-unused-vars */\n typeHint = typeHint || canonicalType(value);\n function withStack(value, fn) {\n stack.push(value);\n fn();\n stack.pop();\n }\n\n stack = stack || [];\n\n if (stack.indexOf(value) !== -1) {\n return '[Circular]';\n }\n\n switch (typeHint) {\n case 'undefined':\n case 'buffer':\n case 'null':\n canonicalizedObj = value;\n break;\n case 'array':\n withStack(value, function() {\n canonicalizedObj = value.map(function(item) {\n return exports.canonicalize(item, stack);\n });\n });\n break;\n case 'function':\n /* eslint-disable-next-line no-unused-vars */\n for (prop in value) {\n canonicalizedObj = {};\n break;\n }\n /* eslint-enable guard-for-in */\n if (!canonicalizedObj) {\n canonicalizedObj = emptyRepresentation(value, typeHint);\n break;\n }\n /* falls through */\n case 'object':\n canonicalizedObj = canonicalizedObj || {};\n withStack(value, function() {\n Object.keys(value)\n .sort()\n .forEach(function(key) {\n canonicalizedObj[key] = exports.canonicalize(value[key], stack);\n });\n });\n break;\n case 'date':\n case 'number':\n case 'regexp':\n case 'boolean':\n case 'symbol':\n canonicalizedObj = value;\n break;\n default:\n canonicalizedObj = value + '';\n }\n\n return canonicalizedObj;\n};\n\n/**\n * @summary\n * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)\n * @description\n * When invoking this function you get a filter function that get the Error.stack as an input,\n * and return a prettify output.\n * (i.e: strip Mocha and internal node functions from stack trace).\n * @returns {Function}\n */\nexports.stackTraceFilter = function() {\n // TODO: Replace with `process.browser`\n var is = typeof document === 'undefined' ? {node: true} : {browser: true};\n var slash = path.sep;\n var cwd;\n if (is.node) {\n cwd = exports.cwd() + slash;\n } else {\n cwd = (typeof location === 'undefined'\n ? window.location\n : location\n ).href.replace(/\\/[^/]*$/, '/');\n slash = '/';\n }\n\n function isMochaInternal(line) {\n return (\n ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||\n ~line.indexOf(slash + 'mocha.js') ||\n ~line.indexOf(slash + 'mocha.min.js')\n );\n }\n\n function isNodeInternal(line) {\n return (\n ~line.indexOf('(timers.js:') ||\n ~line.indexOf('(events.js:') ||\n ~line.indexOf('(node.js:') ||\n ~line.indexOf('(module.js:') ||\n ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||\n false\n );\n }\n\n return function(stack) {\n stack = stack.split('\\n');\n\n stack = stack.reduce(function(list, line) {\n if (isMochaInternal(line)) {\n return list;\n }\n\n if (is.node && isNodeInternal(line)) {\n return list;\n }\n\n // Clean up cwd(absolute)\n if (/:\\d+:\\d+\\)?$/.test(line)) {\n line = line.replace('(' + cwd, '(');\n }\n\n list.push(line);\n return list;\n }, []);\n\n return stack.join('\\n');\n };\n};\n\n/**\n * Crude, but effective.\n * @public\n * @param {*} value\n * @returns {boolean} Whether or not `value` is a Promise\n */\nexports.isPromise = function isPromise(value) {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof value.then === 'function'\n );\n};\n\n/**\n * Clamps a numeric value to an inclusive range.\n *\n * @param {number} value - Value to be clamped.\n * @param {number[]} range - Two element array specifying [min, max] range.\n * @returns {number} clamped value\n */\nexports.clamp = function clamp(value, range) {\n return Math.min(Math.max(value, range[0]), range[1]);\n};\n\n/**\n * Single quote text by combining with undirectional ASCII quotation marks.\n *\n * @description\n * Provides a simple means of markup for quoting text to be used in output.\n * Use this to quote names of variables, methods, and packages.\n *\n * package 'foo' cannot be found\n *\n * @private\n * @param {string} str - Value to be quoted.\n * @returns {string} quoted value\n * @example\n * sQuote('n') // => 'n'\n */\nexports.sQuote = function(str) {\n return \"'\" + str + \"'\";\n};\n\n/**\n * Double quote text by combining with undirectional ASCII quotation marks.\n *\n * @description\n * Provides a simple means of markup for quoting text to be used in output.\n * Use this to quote names of datatypes, classes, pathnames, and strings.\n *\n * argument 'value' must be \"string\" or \"number\"\n *\n * @private\n * @param {string} str - Value to be quoted.\n * @returns {string} quoted value\n * @example\n * dQuote('number') // => \"number\"\n */\nexports.dQuote = function(str) {\n return '\"' + str + '\"';\n};\n\n/**\n * It's a noop.\n * @public\n */\nexports.noop = function() {};\n\n/**\n * Creates a map-like object.\n *\n * @description\n * A \"map\" is an object with no prototype, for our purposes. In some cases\n * this would be more appropriate than a `Map`, especially if your environment\n * doesn't support it. Recommended for use in Mocha's public APIs.\n *\n * @public\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Custom_and_Null_objects|MDN:Map}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Custom_and_Null_objects|MDN:Object.assign}\n * @param {...*} [obj] - Arguments to `Object.assign()`.\n * @returns {Object} An object with no prototype, having `...obj` properties\n */\nexports.createMap = function(obj) {\n return Object.assign.apply(\n null,\n [Object.create(null)].concat(Array.prototype.slice.call(arguments))\n );\n};\n\n/**\n * Creates a read-only map-like object.\n *\n * @description\n * This differs from {@link module:utils.createMap createMap} only in that\n * the argument must be non-empty, because the result is frozen.\n *\n * @see {@link module:utils.createMap createMap}\n * @param {...*} [obj] - Arguments to `Object.assign()`.\n * @returns {Object} A frozen object with no prototype, having `...obj` properties\n * @throws {TypeError} if argument is not a non-empty object.\n */\nexports.defineConstants = function(obj) {\n if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) {\n throw new TypeError('Invalid argument; expected a non-empty object');\n }\n return Object.freeze(exports.createMap(obj));\n};\n\n/**\n * Whether current version of Node support ES modules\n *\n * @description\n * Versions prior to 10 did not support ES Modules, and version 10 has an old incompatible version of ESM.\n * This function returns whether Node.JS has ES Module supports that is compatible with Mocha's needs,\n * which is version >=12.11.\n *\n * @param {partialSupport} whether the full Node.js ESM support is available (>= 12) or just something that supports the runtime (>= 10)\n *\n * @returns {Boolean} whether the current version of Node.JS supports ES Modules in a way that is compatible with Mocha\n */\nexports.supportsEsModules = function(partialSupport) {\n if (!exports.isBrowser() && process.versions && process.versions.node) {\n var versionFields = process.versions.node.split('.');\n var major = +versionFields[0];\n var minor = +versionFields[1];\n\n if (!partialSupport) {\n return major >= 13 || (major === 12 && minor >= 11);\n } else {\n return major >= 10;\n }\n }\n};\n\n/**\n * Returns current working directory\n *\n * Wrapper around `process.cwd()` for isolation\n * @private\n */\nexports.cwd = function cwd() {\n return process.cwd();\n};\n\n/**\n * Returns `true` if Mocha is running in a browser.\n * Checks for `process.browser`.\n * @returns {boolean}\n * @private\n */\nexports.isBrowser = function isBrowser() {\n return Boolean(process.browser);\n};\n\n/**\n * Lookup file names at the given `path`.\n *\n * @description\n * Filenames are returned in _traversal_ order by the OS/filesystem.\n * **Make no assumption that the names will be sorted in any fashion.**\n *\n * @public\n * @alias module:lib/cli.lookupFiles\n * @param {string} filepath - Base path to start searching from.\n * @param {string[]} [extensions=[]] - File extensions to look for.\n * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.\n * @return {string[]} An array of paths.\n * @throws {Error} if no files match pattern.\n * @throws {TypeError} if `filepath` is directory and `extensions` not provided.\n * @deprecated Moved to {@link module:lib/cli.lookupFiles}\n */\nexports.lookupFiles = (...args) => {\n if (exports.isBrowser()) {\n throw errors.createUnsupportedError(\n 'lookupFiles() is only supported in Node.js!'\n );\n }\n errors.deprecate(\n '`lookupFiles()` in module `mocha/lib/utils` has moved to module `mocha/lib/cli` and will be removed in the next major revision of Mocha'\n );\n return require('./cli').lookupFiles(...args);\n};\n\n/*\n * Casts `value` to an array; useful for optionally accepting array parameters\n *\n * It follows these rules, depending on `value`. If `value` is...\n * 1. `undefined`: return an empty Array\n * 2. `null`: return an array with a single `null` element\n * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable\n * 4. otherwise: return an array with a single element, `value`\n * @param {*} value - Something to cast to an Array\n * @returns {Array<*>}\n */\nexports.castArray = function castArray(value) {\n if (value === undefined) {\n return [];\n }\n if (value === null) {\n return [null];\n }\n if (\n typeof value === 'object' &&\n (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)\n ) {\n return Array.from(value);\n }\n return [value];\n};\n\nexports.constants = exports.defineConstants({\n MOCHA_ID_PROP_NAME\n});\n\n/**\n * Creates a new unique identifier\n * @returns {string} Unique identifier\n */\nexports.uniqueID = () => nanoid();\n\nexports.assignNewMochaID = obj => {\n const id = exports.uniqueID();\n Object.defineProperty(obj, MOCHA_ID_PROP_NAME, {\n get() {\n return id;\n }\n });\n return obj;\n};\n\n/**\n * Retrieves a Mocha ID from an object, if present.\n * @param {*} [obj] - Object\n * @returns {string|void}\n */\nexports.getMochaID = obj =>\n obj && typeof obj === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined;\n","'use strict';\nvar collection = require('../internals/collection');\nvar collectionStrong = require('../internals/collection-strong');\n\n// `Map` constructor\n// https://tc39.es/ecma262/#sec-map-objects\nmodule.exports = collection('Map', function (init) {\n return function Map() { return init(this, arguments.length ? arguments[0] : undefined); };\n}, collectionStrong);\n","'use strict';\n\n/**\n @module Pending\n*/\n\nmodule.exports = Pending;\n\n/**\n * Initialize a new `Pending` error with the given message.\n *\n * @param {string} message\n */\nfunction Pending(message) {\n this.message = message;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride,\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter;\nvar Pending = require('./pending');\nvar debug = require('debug')('mocha:runnable');\nvar milliseconds = require('ms');\nvar utils = require('./utils');\nconst {\n createInvalidExceptionError,\n createMultipleDoneError,\n createTimeoutError\n} = require('./errors');\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n * @private\n */\nvar Date = global.Date;\nvar setTimeout = global.setTimeout;\nvar clearTimeout = global.clearTimeout;\nvar toString = Object.prototype.toString;\n\nmodule.exports = Runnable;\n\n/**\n * Initialize a new `Runnable` with the given `title` and callback `fn`.\n *\n * @class\n * @extends external:EventEmitter\n * @public\n * @param {String} title\n * @param {Function} fn\n */\nfunction Runnable(title, fn) {\n this.title = title;\n this.fn = fn;\n this.body = (fn || '').toString();\n this.async = fn && fn.length;\n this.sync = !this.async;\n this._timeout = 2000;\n this._slow = 75;\n this._retries = -1;\n utils.assignNewMochaID(this);\n Object.defineProperty(this, 'id', {\n get() {\n return utils.getMochaID(this);\n }\n });\n this.reset();\n}\n\n/**\n * Inherit from `EventEmitter.prototype`.\n */\nutils.inherits(Runnable, EventEmitter);\n\n/**\n * Resets the state initially or for a next run.\n */\nRunnable.prototype.reset = function() {\n this.timedOut = false;\n this._currentRetry = 0;\n this.pending = false;\n delete this.state;\n delete this.err;\n};\n\n/**\n * Get current timeout value in msecs.\n *\n * @private\n * @returns {number} current timeout threshold value\n */\n/**\n * @summary\n * Set timeout threshold value (msecs).\n *\n * @description\n * A string argument can use shorthand (e.g., \"2s\") and will be converted.\n * The value will be clamped to range [0, 2^31-1].\n * If clamped value matches either range endpoint, timeouts will be disabled.\n *\n * @private\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value}\n * @param {number|string} ms - Timeout threshold value.\n * @returns {Runnable} this\n * @chainable\n */\nRunnable.prototype.timeout = function(ms) {\n if (!arguments.length) {\n return this._timeout;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n\n // Clamp to range\n var INT_MAX = Math.pow(2, 31) - 1;\n var range = [0, INT_MAX];\n ms = utils.clamp(ms, range);\n\n // see #1652 for reasoning\n if (ms === range[0] || ms === range[1]) {\n this._timeout = 0;\n } else {\n this._timeout = ms;\n }\n debug('timeout %d', this._timeout);\n\n if (this.timer) {\n this.resetTimeout();\n }\n return this;\n};\n\n/**\n * Set or get slow `ms`.\n *\n * @private\n * @param {number|string} ms\n * @return {Runnable|number} ms or Runnable instance.\n */\nRunnable.prototype.slow = function(ms) {\n if (!arguments.length || typeof ms === 'undefined') {\n return this._slow;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n debug('slow %d', ms);\n this._slow = ms;\n return this;\n};\n\n/**\n * Halt and mark as pending.\n *\n * @memberof Mocha.Runnable\n * @public\n */\nRunnable.prototype.skip = function() {\n this.pending = true;\n throw new Pending('sync skip; aborting execution');\n};\n\n/**\n * Check if this runnable or its parent suite is marked as pending.\n *\n * @private\n */\nRunnable.prototype.isPending = function() {\n return this.pending || (this.parent && this.parent.isPending());\n};\n\n/**\n * Return `true` if this Runnable has failed.\n * @return {boolean}\n * @private\n */\nRunnable.prototype.isFailed = function() {\n return !this.isPending() && this.state === constants.STATE_FAILED;\n};\n\n/**\n * Return `true` if this Runnable has passed.\n * @return {boolean}\n * @private\n */\nRunnable.prototype.isPassed = function() {\n return !this.isPending() && this.state === constants.STATE_PASSED;\n};\n\n/**\n * Set or get number of retries.\n *\n * @private\n */\nRunnable.prototype.retries = function(n) {\n if (!arguments.length) {\n return this._retries;\n }\n this._retries = n;\n};\n\n/**\n * Set or get current retry\n *\n * @private\n */\nRunnable.prototype.currentRetry = function(n) {\n if (!arguments.length) {\n return this._currentRetry;\n }\n this._currentRetry = n;\n};\n\n/**\n * Return the full title generated by recursively concatenating the parent's\n * full title.\n *\n * @memberof Mocha.Runnable\n * @public\n * @return {string}\n */\nRunnable.prototype.fullTitle = function() {\n return this.titlePath().join(' ');\n};\n\n/**\n * Return the title path generated by concatenating the parent's title path with the title.\n *\n * @memberof Mocha.Runnable\n * @public\n * @return {string}\n */\nRunnable.prototype.titlePath = function() {\n return this.parent.titlePath().concat([this.title]);\n};\n\n/**\n * Clear the timeout.\n *\n * @private\n */\nRunnable.prototype.clearTimeout = function() {\n clearTimeout(this.timer);\n};\n\n/**\n * Reset the timeout.\n *\n * @private\n */\nRunnable.prototype.resetTimeout = function() {\n var self = this;\n var ms = this.timeout();\n\n if (ms === 0) {\n return;\n }\n this.clearTimeout();\n this.timer = setTimeout(function() {\n if (self.timeout() === 0) {\n return;\n }\n self.callback(self._timeoutError(ms));\n self.timedOut = true;\n }, ms);\n};\n\n/**\n * Set or get a list of whitelisted globals for this test run.\n *\n * @private\n * @param {string[]} globals\n */\nRunnable.prototype.globals = function(globals) {\n if (!arguments.length) {\n return this._allowedGlobals;\n }\n this._allowedGlobals = globals;\n};\n\n/**\n * Run the test and invoke `fn(err)`.\n *\n * @param {Function} fn\n * @private\n */\nRunnable.prototype.run = function(fn) {\n var self = this;\n var start = new Date();\n var ctx = this.ctx;\n var finished;\n var errorWasHandled = false;\n\n if (this.isPending()) return fn();\n\n // Sometimes the ctx exists, but it is not runnable\n if (ctx && ctx.runnable) {\n ctx.runnable(this);\n }\n\n // called multiple times\n function multiple(err) {\n if (errorWasHandled) {\n return;\n }\n errorWasHandled = true;\n self.emit('error', createMultipleDoneError(self, err));\n }\n\n // finished\n function done(err) {\n var ms = self.timeout();\n if (self.timedOut) {\n return;\n }\n\n if (finished) {\n return multiple(err);\n }\n\n self.clearTimeout();\n self.duration = new Date() - start;\n finished = true;\n if (!err && self.duration > ms && ms > 0) {\n err = self._timeoutError(ms);\n }\n fn(err);\n }\n\n // for .resetTimeout() and Runner#uncaught()\n this.callback = done;\n\n if (this.fn && typeof this.fn.call !== 'function') {\n done(\n new TypeError(\n 'A runnable must be passed a function as its second argument.'\n )\n );\n return;\n }\n\n // explicit async with `done` argument\n if (this.async) {\n this.resetTimeout();\n\n // allows skip() to be used in an explicit async context\n this.skip = function asyncSkip() {\n this.pending = true;\n done();\n // halt execution, the uncaught handler will ignore the failure.\n throw new Pending('async skip; aborting execution');\n };\n\n try {\n callFnAsync(this.fn);\n } catch (err) {\n // handles async runnables which actually run synchronously\n errorWasHandled = true;\n if (err instanceof Pending) {\n return; // done() is already called in this.skip()\n } else if (this.allowUncaught) {\n throw err;\n }\n done(Runnable.toValueOrError(err));\n }\n return;\n }\n\n // sync or promise-returning\n try {\n callFn(this.fn);\n } catch (err) {\n errorWasHandled = true;\n if (err instanceof Pending) {\n return done();\n } else if (this.allowUncaught) {\n throw err;\n }\n done(Runnable.toValueOrError(err));\n }\n\n function callFn(fn) {\n var result = fn.call(ctx);\n if (result && typeof result.then === 'function') {\n self.resetTimeout();\n result.then(\n function() {\n done();\n // Return null so libraries like bluebird do not warn about\n // subsequently constructed Promises.\n return null;\n },\n function(reason) {\n done(reason || new Error('Promise rejected with no or falsy reason'));\n }\n );\n } else {\n if (self.asyncOnly) {\n return done(\n new Error(\n '--async-only option in use without declaring `done()` or returning a promise'\n )\n );\n }\n\n done();\n }\n }\n\n function callFnAsync(fn) {\n var result = fn.call(ctx, function(err) {\n if (err instanceof Error || toString.call(err) === '[object Error]') {\n return done(err);\n }\n if (err) {\n if (Object.prototype.toString.call(err) === '[object Object]') {\n return done(\n new Error('done() invoked with non-Error: ' + JSON.stringify(err))\n );\n }\n return done(new Error('done() invoked with non-Error: ' + err));\n }\n if (result && utils.isPromise(result)) {\n return done(\n new Error(\n 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'\n )\n );\n }\n\n done();\n });\n }\n};\n\n/**\n * Instantiates a \"timeout\" error\n *\n * @param {number} ms - Timeout (in milliseconds)\n * @returns {Error} a \"timeout\" error\n * @private\n */\nRunnable.prototype._timeoutError = function(ms) {\n let msg = `Timeout of ${ms}ms exceeded. For async tests and hooks, ensure \"done()\" is called; if returning a Promise, ensure it resolves.`;\n if (this.file) {\n msg += ' (' + this.file + ')';\n }\n return createTimeoutError(msg, ms, this.file);\n};\n\nvar constants = utils.defineConstants(\n /**\n * {@link Runnable}-related constants.\n * @public\n * @memberof Runnable\n * @readonly\n * @static\n * @alias constants\n * @enum {string}\n */\n {\n /**\n * Value of `state` prop when a `Runnable` has failed\n */\n STATE_FAILED: 'failed',\n /**\n * Value of `state` prop when a `Runnable` has passed\n */\n STATE_PASSED: 'passed',\n /**\n * Value of `state` prop when a `Runnable` has been skipped by user\n */\n STATE_PENDING: 'pending'\n }\n);\n\n/**\n * Given `value`, return identity if truthy, otherwise create an \"invalid exception\" error and return that.\n * @param {*} [value] - Value to return, if present\n * @returns {*|Error} `value`, otherwise an `Error`\n * @private\n */\nRunnable.toValueOrError = function(value) {\n return (\n value ||\n createInvalidExceptionError(\n 'Runnable failed with falsy or undefined exception. Please throw an Error instead.',\n value\n )\n );\n};\n\nRunnable.constants = constants;\n","'use strict';\n\nvar Runnable = require('./runnable');\nconst {inherits, constants} = require('./utils');\nconst {MOCHA_ID_PROP_NAME} = constants;\n\n/**\n * Expose `Hook`.\n */\n\nmodule.exports = Hook;\n\n/**\n * Initialize a new `Hook` with the given `title` and callback `fn`\n *\n * @class\n * @extends Runnable\n * @param {String} title\n * @param {Function} fn\n */\nfunction Hook(title, fn) {\n Runnable.call(this, title, fn);\n this.type = 'hook';\n}\n\n/**\n * Inherit from `Runnable.prototype`.\n */\ninherits(Hook, Runnable);\n\n/**\n * Resets the state for a next run.\n */\nHook.prototype.reset = function() {\n Runnable.prototype.reset.call(this);\n delete this._error;\n};\n\n/**\n * Get or set the test `err`.\n *\n * @memberof Hook\n * @public\n * @param {Error} err\n * @return {Error}\n */\nHook.prototype.error = function(err) {\n if (!arguments.length) {\n err = this._error;\n this._error = null;\n return err;\n }\n\n this._error = err;\n};\n\n/**\n * Returns an object suitable for IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nHook.prototype.serialize = function serialize() {\n return {\n $$isPending: this.isPending(),\n $$titlePath: this.titlePath(),\n ctx:\n this.ctx && this.ctx.currentTest\n ? {\n currentTest: {\n title: this.ctx.currentTest.title,\n [MOCHA_ID_PROP_NAME]: this.ctx.currentTest.id\n }\n }\n : {},\n parent: {\n [MOCHA_ID_PROP_NAME]: this.parent.id\n },\n title: this.title,\n type: this.type,\n [MOCHA_ID_PROP_NAME]: this.id\n };\n};\n","'use strict';\n\n/**\n * Module dependencies.\n * @private\n */\nconst {EventEmitter} = require('events');\nconst Hook = require('./hook');\nvar {\n assignNewMochaID,\n clamp,\n constants: utilsConstants,\n createMap,\n defineConstants,\n getMochaID,\n inherits,\n isString\n} = require('./utils');\nconst debug = require('debug')('mocha:suite');\nconst milliseconds = require('ms');\nconst errors = require('./errors');\n\nconst {MOCHA_ID_PROP_NAME} = utilsConstants;\n\n/**\n * Expose `Suite`.\n */\n\nexports = module.exports = Suite;\n\n/**\n * Create a new `Suite` with the given `title` and parent `Suite`.\n *\n * @public\n * @param {Suite} parent - Parent suite (required!)\n * @param {string} title - Title\n * @return {Suite}\n */\nSuite.create = function(parent, title) {\n var suite = new Suite(title, parent.ctx);\n suite.parent = parent;\n title = suite.fullTitle();\n parent.addSuite(suite);\n return suite;\n};\n\n/**\n * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`.\n *\n * @public\n * @class\n * @extends EventEmitter\n * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter}\n * @param {string} title - Suite title.\n * @param {Context} parentContext - Parent context instance.\n * @param {boolean} [isRoot=false] - Whether this is the root suite.\n */\nfunction Suite(title, parentContext, isRoot) {\n if (!isString(title)) {\n throw errors.createInvalidArgumentTypeError(\n 'Suite argument \"title\" must be a string. Received type \"' +\n typeof title +\n '\"',\n 'title',\n 'string'\n );\n }\n this.title = title;\n function Context() {}\n Context.prototype = parentContext;\n this.ctx = new Context();\n this.suites = [];\n this.tests = [];\n this.root = isRoot === true;\n this.pending = false;\n this._retries = -1;\n this._beforeEach = [];\n this._beforeAll = [];\n this._afterEach = [];\n this._afterAll = [];\n this._timeout = 2000;\n this._slow = 75;\n this._bail = false;\n this._onlyTests = [];\n this._onlySuites = [];\n assignNewMochaID(this);\n\n Object.defineProperty(this, 'id', {\n get() {\n return getMochaID(this);\n }\n });\n\n this.reset();\n\n this.on('newListener', function(event) {\n if (deprecatedEvents[event]) {\n errors.deprecate(\n 'Event \"' +\n event +\n '\" is deprecated. Please let the Mocha team know about your use case: https://git.io/v6Lwm'\n );\n }\n });\n}\n\n/**\n * Inherit from `EventEmitter.prototype`.\n */\ninherits(Suite, EventEmitter);\n\n/**\n * Resets the state initially or for a next run.\n */\nSuite.prototype.reset = function() {\n this.delayed = false;\n function doReset(thingToReset) {\n thingToReset.reset();\n }\n this.suites.forEach(doReset);\n this.tests.forEach(doReset);\n this._beforeEach.forEach(doReset);\n this._afterEach.forEach(doReset);\n this._beforeAll.forEach(doReset);\n this._afterAll.forEach(doReset);\n};\n\n/**\n * Return a clone of this `Suite`.\n *\n * @private\n * @return {Suite}\n */\nSuite.prototype.clone = function() {\n var suite = new Suite(this.title);\n debug('clone');\n suite.ctx = this.ctx;\n suite.root = this.root;\n suite.timeout(this.timeout());\n suite.retries(this.retries());\n suite.slow(this.slow());\n suite.bail(this.bail());\n return suite;\n};\n\n/**\n * Set or get timeout `ms` or short-hand such as \"2s\".\n *\n * @private\n * @todo Do not attempt to set value if `ms` is undefined\n * @param {number|string} ms\n * @return {Suite|number} for chaining\n */\nSuite.prototype.timeout = function(ms) {\n if (!arguments.length) {\n return this._timeout;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n\n // Clamp to range\n var INT_MAX = Math.pow(2, 31) - 1;\n var range = [0, INT_MAX];\n ms = clamp(ms, range);\n\n debug('timeout %d', ms);\n this._timeout = parseInt(ms, 10);\n return this;\n};\n\n/**\n * Set or get number of times to retry a failed test.\n *\n * @private\n * @param {number|string} n\n * @return {Suite|number} for chaining\n */\nSuite.prototype.retries = function(n) {\n if (!arguments.length) {\n return this._retries;\n }\n debug('retries %d', n);\n this._retries = parseInt(n, 10) || 0;\n return this;\n};\n\n/**\n * Set or get slow `ms` or short-hand such as \"2s\".\n *\n * @private\n * @param {number|string} ms\n * @return {Suite|number} for chaining\n */\nSuite.prototype.slow = function(ms) {\n if (!arguments.length) {\n return this._slow;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n debug('slow %d', ms);\n this._slow = ms;\n return this;\n};\n\n/**\n * Set or get whether to bail after first error.\n *\n * @private\n * @param {boolean} bail\n * @return {Suite|number} for chaining\n */\nSuite.prototype.bail = function(bail) {\n if (!arguments.length) {\n return this._bail;\n }\n debug('bail %s', bail);\n this._bail = bail;\n return this;\n};\n\n/**\n * Check if this suite or its parent suite is marked as pending.\n *\n * @private\n */\nSuite.prototype.isPending = function() {\n return this.pending || (this.parent && this.parent.isPending());\n};\n\n/**\n * Generic hook-creator.\n * @private\n * @param {string} title - Title of hook\n * @param {Function} fn - Hook callback\n * @returns {Hook} A new hook\n */\nSuite.prototype._createHook = function(title, fn) {\n var hook = new Hook(title, fn);\n hook.parent = this;\n hook.timeout(this.timeout());\n hook.retries(this.retries());\n hook.slow(this.slow());\n hook.ctx = this.ctx;\n hook.file = this.file;\n return hook;\n};\n\n/**\n * Run `fn(test[, done])` before running tests.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.beforeAll = function(title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"before all\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._beforeAll.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` after running tests.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.afterAll = function(title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"after all\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._afterAll.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` before each test case.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.beforeEach = function(title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"before each\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._beforeEach.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` after each test case.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.afterEach = function(title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"after each\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._afterEach.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook);\n return this;\n};\n\n/**\n * Add a test `suite`.\n *\n * @private\n * @param {Suite} suite\n * @return {Suite} for chaining\n */\nSuite.prototype.addSuite = function(suite) {\n suite.parent = this;\n suite.root = false;\n suite.timeout(this.timeout());\n suite.retries(this.retries());\n suite.slow(this.slow());\n suite.bail(this.bail());\n this.suites.push(suite);\n this.emit(constants.EVENT_SUITE_ADD_SUITE, suite);\n return this;\n};\n\n/**\n * Add a `test` to this suite.\n *\n * @private\n * @param {Test} test\n * @return {Suite} for chaining\n */\nSuite.prototype.addTest = function(test) {\n test.parent = this;\n test.timeout(this.timeout());\n test.retries(this.retries());\n test.slow(this.slow());\n test.ctx = this.ctx;\n this.tests.push(test);\n this.emit(constants.EVENT_SUITE_ADD_TEST, test);\n return this;\n};\n\n/**\n * Return the full title generated by recursively concatenating the parent's\n * full title.\n *\n * @memberof Suite\n * @public\n * @return {string}\n */\nSuite.prototype.fullTitle = function() {\n return this.titlePath().join(' ');\n};\n\n/**\n * Return the title path generated by recursively concatenating the parent's\n * title path.\n *\n * @memberof Suite\n * @public\n * @return {string}\n */\nSuite.prototype.titlePath = function() {\n var result = [];\n if (this.parent) {\n result = result.concat(this.parent.titlePath());\n }\n if (!this.root) {\n result.push(this.title);\n }\n return result;\n};\n\n/**\n * Return the total number of tests.\n *\n * @memberof Suite\n * @public\n * @return {number}\n */\nSuite.prototype.total = function() {\n return (\n this.suites.reduce(function(sum, suite) {\n return sum + suite.total();\n }, 0) + this.tests.length\n );\n};\n\n/**\n * Iterates through each suite recursively to find all tests. Applies a\n * function in the format `fn(test)`.\n *\n * @private\n * @param {Function} fn\n * @return {Suite}\n */\nSuite.prototype.eachTest = function(fn) {\n this.tests.forEach(fn);\n this.suites.forEach(function(suite) {\n suite.eachTest(fn);\n });\n return this;\n};\n\n/**\n * This will run the root suite if we happen to be running in delayed mode.\n * @private\n */\nSuite.prototype.run = function run() {\n if (this.root) {\n this.emit(constants.EVENT_ROOT_SUITE_RUN);\n }\n};\n\n/**\n * Determines whether a suite has an `only` test or suite as a descendant.\n *\n * @private\n * @returns {Boolean}\n */\nSuite.prototype.hasOnly = function hasOnly() {\n return (\n this._onlyTests.length > 0 ||\n this._onlySuites.length > 0 ||\n this.suites.some(function(suite) {\n return suite.hasOnly();\n })\n );\n};\n\n/**\n * Filter suites based on `isOnly` logic.\n *\n * @private\n * @returns {Boolean}\n */\nSuite.prototype.filterOnly = function filterOnly() {\n if (this._onlyTests.length) {\n // If the suite contains `only` tests, run those and ignore any nested suites.\n this.tests = this._onlyTests;\n this.suites = [];\n } else {\n // Otherwise, do not run any of the tests in this suite.\n this.tests = [];\n this._onlySuites.forEach(function(onlySuite) {\n // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.\n // Otherwise, all of the tests on this `only` suite should be run, so don't filter it.\n if (onlySuite.hasOnly()) {\n onlySuite.filterOnly();\n }\n });\n // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.\n var onlySuites = this._onlySuites;\n this.suites = this.suites.filter(function(childSuite) {\n return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly();\n });\n }\n // Keep the suite only if there is something to run\n return this.tests.length > 0 || this.suites.length > 0;\n};\n\n/**\n * Adds a suite to the list of subsuites marked `only`.\n *\n * @private\n * @param {Suite} suite\n */\nSuite.prototype.appendOnlySuite = function(suite) {\n this._onlySuites.push(suite);\n};\n\n/**\n * Marks a suite to be `only`.\n *\n * @private\n */\nSuite.prototype.markOnly = function() {\n this.parent && this.parent.appendOnlySuite(this);\n};\n\n/**\n * Adds a test to the list of tests marked `only`.\n *\n * @private\n * @param {Test} test\n */\nSuite.prototype.appendOnlyTest = function(test) {\n this._onlyTests.push(test);\n};\n\n/**\n * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants.\n * @private\n */\nSuite.prototype.getHooks = function getHooks(name) {\n return this['_' + name];\n};\n\n/**\n * cleans all references from this suite and all child suites.\n */\nSuite.prototype.dispose = function() {\n this.suites.forEach(function(suite) {\n suite.dispose();\n });\n this.cleanReferences();\n};\n\n/**\n * Cleans up the references to all the deferred functions\n * (before/after/beforeEach/afterEach) and tests of a Suite.\n * These must be deleted otherwise a memory leak can happen,\n * as those functions may reference variables from closures,\n * thus those variables can never be garbage collected as long\n * as the deferred functions exist.\n *\n * @private\n */\nSuite.prototype.cleanReferences = function cleanReferences() {\n function cleanArrReferences(arr) {\n for (var i = 0; i < arr.length; i++) {\n delete arr[i].fn;\n }\n }\n\n if (Array.isArray(this._beforeAll)) {\n cleanArrReferences(this._beforeAll);\n }\n\n if (Array.isArray(this._beforeEach)) {\n cleanArrReferences(this._beforeEach);\n }\n\n if (Array.isArray(this._afterAll)) {\n cleanArrReferences(this._afterAll);\n }\n\n if (Array.isArray(this._afterEach)) {\n cleanArrReferences(this._afterEach);\n }\n\n for (var i = 0; i < this.tests.length; i++) {\n delete this.tests[i].fn;\n }\n};\n\n/**\n * Returns an object suitable for IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nSuite.prototype.serialize = function serialize() {\n return {\n _bail: this._bail,\n $$fullTitle: this.fullTitle(),\n $$isPending: this.isPending(),\n root: this.root,\n title: this.title,\n id: this.id,\n parent: this.parent ? {[MOCHA_ID_PROP_NAME]: this.parent.id} : null\n };\n};\n\nvar constants = defineConstants(\n /**\n * {@link Suite}-related constants.\n * @public\n * @memberof Suite\n * @alias constants\n * @readonly\n * @static\n * @enum {string}\n */\n {\n /**\n * Event emitted after a test file has been loaded Not emitted in browser.\n */\n EVENT_FILE_POST_REQUIRE: 'post-require',\n /**\n * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.\n */\n EVENT_FILE_PRE_REQUIRE: 'pre-require',\n /**\n * Event emitted immediately after a test file has been loaded. Not emitted in browser.\n */\n EVENT_FILE_REQUIRE: 'require',\n /**\n * Event emitted when `global.run()` is called (use with `delay` option)\n */\n EVENT_ROOT_SUITE_RUN: 'run',\n\n /**\n * Namespace for collection of a `Suite`'s \"after all\" hooks\n */\n HOOK_TYPE_AFTER_ALL: 'afterAll',\n /**\n * Namespace for collection of a `Suite`'s \"after each\" hooks\n */\n HOOK_TYPE_AFTER_EACH: 'afterEach',\n /**\n * Namespace for collection of a `Suite`'s \"before all\" hooks\n */\n HOOK_TYPE_BEFORE_ALL: 'beforeAll',\n /**\n * Namespace for collection of a `Suite`'s \"before all\" hooks\n */\n HOOK_TYPE_BEFORE_EACH: 'beforeEach',\n\n // the following events are all deprecated\n\n /**\n * Emitted after an \"after all\" `Hook` has been added to a `Suite`. Deprecated\n */\n EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll',\n /**\n * Emitted after an \"after each\" `Hook` has been added to a `Suite` Deprecated\n */\n EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach',\n /**\n * Emitted after an \"before all\" `Hook` has been added to a `Suite` Deprecated\n */\n EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll',\n /**\n * Emitted after an \"before each\" `Hook` has been added to a `Suite` Deprecated\n */\n EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach',\n /**\n * Emitted after a child `Suite` has been added to a `Suite`. Deprecated\n */\n EVENT_SUITE_ADD_SUITE: 'suite',\n /**\n * Emitted after a `Test` has been added to a `Suite`. Deprecated\n */\n EVENT_SUITE_ADD_TEST: 'test'\n }\n);\n\n/**\n * @summary There are no known use cases for these events.\n * @desc This is a `Set`-like object having all keys being the constant's string value and the value being `true`.\n * @todo Remove eventually\n * @type {Object}\n * @ignore\n */\nvar deprecatedEvents = Object.keys(constants)\n .filter(function(constant) {\n return constant.substring(0, 15) === 'EVENT_SUITE_ADD';\n })\n .reduce(function(acc, constant) {\n acc[constants[constant]] = true;\n return acc;\n }, createMap());\n\nSuite.constants = constants;\n","'use strict';\n\n/**\n * Module dependencies.\n * @private\n */\nvar util = require('util');\nvar EventEmitter = require('events').EventEmitter;\nvar Pending = require('./pending');\nvar utils = require('./utils');\nvar debug = require('debug')('mocha:runner');\nvar Runnable = require('./runnable');\nvar Suite = require('./suite');\nvar HOOK_TYPE_BEFORE_EACH = Suite.constants.HOOK_TYPE_BEFORE_EACH;\nvar HOOK_TYPE_AFTER_EACH = Suite.constants.HOOK_TYPE_AFTER_EACH;\nvar HOOK_TYPE_AFTER_ALL = Suite.constants.HOOK_TYPE_AFTER_ALL;\nvar HOOK_TYPE_BEFORE_ALL = Suite.constants.HOOK_TYPE_BEFORE_ALL;\nvar EVENT_ROOT_SUITE_RUN = Suite.constants.EVENT_ROOT_SUITE_RUN;\nvar STATE_FAILED = Runnable.constants.STATE_FAILED;\nvar STATE_PASSED = Runnable.constants.STATE_PASSED;\nvar STATE_PENDING = Runnable.constants.STATE_PENDING;\nvar dQuote = utils.dQuote;\nvar sQuote = utils.sQuote;\nvar stackFilter = utils.stackTraceFilter();\nvar stringify = utils.stringify;\n\nconst {\n createInvalidExceptionError,\n createUnsupportedError,\n createFatalError,\n isMochaError,\n constants: errorConstants\n} = require('./errors');\n\n/**\n * Non-enumerable globals.\n * @private\n * @readonly\n */\nvar globals = [\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'XMLHttpRequest',\n 'Date',\n 'setImmediate',\n 'clearImmediate'\n];\n\nvar constants = utils.defineConstants(\n /**\n * {@link Runner}-related constants.\n * @public\n * @memberof Runner\n * @readonly\n * @alias constants\n * @static\n * @enum {string}\n */\n {\n /**\n * Emitted when {@link Hook} execution begins\n */\n EVENT_HOOK_BEGIN: 'hook',\n /**\n * Emitted when {@link Hook} execution ends\n */\n EVENT_HOOK_END: 'hook end',\n /**\n * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)\n */\n EVENT_RUN_BEGIN: 'start',\n /**\n * Emitted when Root {@link Suite} execution has been delayed via `delay` option\n */\n EVENT_DELAY_BEGIN: 'waiting',\n /**\n * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()`\n */\n EVENT_DELAY_END: 'ready',\n /**\n * Emitted when Root {@link Suite} execution ends\n */\n EVENT_RUN_END: 'end',\n /**\n * Emitted when {@link Suite} execution begins\n */\n EVENT_SUITE_BEGIN: 'suite',\n /**\n * Emitted when {@link Suite} execution ends\n */\n EVENT_SUITE_END: 'suite end',\n /**\n * Emitted when {@link Test} execution begins\n */\n EVENT_TEST_BEGIN: 'test',\n /**\n * Emitted when {@link Test} execution ends\n */\n EVENT_TEST_END: 'test end',\n /**\n * Emitted when {@link Test} execution fails\n */\n EVENT_TEST_FAIL: 'fail',\n /**\n * Emitted when {@link Test} execution succeeds\n */\n EVENT_TEST_PASS: 'pass',\n /**\n * Emitted when {@link Test} becomes pending\n */\n EVENT_TEST_PENDING: 'pending',\n /**\n * Emitted when {@link Test} execution has failed, but will retry\n */\n EVENT_TEST_RETRY: 'retry',\n /**\n * Initial state of Runner\n */\n STATE_IDLE: 'idle',\n /**\n * State set to this value when the Runner has started running\n */\n STATE_RUNNING: 'running',\n /**\n * State set to this value when the Runner has stopped\n */\n STATE_STOPPED: 'stopped'\n }\n);\n\nclass Runner extends EventEmitter {\n /**\n * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.\n *\n * @extends external:EventEmitter\n * @public\n * @class\n * @param {Suite} suite - Root suite\n * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility).\n * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.\n * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.\n */\n constructor(suite, opts) {\n super();\n if (opts === undefined) {\n opts = {};\n }\n if (typeof opts === 'boolean') {\n // TODO: deprecate this\n this._delay = opts;\n opts = {};\n } else {\n this._delay = opts.delay;\n }\n var self = this;\n this._globals = [];\n this._abort = false;\n this.suite = suite;\n this._opts = opts;\n this.state = constants.STATE_IDLE;\n this.total = suite.total();\n this.failures = 0;\n /**\n * @type {Map>>}\n */\n this._eventListeners = new Map();\n this.on(constants.EVENT_TEST_END, function(test) {\n if (test.type === 'test' && test.retriedTest() && test.parent) {\n var idx =\n test.parent.tests && test.parent.tests.indexOf(test.retriedTest());\n if (idx > -1) test.parent.tests[idx] = test;\n }\n self.checkGlobals(test);\n });\n this.on(constants.EVENT_HOOK_END, function(hook) {\n self.checkGlobals(hook);\n });\n this._defaultGrep = /.*/;\n this.grep(this._defaultGrep);\n this.globals(this.globalProps());\n\n this.uncaught = this._uncaught.bind(this);\n this.unhandled = (reason, promise) => {\n if (isMochaError(reason)) {\n debug(\n 'trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:',\n reason\n );\n this.uncaught(reason);\n } else {\n debug(\n 'trapped unhandled rejection from (probably) user code; re-emitting on process'\n );\n this._removeEventListener(\n process,\n 'unhandledRejection',\n this.unhandled\n );\n try {\n process.emit('unhandledRejection', reason, promise);\n } finally {\n this._addEventListener(process, 'unhandledRejection', this.unhandled);\n }\n }\n };\n }\n}\n\n/**\n * Wrapper for setImmediate, process.nextTick, or browser polyfill.\n *\n * @param {Function} fn\n * @private\n */\nRunner.immediately = global.setImmediate || process.nextTick;\n\n/**\n * Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed.\n * @param {EventEmitter} target - The `EventEmitter`\n * @param {string} eventName - The event name\n * @param {string} fn - Listener function\n * @private\n */\nRunner.prototype._addEventListener = function(target, eventName, listener) {\n debug(\n '_addEventListener(): adding for event %s; %d current listeners',\n eventName,\n target.listenerCount(eventName)\n );\n /* istanbul ignore next */\n if (\n this._eventListeners.has(target) &&\n this._eventListeners.get(target).has(eventName) &&\n this._eventListeners\n .get(target)\n .get(eventName)\n .has(listener)\n ) {\n debug(\n 'warning: tried to attach duplicate event listener for %s',\n eventName\n );\n return;\n }\n target.on(eventName, listener);\n const targetListeners = this._eventListeners.has(target)\n ? this._eventListeners.get(target)\n : new Map();\n const targetEventListeners = targetListeners.has(eventName)\n ? targetListeners.get(eventName)\n : new Set();\n targetEventListeners.add(listener);\n targetListeners.set(eventName, targetEventListeners);\n this._eventListeners.set(target, targetListeners);\n};\n\n/**\n * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping.\n * @param {EventEmitter} target - The `EventEmitter`\n * @param {string} eventName - The event name\n * @param {function} listener - Listener function\n * @private\n */\nRunner.prototype._removeEventListener = function(target, eventName, listener) {\n target.removeListener(eventName, listener);\n\n if (this._eventListeners.has(target)) {\n const targetListeners = this._eventListeners.get(target);\n if (targetListeners.has(eventName)) {\n const targetEventListeners = targetListeners.get(eventName);\n targetEventListeners.delete(listener);\n if (!targetEventListeners.size) {\n targetListeners.delete(eventName);\n }\n }\n if (!targetListeners.size) {\n this._eventListeners.delete(target);\n }\n } else {\n debug('trying to remove listener for untracked object %s', target);\n }\n};\n\n/**\n * Removes all event handlers set during a run on this instance.\n * Remark: this does _not_ clean/dispose the tests or suites themselves.\n */\nRunner.prototype.dispose = function() {\n this.removeAllListeners();\n this._eventListeners.forEach((targetListeners, target) => {\n targetListeners.forEach((targetEventListeners, eventName) => {\n targetEventListeners.forEach(listener => {\n target.removeListener(eventName, listener);\n });\n });\n });\n this._eventListeners.clear();\n};\n\n/**\n * Run tests with full titles matching `re`. Updates runner.total\n * with number of tests matched.\n *\n * @public\n * @memberof Runner\n * @param {RegExp} re\n * @param {boolean} invert\n * @return {Runner} Runner instance.\n */\nRunner.prototype.grep = function(re, invert) {\n debug('grep(): setting to %s', re);\n this._grep = re;\n this._invert = invert;\n this.total = this.grepTotal(this.suite);\n return this;\n};\n\n/**\n * Returns the number of tests matching the grep search for the\n * given suite.\n *\n * @memberof Runner\n * @public\n * @param {Suite} suite\n * @return {number}\n */\nRunner.prototype.grepTotal = function(suite) {\n var self = this;\n var total = 0;\n\n suite.eachTest(function(test) {\n var match = self._grep.test(test.fullTitle());\n if (self._invert) {\n match = !match;\n }\n if (match) {\n total++;\n }\n });\n\n return total;\n};\n\n/**\n * Return a list of global properties.\n *\n * @return {Array}\n * @private\n */\nRunner.prototype.globalProps = function() {\n var props = Object.keys(global);\n\n // non-enumerables\n for (var i = 0; i < globals.length; ++i) {\n if (~props.indexOf(globals[i])) {\n continue;\n }\n props.push(globals[i]);\n }\n\n return props;\n};\n\n/**\n * Allow the given `arr` of globals.\n *\n * @public\n * @memberof Runner\n * @param {Array} arr\n * @return {Runner} Runner instance.\n */\nRunner.prototype.globals = function(arr) {\n if (!arguments.length) {\n return this._globals;\n }\n debug('globals(): setting to %O', arr);\n this._globals = this._globals.concat(arr);\n return this;\n};\n\n/**\n * Check for global variable leaks.\n *\n * @private\n */\nRunner.prototype.checkGlobals = function(test) {\n if (!this.checkLeaks) {\n return;\n }\n var ok = this._globals;\n\n var globals = this.globalProps();\n var leaks;\n\n if (test) {\n ok = ok.concat(test._allowedGlobals || []);\n }\n\n if (this.prevGlobalsLength === globals.length) {\n return;\n }\n this.prevGlobalsLength = globals.length;\n\n leaks = filterLeaks(ok, globals);\n this._globals = this._globals.concat(leaks);\n\n if (leaks.length) {\n var msg = 'global leak(s) detected: %s';\n var error = new Error(util.format(msg, leaks.map(sQuote).join(', ')));\n this.fail(test, error);\n }\n};\n\n/**\n * Fail the given `test`.\n *\n * If `test` is a hook, failures work in the following pattern:\n * - If bail, run corresponding `after each` and `after` hooks,\n * then exit\n * - Failed `before` hook skips all tests in a suite and subsuites,\n * but jumps to corresponding `after` hook\n * - Failed `before each` hook skips remaining tests in a\n * suite and jumps to corresponding `after each` hook,\n * which is run only once\n * - Failed `after` hook does not alter execution order\n * - Failed `after each` hook skips remaining tests in a\n * suite and subsuites, but executes other `after each`\n * hooks\n *\n * @private\n * @param {Runnable} test\n * @param {Error} err\n * @param {boolean} [force=false] - Whether to fail a pending test.\n */\nRunner.prototype.fail = function(test, err, force) {\n force = force === true;\n if (test.isPending() && !force) {\n return;\n }\n if (this.state === constants.STATE_STOPPED) {\n if (err.code === errorConstants.MULTIPLE_DONE) {\n throw err;\n }\n throw createFatalError(\n 'Test failed after root suite execution completed!',\n err\n );\n }\n\n ++this.failures;\n debug('total number of failures: %d', this.failures);\n test.state = STATE_FAILED;\n\n if (!isError(err)) {\n err = thrown2Error(err);\n }\n\n try {\n err.stack =\n this.fullStackTrace || !err.stack ? err.stack : stackFilter(err.stack);\n } catch (ignore) {\n // some environments do not take kindly to monkeying with the stack\n }\n\n this.emit(constants.EVENT_TEST_FAIL, test, err);\n};\n\n/**\n * Run hook `name` callbacks and then invoke `fn()`.\n *\n * @private\n * @param {string} name\n * @param {Function} fn\n */\n\nRunner.prototype.hook = function(name, fn) {\n var suite = this.suite;\n var hooks = suite.getHooks(name);\n var self = this;\n\n function next(i) {\n var hook = hooks[i];\n if (!hook) {\n return fn();\n }\n self.currentRunnable = hook;\n\n if (name === HOOK_TYPE_BEFORE_ALL) {\n hook.ctx.currentTest = hook.parent.tests[0];\n } else if (name === HOOK_TYPE_AFTER_ALL) {\n hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1];\n } else {\n hook.ctx.currentTest = self.test;\n }\n\n setHookTitle(hook);\n\n hook.allowUncaught = self.allowUncaught;\n\n self.emit(constants.EVENT_HOOK_BEGIN, hook);\n\n if (!hook.listeners('error').length) {\n self._addEventListener(hook, 'error', function(err) {\n self.fail(hook, err);\n });\n }\n\n hook.run(function cbHookRun(err) {\n var testError = hook.error();\n if (testError) {\n self.fail(self.test, testError);\n }\n // conditional skip\n if (hook.pending) {\n if (name === HOOK_TYPE_AFTER_EACH) {\n // TODO define and implement use case\n if (self.test) {\n self.test.pending = true;\n }\n } else if (name === HOOK_TYPE_BEFORE_EACH) {\n if (self.test) {\n self.test.pending = true;\n }\n self.emit(constants.EVENT_HOOK_END, hook);\n hook.pending = false; // activates hook for next test\n return fn(new Error('abort hookDown'));\n } else if (name === HOOK_TYPE_BEFORE_ALL) {\n suite.tests.forEach(function(test) {\n test.pending = true;\n });\n suite.suites.forEach(function(suite) {\n suite.pending = true;\n });\n hooks = [];\n } else {\n hook.pending = false;\n var errForbid = createUnsupportedError('`this.skip` forbidden');\n self.fail(hook, errForbid);\n return fn(errForbid);\n }\n } else if (err) {\n self.fail(hook, err);\n // stop executing hooks, notify callee of hook err\n return fn(err);\n }\n self.emit(constants.EVENT_HOOK_END, hook);\n delete hook.ctx.currentTest;\n setHookTitle(hook);\n next(++i);\n });\n\n function setHookTitle(hook) {\n hook.originalTitle = hook.originalTitle || hook.title;\n if (hook.ctx && hook.ctx.currentTest) {\n hook.title =\n hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);\n } else {\n var parentTitle;\n if (hook.parent.title) {\n parentTitle = hook.parent.title;\n } else {\n parentTitle = hook.parent.root ? '{root}' : '';\n }\n hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);\n }\n }\n }\n\n Runner.immediately(function() {\n next(0);\n });\n};\n\n/**\n * Run hook `name` for the given array of `suites`\n * in order, and callback `fn(err, errSuite)`.\n *\n * @private\n * @param {string} name\n * @param {Array} suites\n * @param {Function} fn\n */\nRunner.prototype.hooks = function(name, suites, fn) {\n var self = this;\n var orig = this.suite;\n\n function next(suite) {\n self.suite = suite;\n\n if (!suite) {\n self.suite = orig;\n return fn();\n }\n\n self.hook(name, function(err) {\n if (err) {\n var errSuite = self.suite;\n self.suite = orig;\n return fn(err, errSuite);\n }\n\n next(suites.pop());\n });\n }\n\n next(suites.pop());\n};\n\n/**\n * Run hooks from the top level down.\n *\n * @param {String} name\n * @param {Function} fn\n * @private\n */\nRunner.prototype.hookUp = function(name, fn) {\n var suites = [this.suite].concat(this.parents()).reverse();\n this.hooks(name, suites, fn);\n};\n\n/**\n * Run hooks from the bottom up.\n *\n * @param {String} name\n * @param {Function} fn\n * @private\n */\nRunner.prototype.hookDown = function(name, fn) {\n var suites = [this.suite].concat(this.parents());\n this.hooks(name, suites, fn);\n};\n\n/**\n * Return an array of parent Suites from\n * closest to furthest.\n *\n * @return {Array}\n * @private\n */\nRunner.prototype.parents = function() {\n var suite = this.suite;\n var suites = [];\n while (suite.parent) {\n suite = suite.parent;\n suites.push(suite);\n }\n return suites;\n};\n\n/**\n * Run the current test and callback `fn(err)`.\n *\n * @param {Function} fn\n * @private\n */\nRunner.prototype.runTest = function(fn) {\n var self = this;\n var test = this.test;\n\n if (!test) {\n return;\n }\n\n if (this.asyncOnly) {\n test.asyncOnly = true;\n }\n this._addEventListener(test, 'error', function(err) {\n self.fail(test, err);\n });\n if (this.allowUncaught) {\n test.allowUncaught = true;\n return test.run(fn);\n }\n try {\n test.run(fn);\n } catch (err) {\n fn(err);\n }\n};\n\n/**\n * Run tests in the given `suite` and invoke the callback `fn()` when complete.\n *\n * @private\n * @param {Suite} suite\n * @param {Function} fn\n */\nRunner.prototype.runTests = function(suite, fn) {\n var self = this;\n var tests = suite.tests.slice();\n var test;\n\n function hookErr(_, errSuite, after) {\n // before/after Each hook for errSuite failed:\n var orig = self.suite;\n\n // for failed 'after each' hook start from errSuite parent,\n // otherwise start from errSuite itself\n self.suite = after ? errSuite.parent : errSuite;\n\n if (self.suite) {\n // call hookUp afterEach\n self.hookUp(HOOK_TYPE_AFTER_EACH, function(err2, errSuite2) {\n self.suite = orig;\n // some hooks may fail even now\n if (err2) {\n return hookErr(err2, errSuite2, true);\n }\n // report error suite\n fn(errSuite);\n });\n } else {\n // there is no need calling other 'after each' hooks\n self.suite = orig;\n fn(errSuite);\n }\n }\n\n function next(err, errSuite) {\n // if we bail after first err\n if (self.failures && suite._bail) {\n tests = [];\n }\n\n if (self._abort) {\n return fn();\n }\n\n if (err) {\n return hookErr(err, errSuite, true);\n }\n\n // next test\n test = tests.shift();\n\n // all done\n if (!test) {\n return fn();\n }\n\n // grep\n var match = self._grep.test(test.fullTitle());\n if (self._invert) {\n match = !match;\n }\n if (!match) {\n // Run immediately only if we have defined a grep. When we\n // define a grep — It can cause maximum callstack error if\n // the grep is doing a large recursive loop by neglecting\n // all tests. The run immediately function also comes with\n // a performance cost. So we don't want to run immediately\n // if we run the whole test suite, because running the whole\n // test suite don't do any immediate recursive loops. Thus,\n // allowing a JS runtime to breathe.\n if (self._grep !== self._defaultGrep) {\n Runner.immediately(next);\n } else {\n next();\n }\n return;\n }\n\n // static skip, no hooks are executed\n if (test.isPending()) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return next();\n }\n\n // execute test and hook(s)\n self.emit(constants.EVENT_TEST_BEGIN, (self.test = test));\n self.hookDown(HOOK_TYPE_BEFORE_EACH, function(err, errSuite) {\n // conditional skip within beforeEach\n if (test.isPending()) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n // skip inner afterEach hooks below errSuite level\n var origSuite = self.suite;\n self.suite = errSuite || self.suite;\n return self.hookUp(HOOK_TYPE_AFTER_EACH, function(e, eSuite) {\n self.suite = origSuite;\n next(e, eSuite);\n });\n }\n if (err) {\n return hookErr(err, errSuite, false);\n }\n self.currentRunnable = self.test;\n self.runTest(function(err) {\n test = self.test;\n // conditional skip within it\n if (test.pending) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n } else if (err) {\n var retry = test.currentRetry();\n if (retry < test.retries()) {\n var clonedTest = test.clone();\n clonedTest.currentRetry(retry + 1);\n tests.unshift(clonedTest);\n\n self.emit(constants.EVENT_TEST_RETRY, test, err);\n\n // Early return + hook trigger so that it doesn't\n // increment the count wrong\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n } else {\n self.fail(test, err);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n }\n\n test.state = STATE_PASSED;\n self.emit(constants.EVENT_TEST_PASS, test);\n self.emit(constants.EVENT_TEST_END, test);\n self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n });\n });\n }\n\n this.next = next;\n this.hookErr = hookErr;\n next();\n};\n\n/**\n * Run the given `suite` and invoke the callback `fn()` when complete.\n *\n * @private\n * @param {Suite} suite\n * @param {Function} fn\n */\nRunner.prototype.runSuite = function(suite, fn) {\n var i = 0;\n var self = this;\n var total = this.grepTotal(suite);\n\n debug('runSuite(): running %s', suite.fullTitle());\n\n if (!total || (self.failures && suite._bail)) {\n debug('runSuite(): bailing');\n return fn();\n }\n\n this.emit(constants.EVENT_SUITE_BEGIN, (this.suite = suite));\n\n function next(errSuite) {\n if (errSuite) {\n // current suite failed on a hook from errSuite\n if (errSuite === suite) {\n // if errSuite is current suite\n // continue to the next sibling suite\n return done();\n }\n // errSuite is among the parents of current suite\n // stop execution of errSuite and all sub-suites\n return done(errSuite);\n }\n\n if (self._abort) {\n return done();\n }\n\n var curr = suite.suites[i++];\n if (!curr) {\n return done();\n }\n\n // Avoid grep neglecting large number of tests causing a\n // huge recursive loop and thus a maximum call stack error.\n // See comment in `this.runTests()` for more information.\n if (self._grep !== self._defaultGrep) {\n Runner.immediately(function() {\n self.runSuite(curr, next);\n });\n } else {\n self.runSuite(curr, next);\n }\n }\n\n function done(errSuite) {\n self.suite = suite;\n self.nextSuite = next;\n\n // remove reference to test\n delete self.test;\n\n self.hook(HOOK_TYPE_AFTER_ALL, function() {\n self.emit(constants.EVENT_SUITE_END, suite);\n fn(errSuite);\n });\n }\n\n this.nextSuite = next;\n\n this.hook(HOOK_TYPE_BEFORE_ALL, function(err) {\n if (err) {\n return done();\n }\n self.runTests(suite, next);\n });\n};\n\n/**\n * Handle uncaught exceptions within runner.\n *\n * This function is bound to the instance as `Runner#uncaught` at instantiation\n * time. It's intended to be listening on the `Process.uncaughtException` event.\n * In order to not leak EE listeners, we need to ensure no more than a single\n * `uncaughtException` listener exists per `Runner`. The only way to do\n * this--because this function needs the context (and we don't have lambdas)--is\n * to use `Function.prototype.bind`. We need strict equality to unregister and\n * _only_ unregister the _one_ listener we set from the\n * `Process.uncaughtException` event; would be poor form to just remove\n * everything. See {@link Runner#run} for where the event listener is registered\n * and unregistered.\n * @param {Error} err - Some uncaught error\n * @private\n */\nRunner.prototype._uncaught = function(err) {\n // this is defensive to prevent future developers from mis-calling this function.\n // it's more likely that it'd be called with the incorrect context--say, the global\n // `process` object--than it would to be called with a context that is not a \"subclass\"\n // of `Runner`.\n if (!(this instanceof Runner)) {\n throw createFatalError(\n 'Runner#uncaught() called with invalid context',\n this\n );\n }\n if (err instanceof Pending) {\n debug('uncaught(): caught a Pending');\n return;\n }\n // browser does not exit script when throwing in global.onerror()\n if (this.allowUncaught && !utils.isBrowser()) {\n debug('uncaught(): bubbling exception due to --allow-uncaught');\n throw err;\n }\n\n if (this.state === constants.STATE_STOPPED) {\n debug('uncaught(): throwing after run has completed!');\n throw err;\n }\n\n if (err) {\n debug('uncaught(): got truthy exception %O', err);\n } else {\n debug('uncaught(): undefined/falsy exception');\n err = createInvalidExceptionError(\n 'Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger',\n err\n );\n }\n\n if (!isError(err)) {\n err = thrown2Error(err);\n debug('uncaught(): converted \"error\" %o to Error', err);\n }\n err.uncaught = true;\n\n var runnable = this.currentRunnable;\n\n if (!runnable) {\n runnable = new Runnable('Uncaught error outside test suite');\n debug('uncaught(): no current Runnable; created a phony one');\n runnable.parent = this.suite;\n\n if (this.state === constants.STATE_RUNNING) {\n debug('uncaught(): failing gracefully');\n this.fail(runnable, err);\n } else {\n // Can't recover from this failure\n debug('uncaught(): test run has not yet started; unrecoverable');\n this.emit(constants.EVENT_RUN_BEGIN);\n this.fail(runnable, err);\n this.emit(constants.EVENT_RUN_END);\n }\n\n return;\n }\n\n runnable.clearTimeout();\n\n if (runnable.isFailed()) {\n debug('uncaught(): Runnable has already failed');\n // Ignore error if already failed\n return;\n } else if (runnable.isPending()) {\n debug('uncaught(): pending Runnable wound up failing!');\n // report 'pending test' retrospectively as failed\n this.fail(runnable, err, true);\n return;\n }\n\n // we cannot recover gracefully if a Runnable has already passed\n // then fails asynchronously\n if (runnable.isPassed()) {\n debug('uncaught(): Runnable has already passed; bailing gracefully');\n this.fail(runnable, err);\n this.abort();\n } else {\n debug('uncaught(): forcing Runnable to complete with Error');\n return runnable.callback(err);\n }\n};\n\n/**\n * Run the root suite and invoke `fn(failures)`\n * on completion.\n *\n * @public\n * @memberof Runner\n * @param {Function} fn - Callback when finished\n * @param {{files: string[], options: Options}} [opts] - For subclasses\n * @returns {Runner} Runner instance.\n */\nRunner.prototype.run = function(fn, opts = {}) {\n var rootSuite = this.suite;\n var options = opts.options || {};\n\n debug('run(): got options: %O', options);\n fn = fn || function() {};\n\n const end = () => {\n debug('run(): root suite completed; emitting %s', constants.EVENT_RUN_END);\n this.emit(constants.EVENT_RUN_END);\n };\n\n const begin = () => {\n debug('run(): emitting %s', constants.EVENT_RUN_BEGIN);\n this.emit(constants.EVENT_RUN_BEGIN);\n debug('run(): emitted %s', constants.EVENT_RUN_BEGIN);\n\n this.runSuite(rootSuite, end);\n };\n\n const prepare = () => {\n debug('run(): starting');\n // If there is an `only` filter\n if (rootSuite.hasOnly()) {\n rootSuite.filterOnly();\n debug('run(): filtered exclusive Runnables');\n }\n this.state = constants.STATE_RUNNING;\n if (this._delay) {\n this.emit(constants.EVENT_DELAY_END);\n debug('run(): \"delay\" ended');\n }\n\n return begin();\n };\n\n // references cleanup to avoid memory leaks\n if (this._opts.cleanReferencesAfterRun) {\n this.on(constants.EVENT_SUITE_END, suite => {\n suite.cleanReferences();\n });\n }\n\n // callback\n this.on(constants.EVENT_RUN_END, function() {\n this.state = constants.STATE_STOPPED;\n debug('run(): emitted %s', constants.EVENT_RUN_END);\n fn(this.failures);\n });\n\n this._removeEventListener(process, 'uncaughtException', this.uncaught);\n this._removeEventListener(process, 'unhandledRejection', this.unhandled);\n this._addEventListener(process, 'uncaughtException', this.uncaught);\n this._addEventListener(process, 'unhandledRejection', this.unhandled);\n\n if (this._delay) {\n // for reporters, I guess.\n // might be nice to debounce some dots while we wait.\n this.emit(constants.EVENT_DELAY_BEGIN, rootSuite);\n rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare);\n debug('run(): waiting for green light due to --delay');\n } else {\n Runner.immediately(prepare);\n }\n\n return this;\n};\n\n/**\n * Toggle partial object linking behavior; used for building object references from\n * unique ID's. Does nothing in serial mode, because the object references already exist.\n * Subclasses can implement this (e.g., `ParallelBufferedRunner`)\n * @abstract\n * @param {boolean} [value] - If `true`, enable partial object linking, otherwise disable\n * @returns {Runner}\n * @chainable\n * @public\n * @example\n * // this reporter needs proper object references when run in parallel mode\n * class MyReporter() {\n * constructor(runner) {\n * this.runner.linkPartialObjects(true)\n * .on(EVENT_SUITE_BEGIN, suite => {\n // this Suite may be the same object...\n * })\n * .on(EVENT_TEST_BEGIN, test => {\n * // ...as the `test.parent` property\n * });\n * }\n * }\n */\nRunner.prototype.linkPartialObjects = function(value) {\n return this;\n};\n\n/*\n * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`.\n * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead.\n * @public\n * @memberof Runner\n * @param {Object} [opts] - Options for {@link Runner#run}\n * @returns {Promise} Failure count\n */\nRunner.prototype.runAsync = async function runAsync(opts = {}) {\n return new Promise(resolve => {\n this.run(resolve, opts);\n });\n};\n\n/**\n * Cleanly abort execution.\n *\n * @memberof Runner\n * @public\n * @return {Runner} Runner instance.\n */\nRunner.prototype.abort = function() {\n debug('abort(): aborting');\n this._abort = true;\n\n return this;\n};\n\n/**\n * Returns `true` if Mocha is running in parallel mode. For reporters.\n *\n * Subclasses should return an appropriate value.\n * @public\n * @returns {false}\n */\nRunner.prototype.isParallelMode = function isParallelMode() {\n return false;\n};\n\n/**\n * Configures an alternate reporter for worker processes to use. Subclasses\n * using worker processes should implement this.\n * @public\n * @param {string} path - Absolute path to alternate reporter for worker processes to use\n * @returns {Runner}\n * @throws When in serial mode\n * @chainable\n * @abstract\n */\nRunner.prototype.workerReporter = function() {\n throw createUnsupportedError('workerReporter() not supported in serial mode');\n};\n\n/**\n * Filter leaks with the given globals flagged as `ok`.\n *\n * @private\n * @param {Array} ok\n * @param {Array} globals\n * @return {Array}\n */\nfunction filterLeaks(ok, globals) {\n return globals.filter(function(key) {\n // Firefox and Chrome exposes iframes as index inside the window object\n if (/^\\d+/.test(key)) {\n return false;\n }\n\n // in firefox\n // if runner runs in an iframe, this iframe's window.getInterface method\n // not init at first it is assigned in some seconds\n if (global.navigator && /^getInterface/.test(key)) {\n return false;\n }\n\n // an iframe could be approached by window[iframeIndex]\n // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak\n if (global.navigator && /^\\d+/.test(key)) {\n return false;\n }\n\n // Opera and IE expose global variables for HTML element IDs (issue #243)\n if (/^mocha-/.test(key)) {\n return false;\n }\n\n var matched = ok.filter(function(ok) {\n if (~ok.indexOf('*')) {\n return key.indexOf(ok.split('*')[0]) === 0;\n }\n return key === ok;\n });\n return !matched.length && (!global.navigator || key !== 'onerror');\n });\n}\n\n/**\n * Check if argument is an instance of Error object or a duck-typed equivalent.\n *\n * @private\n * @param {Object} err - object to check\n * @param {string} err.message - error message\n * @returns {boolean}\n */\nfunction isError(err) {\n return err instanceof Error || (err && typeof err.message === 'string');\n}\n\n/**\n *\n * Converts thrown non-extensible type into proper Error.\n *\n * @private\n * @param {*} thrown - Non-extensible type thrown by code\n * @return {Error}\n */\nfunction thrown2Error(err) {\n return new Error(\n `the ${utils.canonicalType(err)} ${stringify(\n err\n )} was thrown, throw an Error :)`\n );\n}\n\nRunner.constants = constants;\n\n/**\n * Node.js' `EventEmitter`\n * @external EventEmitter\n * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter}\n */\n\nmodule.exports = Runner;\n","'use strict';\n/**\n * @module Base\n */\n/**\n * Module dependencies.\n */\n\nvar diff = require('diff');\nvar milliseconds = require('ms');\nvar utils = require('../utils');\nvar supportsColor = require('supports-color');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\n\nconst isBrowser = utils.isBrowser();\n\nfunction getBrowserWindowSize() {\n if ('innerHeight' in global) {\n return [global.innerHeight, global.innerWidth];\n }\n // In a Web Worker, the DOM Window is not available.\n return [640, 480];\n}\n\n/**\n * Expose `Base`.\n */\n\nexports = module.exports = Base;\n\n/**\n * Check if both stdio streams are associated with a tty.\n */\n\nvar isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY);\n\n/**\n * Save log references to avoid tests interfering (see GH-3604).\n */\nvar consoleLog = console.log;\n\n/**\n * Enable coloring by default, except in the browser interface.\n */\n\nexports.useColors =\n !isBrowser &&\n (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);\n\n/**\n * Inline diffs instead of +/-\n */\n\nexports.inlineDiffs = false;\n\n/**\n * Default color map.\n */\n\nexports.colors = {\n pass: 90,\n fail: 31,\n 'bright pass': 92,\n 'bright fail': 91,\n 'bright yellow': 93,\n pending: 36,\n suite: 0,\n 'error title': 0,\n 'error message': 31,\n 'error stack': 90,\n checkmark: 32,\n fast: 90,\n medium: 33,\n slow: 31,\n green: 32,\n light: 90,\n 'diff gutter': 90,\n 'diff added': 32,\n 'diff removed': 31,\n 'diff added inline': '30;42',\n 'diff removed inline': '30;41'\n};\n\n/**\n * Default symbol map.\n */\n\nexports.symbols = {\n ok: '✓',\n err: '✖',\n dot: '․',\n comma: ',',\n bang: '!'\n};\n\n// With node.js on Windows: use symbols available in terminal default fonts\nif (process.platform === 'win32') {\n exports.symbols.ok = '\\u221A';\n exports.symbols.err = '\\u00D7';\n exports.symbols.dot = '.';\n}\n\n/**\n * Color `str` with the given `type`,\n * allowing colors to be disabled,\n * as well as user-defined color\n * schemes.\n *\n * @private\n * @param {string} type\n * @param {string} str\n * @return {string}\n */\nvar color = (exports.color = function(type, str) {\n if (!exports.useColors) {\n return String(str);\n }\n return '\\u001b[' + exports.colors[type] + 'm' + str + '\\u001b[0m';\n});\n\n/**\n * Expose term window size, with some defaults for when stderr is not a tty.\n */\n\nexports.window = {\n width: 75\n};\n\nif (isatty) {\n if (isBrowser) {\n exports.window.width = getBrowserWindowSize()[1];\n } else {\n exports.window.width = process.stdout.getWindowSize(1)[0];\n }\n}\n\n/**\n * Expose some basic cursor interactions that are common among reporters.\n */\n\nexports.cursor = {\n hide: function() {\n isatty && process.stdout.write('\\u001b[?25l');\n },\n\n show: function() {\n isatty && process.stdout.write('\\u001b[?25h');\n },\n\n deleteLine: function() {\n isatty && process.stdout.write('\\u001b[2K');\n },\n\n beginningOfLine: function() {\n isatty && process.stdout.write('\\u001b[0G');\n },\n\n CR: function() {\n if (isatty) {\n exports.cursor.deleteLine();\n exports.cursor.beginningOfLine();\n } else {\n process.stdout.write('\\r');\n }\n }\n};\n\nvar showDiff = (exports.showDiff = function(err) {\n return (\n err &&\n err.showDiff !== false &&\n sameType(err.actual, err.expected) &&\n err.expected !== undefined\n );\n});\n\nfunction stringifyDiffObjs(err) {\n if (!utils.isString(err.actual) || !utils.isString(err.expected)) {\n err.actual = utils.stringify(err.actual);\n err.expected = utils.stringify(err.expected);\n }\n}\n\n/**\n * Returns a diff between 2 strings with coloured ANSI output.\n *\n * @description\n * The diff will be either inline or unified dependent on the value\n * of `Base.inlineDiff`.\n *\n * @param {string} actual\n * @param {string} expected\n * @return {string} Diff\n */\nvar generateDiff = (exports.generateDiff = function(actual, expected) {\n try {\n return exports.inlineDiffs\n ? inlineDiff(actual, expected)\n : unifiedDiff(actual, expected);\n } catch (err) {\n var msg =\n '\\n ' +\n color('diff added', '+ expected') +\n ' ' +\n color('diff removed', '- actual: failed to generate Mocha diff') +\n '\\n';\n return msg;\n }\n});\n\n/**\n * Outputs the given `failures` as a list.\n *\n * @public\n * @memberof Mocha.reporters.Base\n * @variation 1\n * @param {Object[]} failures - Each is Test instance with corresponding\n * Error property\n */\nexports.list = function(failures) {\n var multipleErr, multipleTest;\n Base.consoleLog();\n failures.forEach(function(test, i) {\n // format\n var fmt =\n color('error title', ' %s) %s:\\n') +\n color('error message', ' %s') +\n color('error stack', '\\n%s\\n');\n\n // msg\n var msg;\n var err;\n if (test.err && test.err.multiple) {\n if (multipleTest !== test) {\n multipleTest = test;\n multipleErr = [test.err].concat(test.err.multiple);\n }\n err = multipleErr.shift();\n } else {\n err = test.err;\n }\n var message;\n if (err.message && typeof err.message.toString === 'function') {\n message = err.message + '';\n } else if (typeof err.inspect === 'function') {\n message = err.inspect() + '';\n } else {\n message = '';\n }\n var stack = err.stack || message;\n var index = message ? stack.indexOf(message) : -1;\n\n if (index === -1) {\n msg = message;\n } else {\n index += message.length;\n msg = stack.slice(0, index);\n // remove msg from stack\n stack = stack.slice(index + 1);\n }\n\n // uncaught\n if (err.uncaught) {\n msg = 'Uncaught ' + msg;\n }\n // explicitly show diff\n if (!exports.hideDiff && showDiff(err)) {\n stringifyDiffObjs(err);\n fmt =\n color('error title', ' %s) %s:\\n%s') + color('error stack', '\\n%s\\n');\n var match = message.match(/^([^:]+): expected/);\n msg = '\\n ' + color('error message', match ? match[1] : msg);\n\n msg += generateDiff(err.actual, err.expected);\n }\n\n // indent stack trace\n stack = stack.replace(/^/gm, ' ');\n\n // indented test title\n var testTitle = '';\n test.titlePath().forEach(function(str, index) {\n if (index !== 0) {\n testTitle += '\\n ';\n }\n for (var i = 0; i < index; i++) {\n testTitle += ' ';\n }\n testTitle += str;\n });\n\n Base.consoleLog(fmt, i + 1, testTitle, msg, stack);\n });\n};\n\n/**\n * Constructs a new `Base` reporter instance.\n *\n * @description\n * All other reporters generally inherit from this reporter.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Base(runner, options) {\n var failures = (this.failures = []);\n\n if (!runner) {\n throw new TypeError('Missing runner argument');\n }\n this.options = options || {};\n this.runner = runner;\n this.stats = runner.stats; // assigned so Reporters keep a closer reference\n\n runner.on(EVENT_TEST_PASS, function(test) {\n if (test.duration > test.slow()) {\n test.speed = 'slow';\n } else if (test.duration > test.slow() / 2) {\n test.speed = 'medium';\n } else {\n test.speed = 'fast';\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function(test, err) {\n if (showDiff(err)) {\n stringifyDiffObjs(err);\n }\n // more than one error per test\n if (test.err && err instanceof Error) {\n test.err.multiple = (test.err.multiple || []).concat(err);\n } else {\n test.err = err;\n }\n failures.push(test);\n });\n}\n\n/**\n * Outputs common epilogue used by many of the bundled reporters.\n *\n * @public\n * @memberof Mocha.reporters\n */\nBase.prototype.epilogue = function() {\n var stats = this.stats;\n var fmt;\n\n Base.consoleLog();\n\n // passes\n fmt =\n color('bright pass', ' ') +\n color('green', ' %d passing') +\n color('light', ' (%s)');\n\n Base.consoleLog(fmt, stats.passes || 0, milliseconds(stats.duration));\n\n // pending\n if (stats.pending) {\n fmt = color('pending', ' ') + color('pending', ' %d pending');\n\n Base.consoleLog(fmt, stats.pending);\n }\n\n // failures\n if (stats.failures) {\n fmt = color('fail', ' %d failing');\n\n Base.consoleLog(fmt, stats.failures);\n\n Base.list(this.failures);\n Base.consoleLog();\n }\n\n Base.consoleLog();\n};\n\n/**\n * Pads the given `str` to `len`.\n *\n * @private\n * @param {string} str\n * @param {string} len\n * @return {string}\n */\nfunction pad(str, len) {\n str = String(str);\n return Array(len - str.length + 1).join(' ') + str;\n}\n\n/**\n * Returns inline diff between 2 strings with coloured ANSI output.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} Diff\n */\nfunction inlineDiff(actual, expected) {\n var msg = errorDiff(actual, expected);\n\n // linenos\n var lines = msg.split('\\n');\n if (lines.length > 4) {\n var width = String(lines.length).length;\n msg = lines\n .map(function(str, i) {\n return pad(++i, width) + ' |' + ' ' + str;\n })\n .join('\\n');\n }\n\n // legend\n msg =\n '\\n' +\n color('diff removed inline', 'actual') +\n ' ' +\n color('diff added inline', 'expected') +\n '\\n\\n' +\n msg +\n '\\n';\n\n // indent\n msg = msg.replace(/^/gm, ' ');\n return msg;\n}\n\n/**\n * Returns unified diff between two strings with coloured ANSI output.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} The diff.\n */\nfunction unifiedDiff(actual, expected) {\n var indent = ' ';\n function cleanUp(line) {\n if (line[0] === '+') {\n return indent + colorLines('diff added', line);\n }\n if (line[0] === '-') {\n return indent + colorLines('diff removed', line);\n }\n if (line.match(/@@/)) {\n return '--';\n }\n if (line.match(/\\\\ No newline/)) {\n return null;\n }\n return indent + line;\n }\n function notBlank(line) {\n return typeof line !== 'undefined' && line !== null;\n }\n var msg = diff.createPatch('string', actual, expected);\n var lines = msg.split('\\n').splice(5);\n return (\n '\\n ' +\n colorLines('diff added', '+ expected') +\n ' ' +\n colorLines('diff removed', '- actual') +\n '\\n\\n' +\n lines\n .map(cleanUp)\n .filter(notBlank)\n .join('\\n')\n );\n}\n\n/**\n * Returns character diff for `err`.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} the diff\n */\nfunction errorDiff(actual, expected) {\n return diff\n .diffWordsWithSpace(actual, expected)\n .map(function(str) {\n if (str.added) {\n return colorLines('diff added inline', str.value);\n }\n if (str.removed) {\n return colorLines('diff removed inline', str.value);\n }\n return str.value;\n })\n .join('');\n}\n\n/**\n * Colors lines for `str`, using the color `name`.\n *\n * @private\n * @param {string} name\n * @param {string} str\n * @return {string}\n */\nfunction colorLines(name, str) {\n return str\n .split('\\n')\n .map(function(str) {\n return color(name, str);\n })\n .join('\\n');\n}\n\n/**\n * Object#toString reference.\n */\nvar objToString = Object.prototype.toString;\n\n/**\n * Checks that a / b have the same type.\n *\n * @private\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nfunction sameType(a, b) {\n return objToString.call(a) === objToString.call(b);\n}\n\nBase.consoleLog = consoleLog;\n\nBase.abstract = true;\n","'use strict';\n/**\n * @module Dot\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\n\n/**\n * Expose `Dot`.\n */\n\nexports = module.exports = Dot;\n\n/**\n * Constructs a new `Dot` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Dot(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var n = -1;\n\n runner.on(EVENT_RUN_BEGIN, function() {\n process.stdout.write('\\n');\n });\n\n runner.on(EVENT_TEST_PENDING, function() {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n process.stdout.write(Base.color('pending', Base.symbols.comma));\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n if (test.speed === 'slow') {\n process.stdout.write(Base.color('bright yellow', Base.symbols.dot));\n } else {\n process.stdout.write(Base.color(test.speed, Base.symbols.dot));\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function() {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n process.stdout.write(Base.color('fail', Base.symbols.bang));\n });\n\n runner.once(EVENT_RUN_END, function() {\n process.stdout.write('\\n');\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Dot, Base);\n\nDot.description = 'dot matrix representation';\n","'use strict';\n/**\n * @module Doc\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\n\n/**\n * Expose `Doc`.\n */\n\nexports = module.exports = Doc;\n\n/**\n * Constructs a new `Doc` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Doc(runner, options) {\n Base.call(this, runner, options);\n\n var indents = 2;\n\n function indent() {\n return Array(indents).join(' ');\n }\n\n runner.on(EVENT_SUITE_BEGIN, function(suite) {\n if (suite.root) {\n return;\n }\n ++indents;\n Base.consoleLog('%s
        ', indent());\n ++indents;\n Base.consoleLog('%s

        %s

        ', indent(), utils.escape(suite.title));\n Base.consoleLog('%s
        ', indent());\n });\n\n runner.on(EVENT_SUITE_END, function(suite) {\n if (suite.root) {\n return;\n }\n Base.consoleLog('%s
        ', indent());\n --indents;\n Base.consoleLog('%s
        ', indent());\n --indents;\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n Base.consoleLog('%s
        %s
        ', indent(), utils.escape(test.title));\n Base.consoleLog('%s
        %s
        ', indent(), utils.escape(test.file));\n var code = utils.escape(utils.clean(test.body));\n Base.consoleLog('%s
        %s
        ', indent(), code);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test, err) {\n Base.consoleLog(\n '%s
        %s
        ',\n indent(),\n utils.escape(test.title)\n );\n Base.consoleLog(\n '%s
        %s
        ',\n indent(),\n utils.escape(test.file)\n );\n var code = utils.escape(utils.clean(test.body));\n Base.consoleLog(\n '%s
        %s
        ',\n indent(),\n code\n );\n Base.consoleLog(\n '%s
        %s
        ',\n indent(),\n utils.escape(err)\n );\n });\n}\n\nDoc.description = 'HTML documentation';\n","'use strict';\n/**\n * @module TAP\n */\n/**\n * Module dependencies.\n */\n\nvar util = require('util');\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar inherits = require('../utils').inherits;\nvar sprintf = util.format;\n\n/**\n * Expose `TAP`.\n */\n\nexports = module.exports = TAP;\n\n/**\n * Constructs a new `TAP` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction TAP(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var n = 1;\n\n var tapVersion = '12';\n if (options && options.reporterOptions) {\n if (options.reporterOptions.tapVersion) {\n tapVersion = options.reporterOptions.tapVersion.toString();\n }\n }\n\n this._producer = createProducer(tapVersion);\n\n runner.once(EVENT_RUN_BEGIN, function() {\n self._producer.writeVersion();\n });\n\n runner.on(EVENT_TEST_END, function() {\n ++n;\n });\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n self._producer.writePending(n, test);\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n self._producer.writePass(n, test);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test, err) {\n self._producer.writeFail(n, test, err);\n });\n\n runner.once(EVENT_RUN_END, function() {\n self._producer.writeEpilogue(runner.stats);\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(TAP, Base);\n\n/**\n * Returns a TAP-safe title of `test`.\n *\n * @private\n * @param {Test} test - Test instance.\n * @return {String} title with any hash character removed\n */\nfunction title(test) {\n return test.fullTitle().replace(/#/g, '');\n}\n\n/**\n * Writes newline-terminated formatted string to reporter output stream.\n *\n * @private\n * @param {string} format - `printf`-like format string\n * @param {...*} [varArgs] - Format string arguments\n */\nfunction println(format, varArgs) {\n var vargs = Array.from(arguments);\n vargs[0] += '\\n';\n process.stdout.write(sprintf.apply(null, vargs));\n}\n\n/**\n * Returns a `tapVersion`-appropriate TAP producer instance, if possible.\n *\n * @private\n * @param {string} tapVersion - Version of TAP specification to produce.\n * @returns {TAPProducer} specification-appropriate instance\n * @throws {Error} if specification version has no associated producer.\n */\nfunction createProducer(tapVersion) {\n var producers = {\n '12': new TAP12Producer(),\n '13': new TAP13Producer()\n };\n var producer = producers[tapVersion];\n\n if (!producer) {\n throw new Error(\n 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)\n );\n }\n\n return producer;\n}\n\n/**\n * @summary\n * Constructs a new TAPProducer.\n *\n * @description\n * Only to be used as an abstract base class.\n *\n * @private\n * @constructor\n */\nfunction TAPProducer() {}\n\n/**\n * Writes the TAP version to reporter output stream.\n *\n * @abstract\n */\nTAPProducer.prototype.writeVersion = function() {};\n\n/**\n * Writes the plan to reporter output stream.\n *\n * @abstract\n * @param {number} ntests - Number of tests that are planned to run.\n */\nTAPProducer.prototype.writePlan = function(ntests) {\n println('%d..%d', 1, ntests);\n};\n\n/**\n * Writes that test passed to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that passed.\n * @param {Test} test - Instance containing test information.\n */\nTAPProducer.prototype.writePass = function(n, test) {\n println('ok %d %s', n, title(test));\n};\n\n/**\n * Writes that test was skipped to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that was skipped.\n * @param {Test} test - Instance containing test information.\n */\nTAPProducer.prototype.writePending = function(n, test) {\n println('ok %d %s # SKIP -', n, title(test));\n};\n\n/**\n * Writes that test failed to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that failed.\n * @param {Test} test - Instance containing test information.\n * @param {Error} err - Reason the test failed.\n */\nTAPProducer.prototype.writeFail = function(n, test, err) {\n println('not ok %d %s', n, title(test));\n};\n\n/**\n * Writes the summary epilogue to reporter output stream.\n *\n * @abstract\n * @param {Object} stats - Object containing run statistics.\n */\nTAPProducer.prototype.writeEpilogue = function(stats) {\n // :TBD: Why is this not counting pending tests?\n println('# tests ' + (stats.passes + stats.failures));\n println('# pass ' + stats.passes);\n // :TBD: Why are we not showing pending results?\n println('# fail ' + stats.failures);\n this.writePlan(stats.passes + stats.failures + stats.pending);\n};\n\n/**\n * @summary\n * Constructs a new TAP12Producer.\n *\n * @description\n * Produces output conforming to the TAP12 specification.\n *\n * @private\n * @constructor\n * @extends TAPProducer\n * @see {@link https://testanything.org/tap-specification.html|Specification}\n */\nfunction TAP12Producer() {\n /**\n * Writes that test failed to reporter output stream, with error formatting.\n * @override\n */\n this.writeFail = function(n, test, err) {\n TAPProducer.prototype.writeFail.call(this, n, test, err);\n if (err.message) {\n println(err.message.replace(/^/gm, ' '));\n }\n if (err.stack) {\n println(err.stack.replace(/^/gm, ' '));\n }\n };\n}\n\n/**\n * Inherit from `TAPProducer.prototype`.\n */\ninherits(TAP12Producer, TAPProducer);\n\n/**\n * @summary\n * Constructs a new TAP13Producer.\n *\n * @description\n * Produces output conforming to the TAP13 specification.\n *\n * @private\n * @constructor\n * @extends TAPProducer\n * @see {@link https://testanything.org/tap-version-13-specification.html|Specification}\n */\nfunction TAP13Producer() {\n /**\n * Writes the TAP version to reporter output stream.\n * @override\n */\n this.writeVersion = function() {\n println('TAP version 13');\n };\n\n /**\n * Writes that test failed to reporter output stream, with error formatting.\n * @override\n */\n this.writeFail = function(n, test, err) {\n TAPProducer.prototype.writeFail.call(this, n, test, err);\n var emitYamlBlock = err.message != null || err.stack != null;\n if (emitYamlBlock) {\n println(indent(1) + '---');\n if (err.message) {\n println(indent(2) + 'message: |-');\n println(err.message.replace(/^/gm, indent(3)));\n }\n if (err.stack) {\n println(indent(2) + 'stack: |-');\n println(err.stack.replace(/^/gm, indent(3)));\n }\n println(indent(1) + '...');\n }\n };\n\n function indent(level) {\n return Array(level + 1).join(' ');\n }\n}\n\n/**\n * Inherit from `TAPProducer.prototype`.\n */\ninherits(TAP13Producer, TAPProducer);\n\nTAP.description = 'TAP-compatible output';\n","'use strict';\n/**\n * @module JSON\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\n\n/**\n * Expose `JSON`.\n */\n\nexports = module.exports = JSONReporter;\n\n/**\n * Constructs a new `JSON` reporter instance.\n *\n * @public\n * @class JSON\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction JSONReporter(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var tests = [];\n var pending = [];\n var failures = [];\n var passes = [];\n\n runner.on(EVENT_TEST_END, function(test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n passes.push(test);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test) {\n failures.push(test);\n });\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n pending.push(test);\n });\n\n runner.once(EVENT_RUN_END, function() {\n var obj = {\n stats: self.stats,\n tests: tests.map(clean),\n pending: pending.map(clean),\n failures: failures.map(clean),\n passes: passes.map(clean)\n };\n\n runner.testResults = obj;\n\n process.stdout.write(JSON.stringify(obj, null, 2));\n });\n}\n\n/**\n * Return a plain-object representation of `test`\n * free of cyclic properties etc.\n *\n * @private\n * @param {Object} test\n * @return {Object}\n */\nfunction clean(test) {\n var err = test.err || {};\n if (err instanceof Error) {\n err = errorJSON(err);\n }\n\n return {\n title: test.title,\n fullTitle: test.fullTitle(),\n file: test.file,\n duration: test.duration,\n currentRetry: test.currentRetry(),\n speed: test.speed,\n err: cleanCycles(err)\n };\n}\n\n/**\n * Replaces any circular references inside `obj` with '[object Object]'\n *\n * @private\n * @param {Object} obj\n * @return {Object}\n */\nfunction cleanCycles(obj) {\n var cache = [];\n return JSON.parse(\n JSON.stringify(obj, function(key, value) {\n if (typeof value === 'object' && value !== null) {\n if (cache.indexOf(value) !== -1) {\n // Instead of going in a circle, we'll print [object Object]\n return '' + value;\n }\n cache.push(value);\n }\n\n return value;\n })\n );\n}\n\n/**\n * Transform an Error object into a JSON object.\n *\n * @private\n * @param {Error} err\n * @return {Object}\n */\nfunction errorJSON(err) {\n var res = {};\n Object.getOwnPropertyNames(err).forEach(function(key) {\n res[key] = err[key];\n }, err);\n return res;\n}\n\nJSONReporter.description = 'single JSON object';\n","var classof = require('../internals/classof-raw');\n\n// `thisNumberValue` abstract operation\n// https://tc39.es/ecma262/#sec-thisnumbervalue\nmodule.exports = function (value) {\n if (typeof value != 'number' && classof(value) != 'Number') {\n throw TypeError('Incorrect invocation');\n }\n return +value;\n};\n","'use strict';\nvar toInteger = require('../internals/to-integer');\nvar requireObjectCoercible = require('../internals/require-object-coercible');\n\n// `String.prototype.repeat` method implementation\n// https://tc39.es/ecma262/#sec-string.prototype.repeat\nmodule.exports = ''.repeat || function repeat(count) {\n var str = String(requireObjectCoercible(this));\n var result = '';\n var n = toInteger(count);\n if (n < 0 || n == Infinity) throw RangeError('Wrong number of repetitions');\n for (;n > 0; (n >>>= 1) && (str += str)) if (n & 1) result += str;\n return result;\n};\n","'use strict';\nvar $ = require('../internals/export');\nvar toInteger = require('../internals/to-integer');\nvar thisNumberValue = require('../internals/this-number-value');\nvar repeat = require('../internals/string-repeat');\nvar fails = require('../internals/fails');\n\nvar nativeToFixed = 1.0.toFixed;\nvar floor = Math.floor;\n\nvar pow = function (x, n, acc) {\n return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);\n};\n\nvar log = function (x) {\n var n = 0;\n var x2 = x;\n while (x2 >= 4096) {\n n += 12;\n x2 /= 4096;\n }\n while (x2 >= 2) {\n n += 1;\n x2 /= 2;\n } return n;\n};\n\nvar FORCED = nativeToFixed && (\n 0.00008.toFixed(3) !== '0.000' ||\n 0.9.toFixed(0) !== '1' ||\n 1.255.toFixed(2) !== '1.25' ||\n 1000000000000000128.0.toFixed(0) !== '1000000000000000128'\n) || !fails(function () {\n // V8 ~ Android 4.3-\n nativeToFixed.call({});\n});\n\n// `Number.prototype.toFixed` method\n// https://tc39.es/ecma262/#sec-number.prototype.tofixed\n$({ target: 'Number', proto: true, forced: FORCED }, {\n // eslint-disable-next-line max-statements\n toFixed: function toFixed(fractionDigits) {\n var number = thisNumberValue(this);\n var fractDigits = toInteger(fractionDigits);\n var data = [0, 0, 0, 0, 0, 0];\n var sign = '';\n var result = '0';\n var e, z, j, k;\n\n var multiply = function (n, c) {\n var index = -1;\n var c2 = c;\n while (++index < 6) {\n c2 += n * data[index];\n data[index] = c2 % 1e7;\n c2 = floor(c2 / 1e7);\n }\n };\n\n var divide = function (n) {\n var index = 6;\n var c = 0;\n while (--index >= 0) {\n c += data[index];\n data[index] = floor(c / n);\n c = (c % n) * 1e7;\n }\n };\n\n var dataToString = function () {\n var index = 6;\n var s = '';\n while (--index >= 0) {\n if (s !== '' || index === 0 || data[index] !== 0) {\n var t = String(data[index]);\n s = s === '' ? t : s + repeat.call('0', 7 - t.length) + t;\n }\n } return s;\n };\n\n if (fractDigits < 0 || fractDigits > 20) throw RangeError('Incorrect fraction digits');\n // eslint-disable-next-line no-self-compare\n if (number != number) return 'NaN';\n if (number <= -1e21 || number >= 1e21) return String(number);\n if (number < 0) {\n sign = '-';\n number = -number;\n }\n if (number > 1e-21) {\n e = log(number * pow(2, 69, 1)) - 69;\n z = e < 0 ? number * pow(2, -e, 1) : number / pow(2, e, 1);\n z *= 0x10000000000000;\n e = 52 - e;\n if (e > 0) {\n multiply(0, z);\n j = fractDigits;\n while (j >= 7) {\n multiply(1e7, 0);\n j -= 7;\n }\n multiply(pow(10, j, 1), 0);\n j = e - 1;\n while (j >= 23) {\n divide(1 << 23);\n j -= 23;\n }\n divide(1 << j);\n multiply(1, 1);\n divide(2);\n result = dataToString();\n } else {\n multiply(0, z);\n multiply(1 << -e, 0);\n result = dataToString() + repeat.call('0', fractDigits);\n }\n }\n if (fractDigits > 0) {\n k = result.length;\n result = sign + (k <= fractDigits\n ? '0.' + repeat.call('0', fractDigits - k) + result\n : result.slice(0, k - fractDigits) + '.' + result.slice(k - fractDigits));\n } else {\n result = sign + result;\n } return result;\n }\n});\n","'use strict';\n\n/**\n @module browser/Progress\n*/\n\n/**\n * Expose `Progress`.\n */\n\nmodule.exports = Progress;\n\n/**\n * Initialize a new `Progress` indicator.\n */\nfunction Progress() {\n this.percent = 0;\n this.size(0);\n this.fontSize(11);\n this.font('helvetica, arial, sans-serif');\n}\n\n/**\n * Set progress size to `size`.\n *\n * @public\n * @param {number} size\n * @return {Progress} Progress instance.\n */\nProgress.prototype.size = function(size) {\n this._size = size;\n return this;\n};\n\n/**\n * Set text to `text`.\n *\n * @public\n * @param {string} text\n * @return {Progress} Progress instance.\n */\nProgress.prototype.text = function(text) {\n this._text = text;\n return this;\n};\n\n/**\n * Set font size to `size`.\n *\n * @public\n * @param {number} size\n * @return {Progress} Progress instance.\n */\nProgress.prototype.fontSize = function(size) {\n this._fontSize = size;\n return this;\n};\n\n/**\n * Set font to `family`.\n *\n * @param {string} family\n * @return {Progress} Progress instance.\n */\nProgress.prototype.font = function(family) {\n this._font = family;\n return this;\n};\n\n/**\n * Update percentage to `n`.\n *\n * @param {number} n\n * @return {Progress} Progress instance.\n */\nProgress.prototype.update = function(n) {\n this.percent = n;\n return this;\n};\n\n/**\n * Draw on `ctx`.\n *\n * @param {CanvasRenderingContext2d} ctx\n * @return {Progress} Progress instance.\n */\nProgress.prototype.draw = function(ctx) {\n try {\n var percent = Math.min(this.percent, 100);\n var size = this._size;\n var half = size / 2;\n var x = half;\n var y = half;\n var rad = half - 1;\n var fontSize = this._fontSize;\n\n ctx.font = fontSize + 'px ' + this._font;\n\n var angle = Math.PI * 2 * (percent / 100);\n ctx.clearRect(0, 0, size, size);\n\n // outer circle\n ctx.strokeStyle = '#9f9f9f';\n ctx.beginPath();\n ctx.arc(x, y, rad, 0, angle, false);\n ctx.stroke();\n\n // inner circle\n ctx.strokeStyle = '#eee';\n ctx.beginPath();\n ctx.arc(x, y, rad - 1, 0, angle, true);\n ctx.stroke();\n\n // text\n var text = this._text || (percent | 0) + '%';\n var w = ctx.measureText(text).width;\n\n ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);\n } catch (ignore) {\n // don't fail if we can't render progress\n }\n return this;\n};\n","'use strict';\n\n/* eslint-env browser */\n/**\n * @module HTML\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar Progress = require('../browser/progress');\nvar escapeRe = require('escape-string-regexp');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar escape = utils.escape;\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\n\nvar Date = global.Date;\n\n/**\n * Expose `HTML`.\n */\n\nexports = module.exports = HTML;\n\n/**\n * Stats template.\n */\n\nvar statsTemplate =\n '
        ';\n\nvar playIcon = '‣';\n\n/**\n * Constructs a new `HTML` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction HTML(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var stats = this.stats;\n var stat = fragment(statsTemplate);\n var items = stat.getElementsByTagName('li');\n var passes = items[1].getElementsByTagName('em')[0];\n var passesLink = items[1].getElementsByTagName('a')[0];\n var failures = items[2].getElementsByTagName('em')[0];\n var failuresLink = items[2].getElementsByTagName('a')[0];\n var duration = items[3].getElementsByTagName('em')[0];\n var canvas = stat.getElementsByTagName('canvas')[0];\n var report = fragment('
          ');\n var stack = [report];\n var progress;\n var ctx;\n var root = document.getElementById('mocha');\n\n if (canvas.getContext) {\n var ratio = window.devicePixelRatio || 1;\n canvas.style.width = canvas.width;\n canvas.style.height = canvas.height;\n canvas.width *= ratio;\n canvas.height *= ratio;\n ctx = canvas.getContext('2d');\n ctx.scale(ratio, ratio);\n progress = new Progress();\n }\n\n if (!root) {\n return error('#mocha div missing, add it to your document');\n }\n\n // pass toggle\n on(passesLink, 'click', function(evt) {\n evt.preventDefault();\n unhide();\n var name = /pass/.test(report.className) ? '' : ' pass';\n report.className = report.className.replace(/fail|pass/g, '') + name;\n if (report.className.trim()) {\n hideSuitesWithout('test pass');\n }\n });\n\n // failure toggle\n on(failuresLink, 'click', function(evt) {\n evt.preventDefault();\n unhide();\n var name = /fail/.test(report.className) ? '' : ' fail';\n report.className = report.className.replace(/fail|pass/g, '') + name;\n if (report.className.trim()) {\n hideSuitesWithout('test fail');\n }\n });\n\n root.appendChild(stat);\n root.appendChild(report);\n\n if (progress) {\n progress.size(40);\n }\n\n runner.on(EVENT_SUITE_BEGIN, function(suite) {\n if (suite.root) {\n return;\n }\n\n // suite\n var url = self.suiteURL(suite);\n var el = fragment(\n '
        • %s

        • ',\n url,\n escape(suite.title)\n );\n\n // container\n stack[0].appendChild(el);\n stack.unshift(document.createElement('ul'));\n el.appendChild(stack[0]);\n });\n\n runner.on(EVENT_SUITE_END, function(suite) {\n if (suite.root) {\n updateStats();\n return;\n }\n stack.shift();\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n var url = self.testURL(test);\n var markup =\n '
        • %e%ems ' +\n '' +\n playIcon +\n '

        • ';\n var el = fragment(markup, test.speed, test.title, test.duration, url);\n self.addCodeToggle(el, test.body);\n appendToStack(el);\n updateStats();\n });\n\n runner.on(EVENT_TEST_FAIL, function(test) {\n var el = fragment(\n '
        • %e ' +\n playIcon +\n '

        • ',\n test.title,\n self.testURL(test)\n );\n var stackString; // Note: Includes leading newline\n var message = test.err.toString();\n\n // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we\n // check for the result of the stringifying.\n if (message === '[object Error]') {\n message = test.err.message;\n }\n\n if (test.err.stack) {\n var indexOfMessage = test.err.stack.indexOf(test.err.message);\n if (indexOfMessage === -1) {\n stackString = test.err.stack;\n } else {\n stackString = test.err.stack.substr(\n test.err.message.length + indexOfMessage\n );\n }\n } else if (test.err.sourceURL && test.err.line !== undefined) {\n // Safari doesn't give you a stack. Let's at least provide a source line.\n stackString = '\\n(' + test.err.sourceURL + ':' + test.err.line + ')';\n }\n\n stackString = stackString || '';\n\n if (test.err.htmlMessage && stackString) {\n el.appendChild(\n fragment(\n '
          %s\\n
          %e
          ',\n test.err.htmlMessage,\n stackString\n )\n );\n } else if (test.err.htmlMessage) {\n el.appendChild(\n fragment('
          %s
          ', test.err.htmlMessage)\n );\n } else {\n el.appendChild(\n fragment('
          %e%e
          ', message, stackString)\n );\n }\n\n self.addCodeToggle(el, test.body);\n appendToStack(el);\n updateStats();\n });\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n var el = fragment(\n '
        • %e

        • ',\n test.title\n );\n appendToStack(el);\n updateStats();\n });\n\n function appendToStack(el) {\n // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.\n if (stack[0]) {\n stack[0].appendChild(el);\n }\n }\n\n function updateStats() {\n // TODO: add to stats\n var percent = ((stats.tests / runner.total) * 100) | 0;\n if (progress) {\n progress.update(percent).draw(ctx);\n }\n\n // update stats\n var ms = new Date() - stats.start;\n text(passes, stats.passes);\n text(failures, stats.failures);\n text(duration, (ms / 1000).toFixed(2));\n }\n}\n\n/**\n * Makes a URL, preserving querystring (\"search\") parameters.\n *\n * @param {string} s\n * @return {string} A new URL.\n */\nfunction makeUrl(s) {\n var search = window.location.search;\n\n // Remove previous grep query parameter if present\n if (search) {\n search = search.replace(/[?&]grep=[^&\\s]*/g, '').replace(/^&/, '?');\n }\n\n return (\n window.location.pathname +\n (search ? search + '&' : '?') +\n 'grep=' +\n encodeURIComponent(escapeRe(s))\n );\n}\n\n/**\n * Provide suite URL.\n *\n * @param {Object} [suite]\n */\nHTML.prototype.suiteURL = function(suite) {\n return makeUrl(suite.fullTitle());\n};\n\n/**\n * Provide test URL.\n *\n * @param {Object} [test]\n */\nHTML.prototype.testURL = function(test) {\n return makeUrl(test.fullTitle());\n};\n\n/**\n * Adds code toggle functionality for the provided test's list element.\n *\n * @param {HTMLLIElement} el\n * @param {string} contents\n */\nHTML.prototype.addCodeToggle = function(el, contents) {\n var h2 = el.getElementsByTagName('h2')[0];\n\n on(h2, 'click', function() {\n pre.style.display = pre.style.display === 'none' ? 'block' : 'none';\n });\n\n var pre = fragment('
          %e
          ', utils.clean(contents));\n el.appendChild(pre);\n pre.style.display = 'none';\n};\n\n/**\n * Display error `msg`.\n *\n * @param {string} msg\n */\nfunction error(msg) {\n document.body.appendChild(fragment('
          %s
          ', msg));\n}\n\n/**\n * Return a DOM fragment from `html`.\n *\n * @param {string} html\n */\nfunction fragment(html) {\n var args = arguments;\n var div = document.createElement('div');\n var i = 1;\n\n div.innerHTML = html.replace(/%([se])/g, function(_, type) {\n switch (type) {\n case 's':\n return String(args[i++]);\n case 'e':\n return escape(args[i++]);\n // no default\n }\n });\n\n return div.firstChild;\n}\n\n/**\n * Check for suites that do not have elements\n * with `classname`, and hide them.\n *\n * @param {text} classname\n */\nfunction hideSuitesWithout(classname) {\n var suites = document.getElementsByClassName('suite');\n for (var i = 0; i < suites.length; i++) {\n var els = suites[i].getElementsByClassName(classname);\n if (!els.length) {\n suites[i].className += ' hidden';\n }\n }\n}\n\n/**\n * Unhide .hidden suites.\n */\nfunction unhide() {\n var els = document.getElementsByClassName('suite hidden');\n while (els.length > 0) {\n els[0].className = els[0].className.replace('suite hidden', 'suite');\n }\n}\n\n/**\n * Set an element's text contents.\n *\n * @param {HTMLElement} el\n * @param {string} contents\n */\nfunction text(el, contents) {\n if (el.textContent) {\n el.textContent = contents;\n } else {\n el.innerText = contents;\n }\n}\n\n/**\n * Listen on `event` with callback `fn`.\n */\nfunction on(el, event, fn) {\n if (el.addEventListener) {\n el.addEventListener(event, fn, false);\n } else {\n el.attachEvent('on' + event, fn);\n }\n}\n\nHTML.browserOnly = true;\n","'use strict';\n/**\n * @module List\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar color = Base.color;\nvar cursor = Base.cursor;\n\n/**\n * Expose `List`.\n */\n\nexports = module.exports = List;\n\n/**\n * Constructs a new `List` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction List(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var n = 0;\n\n runner.on(EVENT_RUN_BEGIN, function() {\n Base.consoleLog();\n });\n\n runner.on(EVENT_TEST_BEGIN, function(test) {\n process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));\n });\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n var fmt = color('checkmark', ' -') + color('pending', ' %s');\n Base.consoleLog(fmt, test.fullTitle());\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n var fmt =\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s: ') +\n color(test.speed, '%dms');\n cursor.CR();\n Base.consoleLog(fmt, test.fullTitle(), test.duration);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test) {\n cursor.CR();\n Base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle());\n });\n\n runner.once(EVENT_RUN_END, self.epilogue.bind(self));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(List, Base);\n\nList.description = 'like \"spec\" reporter but flat';\n","'use strict';\n/**\n * @module Min\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\n\n/**\n * Expose `Min`.\n */\n\nexports = module.exports = Min;\n\n/**\n * Constructs a new `Min` reporter instance.\n *\n * @description\n * This minimal test reporter is best used with '--watch'.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Min(runner, options) {\n Base.call(this, runner, options);\n\n runner.on(EVENT_RUN_BEGIN, function() {\n // clear screen\n process.stdout.write('\\u001b[2J');\n // set cursor position\n process.stdout.write('\\u001b[1;3H');\n });\n\n runner.once(EVENT_RUN_END, this.epilogue.bind(this));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Min, Base);\n\nMin.description = 'essentially just a summary';\n","'use strict';\n/**\n * @module Spec\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar inherits = require('../utils').inherits;\nvar color = Base.color;\n\n/**\n * Expose `Spec`.\n */\n\nexports = module.exports = Spec;\n\n/**\n * Constructs a new `Spec` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Spec(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var indents = 0;\n var n = 0;\n\n function indent() {\n return Array(indents).join(' ');\n }\n\n runner.on(EVENT_RUN_BEGIN, function() {\n Base.consoleLog();\n });\n\n runner.on(EVENT_SUITE_BEGIN, function(suite) {\n ++indents;\n Base.consoleLog(color('suite', '%s%s'), indent(), suite.title);\n });\n\n runner.on(EVENT_SUITE_END, function() {\n --indents;\n if (indents === 1) {\n Base.consoleLog();\n }\n });\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n var fmt = indent() + color('pending', ' - %s');\n Base.consoleLog(fmt, test.title);\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n var fmt;\n if (test.speed === 'fast') {\n fmt =\n indent() +\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s');\n Base.consoleLog(fmt, test.title);\n } else {\n fmt =\n indent() +\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s') +\n color(test.speed, ' (%dms)');\n Base.consoleLog(fmt, test.title, test.duration);\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function(test) {\n Base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title);\n });\n\n runner.once(EVENT_RUN_END, self.epilogue.bind(self));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Spec, Base);\n\nSpec.description = 'hierarchical & verbose [default]';\n","'use strict';\n/**\n * @module Nyan\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar inherits = require('../utils').inherits;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\n\n/**\n * Expose `Dot`.\n */\n\nexports = module.exports = NyanCat;\n\n/**\n * Constructs a new `Nyan` reporter instance.\n *\n * @public\n * @class Nyan\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction NyanCat(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var nyanCatWidth = (this.nyanCatWidth = 11);\n\n this.colorIndex = 0;\n this.numberOfLines = 4;\n this.rainbowColors = self.generateColors();\n this.scoreboardWidth = 5;\n this.tick = 0;\n this.trajectories = [[], [], [], []];\n this.trajectoryWidthMax = width - nyanCatWidth;\n\n runner.on(EVENT_RUN_BEGIN, function() {\n Base.cursor.hide();\n self.draw();\n });\n\n runner.on(EVENT_TEST_PENDING, function() {\n self.draw();\n });\n\n runner.on(EVENT_TEST_PASS, function() {\n self.draw();\n });\n\n runner.on(EVENT_TEST_FAIL, function() {\n self.draw();\n });\n\n runner.once(EVENT_RUN_END, function() {\n Base.cursor.show();\n for (var i = 0; i < self.numberOfLines; i++) {\n write('\\n');\n }\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(NyanCat, Base);\n\n/**\n * Draw the nyan cat\n *\n * @private\n */\n\nNyanCat.prototype.draw = function() {\n this.appendRainbow();\n this.drawScoreboard();\n this.drawRainbow();\n this.drawNyanCat();\n this.tick = !this.tick;\n};\n\n/**\n * Draw the \"scoreboard\" showing the number\n * of passes, failures and pending tests.\n *\n * @private\n */\n\nNyanCat.prototype.drawScoreboard = function() {\n var stats = this.stats;\n\n function draw(type, n) {\n write(' ');\n write(Base.color(type, n));\n write('\\n');\n }\n\n draw('green', stats.passes);\n draw('fail', stats.failures);\n draw('pending', stats.pending);\n write('\\n');\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Append the rainbow.\n *\n * @private\n */\n\nNyanCat.prototype.appendRainbow = function() {\n var segment = this.tick ? '_' : '-';\n var rainbowified = this.rainbowify(segment);\n\n for (var index = 0; index < this.numberOfLines; index++) {\n var trajectory = this.trajectories[index];\n if (trajectory.length >= this.trajectoryWidthMax) {\n trajectory.shift();\n }\n trajectory.push(rainbowified);\n }\n};\n\n/**\n * Draw the rainbow.\n *\n * @private\n */\n\nNyanCat.prototype.drawRainbow = function() {\n var self = this;\n\n this.trajectories.forEach(function(line) {\n write('\\u001b[' + self.scoreboardWidth + 'C');\n write(line.join(''));\n write('\\n');\n });\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Draw the nyan cat\n *\n * @private\n */\nNyanCat.prototype.drawNyanCat = function() {\n var self = this;\n var startWidth = this.scoreboardWidth + this.trajectories[0].length;\n var dist = '\\u001b[' + startWidth + 'C';\n var padding = '';\n\n write(dist);\n write('_,------,');\n write('\\n');\n\n write(dist);\n padding = self.tick ? ' ' : ' ';\n write('_|' + padding + '/\\\\_/\\\\ ');\n write('\\n');\n\n write(dist);\n padding = self.tick ? '_' : '__';\n var tail = self.tick ? '~' : '^';\n write(tail + '|' + padding + this.face() + ' ');\n write('\\n');\n\n write(dist);\n padding = self.tick ? ' ' : ' ';\n write(padding + '\"\" \"\" ');\n write('\\n');\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Draw nyan cat face.\n *\n * @private\n * @return {string}\n */\n\nNyanCat.prototype.face = function() {\n var stats = this.stats;\n if (stats.failures) {\n return '( x .x)';\n } else if (stats.pending) {\n return '( o .o)';\n } else if (stats.passes) {\n return '( ^ .^)';\n }\n return '( - .-)';\n};\n\n/**\n * Move cursor up `n`.\n *\n * @private\n * @param {number} n\n */\n\nNyanCat.prototype.cursorUp = function(n) {\n write('\\u001b[' + n + 'A');\n};\n\n/**\n * Move cursor down `n`.\n *\n * @private\n * @param {number} n\n */\n\nNyanCat.prototype.cursorDown = function(n) {\n write('\\u001b[' + n + 'B');\n};\n\n/**\n * Generate rainbow colors.\n *\n * @private\n * @return {Array}\n */\nNyanCat.prototype.generateColors = function() {\n var colors = [];\n\n for (var i = 0; i < 6 * 7; i++) {\n var pi3 = Math.floor(Math.PI / 3);\n var n = i * (1.0 / 6);\n var r = Math.floor(3 * Math.sin(n) + 3);\n var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);\n var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);\n colors.push(36 * r + 6 * g + b + 16);\n }\n\n return colors;\n};\n\n/**\n * Apply rainbow to the given `str`.\n *\n * @private\n * @param {string} str\n * @return {string}\n */\nNyanCat.prototype.rainbowify = function(str) {\n if (!Base.useColors) {\n return str;\n }\n var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];\n this.colorIndex += 1;\n return '\\u001b[38;5;' + color + 'm' + str + '\\u001b[0m';\n};\n\n/**\n * Stdout helper.\n *\n * @param {string} string A message to write to stdout.\n */\nfunction write(string) {\n process.stdout.write(string);\n}\n\nNyanCat.description = '\"nyan cat\"';\n","export default {};\n","'use strict';\n/**\n * @module XUnit\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar fs = require('fs');\nvar path = require('path');\nvar errors = require('../errors');\nvar createUnsupportedError = errors.createUnsupportedError;\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar STATE_FAILED = require('../runnable').constants.STATE_FAILED;\nvar inherits = utils.inherits;\nvar escape = utils.escape;\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\nvar Date = global.Date;\n\n/**\n * Expose `XUnit`.\n */\n\nexports = module.exports = XUnit;\n\n/**\n * Constructs a new `XUnit` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction XUnit(runner, options) {\n Base.call(this, runner, options);\n\n var stats = this.stats;\n var tests = [];\n var self = this;\n\n // the name of the test suite, as it will appear in the resulting XML file\n var suiteName;\n\n // the default name of the test suite if none is provided\n var DEFAULT_SUITE_NAME = 'Mocha Tests';\n\n if (options && options.reporterOptions) {\n if (options.reporterOptions.output) {\n if (!fs.createWriteStream) {\n throw createUnsupportedError('file output not supported in browser');\n }\n\n fs.mkdirSync(path.dirname(options.reporterOptions.output), {\n recursive: true\n });\n self.fileStream = fs.createWriteStream(options.reporterOptions.output);\n }\n\n // get the suite name from the reporter options (if provided)\n suiteName = options.reporterOptions.suiteName;\n }\n\n // fall back to the default suite name\n suiteName = suiteName || DEFAULT_SUITE_NAME;\n\n runner.on(EVENT_TEST_PENDING, function(test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test) {\n tests.push(test);\n });\n\n runner.once(EVENT_RUN_END, function() {\n self.write(\n tag(\n 'testsuite',\n {\n name: suiteName,\n tests: stats.tests,\n failures: 0,\n errors: stats.failures,\n skipped: stats.tests - stats.failures - stats.passes,\n timestamp: new Date().toUTCString(),\n time: stats.duration / 1000 || 0\n },\n false\n )\n );\n\n tests.forEach(function(t) {\n self.test(t);\n });\n\n self.write('');\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(XUnit, Base);\n\n/**\n * Override done to close the stream (if it's a file).\n *\n * @param failures\n * @param {Function} fn\n */\nXUnit.prototype.done = function(failures, fn) {\n if (this.fileStream) {\n this.fileStream.end(function() {\n fn(failures);\n });\n } else {\n fn(failures);\n }\n};\n\n/**\n * Write out the given line.\n *\n * @param {string} line\n */\nXUnit.prototype.write = function(line) {\n if (this.fileStream) {\n this.fileStream.write(line + '\\n');\n } else if (typeof process === 'object' && process.stdout) {\n process.stdout.write(line + '\\n');\n } else {\n Base.consoleLog(line);\n }\n};\n\n/**\n * Output tag for the given `test.`\n *\n * @param {Test} test\n */\nXUnit.prototype.test = function(test) {\n Base.useColors = false;\n\n var attrs = {\n classname: test.parent.fullTitle(),\n name: test.title,\n time: test.duration / 1000 || 0\n };\n\n if (test.state === STATE_FAILED) {\n var err = test.err;\n var diff =\n !Base.hideDiff && Base.showDiff(err)\n ? '\\n' + Base.generateDiff(err.actual, err.expected)\n : '';\n this.write(\n tag(\n 'testcase',\n attrs,\n false,\n tag(\n 'failure',\n {},\n false,\n escape(err.message) + escape(diff) + '\\n' + escape(err.stack)\n )\n )\n );\n } else if (test.isPending()) {\n this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));\n } else {\n this.write(tag('testcase', attrs, true));\n }\n};\n\n/**\n * HTML tag helper.\n *\n * @param name\n * @param attrs\n * @param close\n * @param content\n * @return {string}\n */\nfunction tag(name, attrs, close, content) {\n var end = close ? '/>' : '>';\n var pairs = [];\n var tag;\n\n for (var key in attrs) {\n if (Object.prototype.hasOwnProperty.call(attrs, key)) {\n pairs.push(key + '=\"' + escape(attrs[key]) + '\"');\n }\n }\n\n tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;\n if (content) {\n tag += content + '' + '\\n';\n buf += title(suite.title) + '\\n';\n });\n\n runner.on(EVENT_SUITE_END, function() {\n --level;\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n var code = utils.clean(test.body);\n buf += test.title + '.\\n';\n buf += '\\n```js\\n';\n buf += code + '\\n';\n buf += '```\\n\\n';\n });\n\n runner.once(EVENT_RUN_END, function() {\n process.stdout.write('# TOC\\n');\n process.stdout.write(generateTOC(runner.suite));\n process.stdout.write(buf);\n });\n}\n\nMarkdown.description = 'GitHub Flavored Markdown';\n","'use strict';\n/**\n * @module Progress\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar inherits = require('../utils').inherits;\nvar color = Base.color;\nvar cursor = Base.cursor;\n\n/**\n * Expose `Progress`.\n */\n\nexports = module.exports = Progress;\n\n/**\n * General progress bar color.\n */\n\nBase.colors.progress = 90;\n\n/**\n * Constructs a new `Progress` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Progress(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.5) | 0;\n var total = runner.total;\n var complete = 0;\n var lastN = -1;\n\n // default chars\n options = options || {};\n var reporterOptions = options.reporterOptions || {};\n\n options.open = reporterOptions.open || '[';\n options.complete = reporterOptions.complete || '▬';\n options.incomplete = reporterOptions.incomplete || Base.symbols.dot;\n options.close = reporterOptions.close || ']';\n options.verbose = reporterOptions.verbose || false;\n\n // tests started\n runner.on(EVENT_RUN_BEGIN, function() {\n process.stdout.write('\\n');\n cursor.hide();\n });\n\n // tests complete\n runner.on(EVENT_TEST_END, function() {\n complete++;\n\n var percent = complete / total;\n var n = (width * percent) | 0;\n var i = width - n;\n\n if (n === lastN && !options.verbose) {\n // Don't re-render the line if it hasn't changed\n return;\n }\n lastN = n;\n\n cursor.CR();\n process.stdout.write('\\u001b[J');\n process.stdout.write(color('progress', ' ' + options.open));\n process.stdout.write(Array(n).join(options.complete));\n process.stdout.write(Array(i).join(options.incomplete));\n process.stdout.write(color('progress', options.close));\n if (options.verbose) {\n process.stdout.write(color('progress', ' ' + complete + ' of ' + total));\n }\n });\n\n // tests are complete, output some stats\n // and the failures if any\n runner.once(EVENT_RUN_END, function() {\n cursor.show();\n process.stdout.write('\\n');\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Progress, Base);\n\nProgress.description = 'a progress bar';\n","'use strict';\n/**\n * @module Landing\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar STATE_FAILED = require('../runnable').constants.STATE_FAILED;\n\nvar cursor = Base.cursor;\nvar color = Base.color;\n\n/**\n * Expose `Landing`.\n */\n\nexports = module.exports = Landing;\n\n/**\n * Airplane color.\n */\n\nBase.colors.plane = 0;\n\n/**\n * Airplane crash color.\n */\n\nBase.colors['plane crash'] = 31;\n\n/**\n * Runway color.\n */\n\nBase.colors.runway = 90;\n\n/**\n * Constructs a new `Landing` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Landing(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var stream = process.stdout;\n\n var plane = color('plane', '✈');\n var crashed = -1;\n var n = 0;\n var total = 0;\n\n function runway() {\n var buf = Array(width).join('-');\n return ' ' + color('runway', buf);\n }\n\n runner.on(EVENT_RUN_BEGIN, function() {\n stream.write('\\n\\n\\n ');\n cursor.hide();\n });\n\n runner.on(EVENT_TEST_END, function(test) {\n // check if the plane crashed\n var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed;\n // show the crash\n if (test.state === STATE_FAILED) {\n plane = color('plane crash', '✈');\n crashed = col;\n }\n\n // render landing strip\n stream.write('\\u001b[' + (width + 1) + 'D\\u001b[2A');\n stream.write(runway());\n stream.write('\\n ');\n stream.write(color('runway', Array(col).join('⋅')));\n stream.write(plane);\n stream.write(color('runway', Array(width - col).join('⋅') + '\\n'));\n stream.write(runway());\n stream.write('\\u001b[0m');\n });\n\n runner.once(EVENT_RUN_END, function() {\n cursor.show();\n process.stdout.write('\\n');\n self.epilogue();\n });\n\n // if cursor is hidden when we ctrl-C, then it will remain hidden unless...\n process.once('SIGINT', function() {\n cursor.show();\n process.nextTick(function() {\n process.kill(process.pid, 'SIGINT');\n });\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Landing, Base);\n\nLanding.description = 'Unicode landing strip';\n","'use strict';\n/**\n * @module JSONStream\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\n\n/**\n * Expose `JSONStream`.\n */\n\nexports = module.exports = JSONStream;\n\n/**\n * Constructs a new `JSONStream` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction JSONStream(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var total = runner.total;\n\n runner.once(EVENT_RUN_BEGIN, function() {\n writeEvent(['start', {total: total}]);\n });\n\n runner.on(EVENT_TEST_PASS, function(test) {\n writeEvent(['pass', clean(test)]);\n });\n\n runner.on(EVENT_TEST_FAIL, function(test, err) {\n test = clean(test);\n test.err = err.message;\n test.stack = err.stack || null;\n writeEvent(['fail', test]);\n });\n\n runner.once(EVENT_RUN_END, function() {\n writeEvent(['end', self.stats]);\n });\n}\n\n/**\n * Mocha event to be written to the output stream.\n * @typedef {Array} JSONStream~MochaEvent\n */\n\n/**\n * Writes Mocha event to reporter output stream.\n *\n * @private\n * @param {JSONStream~MochaEvent} event - Mocha event to be output.\n */\nfunction writeEvent(event) {\n process.stdout.write(JSON.stringify(event) + '\\n');\n}\n\n/**\n * Returns an object literal representation of `test`\n * free of cyclic properties, etc.\n *\n * @private\n * @param {Test} test - Instance used as data source.\n * @return {Object} object containing pared-down test instance data\n */\nfunction clean(test) {\n return {\n title: test.title,\n fullTitle: test.fullTitle(),\n file: test.file,\n duration: test.duration,\n currentRetry: test.currentRetry(),\n speed: test.speed\n };\n}\n\nJSONStream.description = 'newline delimited JSON events';\n","'use strict';\n\n// Alias exports to a their normalized format Mocha#reporter to prevent a need\n// for dynamic (try/catch) requires, which Browserify doesn't handle.\nexports.Base = exports.base = require('./base');\nexports.Dot = exports.dot = require('./dot');\nexports.Doc = exports.doc = require('./doc');\nexports.TAP = exports.tap = require('./tap');\nexports.JSON = exports.json = require('./json');\nexports.HTML = exports.html = require('./html');\nexports.List = exports.list = require('./list');\nexports.Min = exports.min = require('./min');\nexports.Spec = exports.spec = require('./spec');\nexports.Nyan = exports.nyan = require('./nyan');\nexports.XUnit = exports.xunit = require('./xunit');\nexports.Markdown = exports.markdown = require('./markdown');\nexports.Progress = exports.progress = require('./progress');\nexports.Landing = exports.landing = require('./landing');\nexports.JSONStream = exports['json-stream'] = require('./json-stream');\n","'use strict';\n\n/**\n * Web Notifications module.\n * @module Growl\n */\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\nvar Date = global.Date;\nvar setTimeout = global.setTimeout;\nvar EVENT_RUN_END = require('../runner').constants.EVENT_RUN_END;\nvar isBrowser = require('../utils').isBrowser;\n\n/**\n * Checks if browser notification support exists.\n *\n * @public\n * @see {@link https://caniuse.com/#feat=notifications|Browser support (notifications)}\n * @see {@link https://caniuse.com/#feat=promises|Browser support (promises)}\n * @see {@link Mocha#growl}\n * @see {@link Mocha#isGrowlCapable}\n * @return {boolean} whether browser notification support exists\n */\nexports.isCapable = function() {\n var hasNotificationSupport = 'Notification' in window;\n var hasPromiseSupport = typeof Promise === 'function';\n return isBrowser() && hasNotificationSupport && hasPromiseSupport;\n};\n\n/**\n * Implements browser notifications as a pseudo-reporter.\n *\n * @public\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/notification|Notification API}\n * @see {@link https://developers.google.com/web/fundamentals/push-notifications/display-a-notification|Displaying a Notification}\n * @see {@link Growl#isPermitted}\n * @see {@link Mocha#_growl}\n * @param {Runner} runner - Runner instance.\n */\nexports.notify = function(runner) {\n var promise = isPermitted();\n\n /**\n * Attempt notification.\n */\n var sendNotification = function() {\n // If user hasn't responded yet... \"No notification for you!\" (Seinfeld)\n Promise.race([promise, Promise.resolve(undefined)])\n .then(canNotify)\n .then(function() {\n display(runner);\n })\n .catch(notPermitted);\n };\n\n runner.once(EVENT_RUN_END, sendNotification);\n};\n\n/**\n * Checks if browser notification is permitted by user.\n *\n * @private\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Notification/permission|Notification.permission}\n * @see {@link Mocha#growl}\n * @see {@link Mocha#isGrowlPermitted}\n * @returns {Promise} promise determining if browser notification\n * permissible when fulfilled.\n */\nfunction isPermitted() {\n var permitted = {\n granted: function allow() {\n return Promise.resolve(true);\n },\n denied: function deny() {\n return Promise.resolve(false);\n },\n default: function ask() {\n return Notification.requestPermission().then(function(permission) {\n return permission === 'granted';\n });\n }\n };\n\n return permitted[Notification.permission]();\n}\n\n/**\n * @summary\n * Determines if notification should proceed.\n *\n * @description\n * Notification shall not proceed unless `value` is true.\n *\n * `value` will equal one of:\n *
            \n *
          • true (from `isPermitted`)
          • \n *
          • false (from `isPermitted`)
          • \n *
          • undefined (from `Promise.race`)
          • \n *
          \n *\n * @private\n * @param {boolean|undefined} value - Determines if notification permissible.\n * @returns {Promise} Notification can proceed\n */\nfunction canNotify(value) {\n if (!value) {\n var why = value === false ? 'blocked' : 'unacknowledged';\n var reason = 'not permitted by user (' + why + ')';\n return Promise.reject(new Error(reason));\n }\n return Promise.resolve();\n}\n\n/**\n * Displays the notification.\n *\n * @private\n * @param {Runner} runner - Runner instance.\n */\nfunction display(runner) {\n var stats = runner.stats;\n var symbol = {\n cross: '\\u274C',\n tick: '\\u2705'\n };\n var logo = require('../../package.json').notifyLogo;\n var _message;\n var message;\n var title;\n\n if (stats.failures) {\n _message = stats.failures + ' of ' + stats.tests + ' tests failed';\n message = symbol.cross + ' ' + _message;\n title = 'Failed';\n } else {\n _message = stats.passes + ' tests passed in ' + stats.duration + 'ms';\n message = symbol.tick + ' ' + _message;\n title = 'Passed';\n }\n\n // Send notification\n var options = {\n badge: logo,\n body: message,\n dir: 'ltr',\n icon: logo,\n lang: 'en-US',\n name: 'mocha',\n requireInteraction: false,\n timestamp: Date.now()\n };\n var notification = new Notification(title, options);\n\n // Autoclose after brief delay (makes various browsers act same)\n var FORCE_DURATION = 4000;\n setTimeout(notification.close.bind(notification), FORCE_DURATION);\n}\n\n/**\n * As notifications are tangential to our purpose, just log the error.\n *\n * @private\n * @param {Error} err - Why notification didn't happen.\n */\nfunction notPermitted(err) {\n console.error('notification error:', err.message);\n}\n","'use strict';\n\n/**\n * Provides a factory function for a {@link StatsCollector} object.\n * @module\n */\n\nvar constants = require('./runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\n\n/**\n * Test statistics collector.\n *\n * @public\n * @typedef {Object} StatsCollector\n * @property {number} suites - integer count of suites run.\n * @property {number} tests - integer count of tests run.\n * @property {number} passes - integer count of passing tests.\n * @property {number} pending - integer count of pending tests.\n * @property {number} failures - integer count of failed tests.\n * @property {Date} start - time when testing began.\n * @property {Date} end - time when testing concluded.\n * @property {number} duration - number of msecs that testing took.\n */\n\nvar Date = global.Date;\n\n/**\n * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`.\n *\n * @private\n * @param {Runner} runner - Runner instance\n * @throws {TypeError} If falsy `runner`\n */\nfunction createStatsCollector(runner) {\n /**\n * @type StatsCollector\n */\n var stats = {\n suites: 0,\n tests: 0,\n passes: 0,\n pending: 0,\n failures: 0\n };\n\n if (!runner) {\n throw new TypeError('Missing runner argument');\n }\n\n runner.stats = stats;\n\n runner.once(EVENT_RUN_BEGIN, function() {\n stats.start = new Date();\n });\n runner.on(EVENT_SUITE_BEGIN, function(suite) {\n suite.root || stats.suites++;\n });\n runner.on(EVENT_TEST_PASS, function() {\n stats.passes++;\n });\n runner.on(EVENT_TEST_FAIL, function() {\n stats.failures++;\n });\n runner.on(EVENT_TEST_PENDING, function() {\n stats.pending++;\n });\n runner.on(EVENT_TEST_END, function() {\n stats.tests++;\n });\n runner.once(EVENT_RUN_END, function() {\n stats.end = new Date();\n stats.duration = stats.end - stats.start;\n });\n}\n\nmodule.exports = createStatsCollector;\n","'use strict';\nvar Runnable = require('./runnable');\nvar utils = require('./utils');\nvar errors = require('./errors');\nvar createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;\nvar isString = utils.isString;\n\nconst {MOCHA_ID_PROP_NAME} = utils.constants;\n\nmodule.exports = Test;\n\n/**\n * Initialize a new `Test` with the given `title` and callback `fn`.\n *\n * @public\n * @class\n * @extends Runnable\n * @param {String} title - Test title (required)\n * @param {Function} [fn] - Test callback. If omitted, the Test is considered \"pending\"\n */\nfunction Test(title, fn) {\n if (!isString(title)) {\n throw createInvalidArgumentTypeError(\n 'Test argument \"title\" should be a string. Received type \"' +\n typeof title +\n '\"',\n 'title',\n 'string'\n );\n }\n this.type = 'test';\n Runnable.call(this, title, fn);\n this.reset();\n}\n\n/**\n * Inherit from `Runnable.prototype`.\n */\nutils.inherits(Test, Runnable);\n\n/**\n * Resets the state initially or for a next run.\n */\nTest.prototype.reset = function() {\n Runnable.prototype.reset.call(this);\n this.pending = !this.fn;\n delete this.state;\n};\n\n/**\n * Set or get retried test\n *\n * @private\n */\nTest.prototype.retriedTest = function(n) {\n if (!arguments.length) {\n return this._retriedTest;\n }\n this._retriedTest = n;\n};\n\n/**\n * Add test to the list of tests marked `only`.\n *\n * @private\n */\nTest.prototype.markOnly = function() {\n this.parent.appendOnlyTest(this);\n};\n\nTest.prototype.clone = function() {\n var test = new Test(this.title, this.fn);\n test.timeout(this.timeout());\n test.slow(this.slow());\n test.retries(this.retries());\n test.currentRetry(this.currentRetry());\n test.retriedTest(this.retriedTest() || this);\n test.globals(this.globals());\n test.parent = this.parent;\n test.file = this.file;\n test.ctx = this.ctx;\n return test;\n};\n\n/**\n * Returns an minimal object suitable for transmission over IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nTest.prototype.serialize = function serialize() {\n return {\n $$currentRetry: this._currentRetry,\n $$fullTitle: this.fullTitle(),\n $$isPending: this.pending,\n $$retriedTest: this._retriedTest || null,\n $$slow: this._slow,\n $$titlePath: this.titlePath(),\n body: this.body,\n duration: this.duration,\n err: this.err,\n parent: {\n $$fullTitle: this.parent.fullTitle(),\n [MOCHA_ID_PROP_NAME]: this.parent.id\n },\n speed: this.speed,\n state: this.state,\n title: this.title,\n type: this.type,\n file: this.file,\n [MOCHA_ID_PROP_NAME]: this.id\n };\n};\n","'use strict';\n\n/**\n @module interfaces/common\n*/\n\nvar Suite = require('../suite');\nvar errors = require('../errors');\nvar createMissingArgumentError = errors.createMissingArgumentError;\nvar createUnsupportedError = errors.createUnsupportedError;\nvar createForbiddenExclusivityError = errors.createForbiddenExclusivityError;\n\n/**\n * Functions common to more than one interface.\n *\n * @private\n * @param {Suite[]} suites\n * @param {Context} context\n * @param {Mocha} mocha\n * @return {Object} An object containing common functions.\n */\nmodule.exports = function(suites, context, mocha) {\n /**\n * Check if the suite should be tested.\n *\n * @private\n * @param {Suite} suite - suite to check\n * @returns {boolean}\n */\n function shouldBeTested(suite) {\n return (\n !mocha.options.grep ||\n (mocha.options.grep &&\n mocha.options.grep.test(suite.fullTitle()) &&\n !mocha.options.invert)\n );\n }\n\n return {\n /**\n * This is only present if flag --delay is passed into Mocha. It triggers\n * root suite execution.\n *\n * @param {Suite} suite The root suite.\n * @return {Function} A function which runs the root suite\n */\n runWithSuite: function runWithSuite(suite) {\n return function run() {\n suite.run();\n };\n },\n\n /**\n * Execute before running tests.\n *\n * @param {string} name\n * @param {Function} fn\n */\n before: function(name, fn) {\n suites[0].beforeAll(name, fn);\n },\n\n /**\n * Execute after running tests.\n *\n * @param {string} name\n * @param {Function} fn\n */\n after: function(name, fn) {\n suites[0].afterAll(name, fn);\n },\n\n /**\n * Execute before each test case.\n *\n * @param {string} name\n * @param {Function} fn\n */\n beforeEach: function(name, fn) {\n suites[0].beforeEach(name, fn);\n },\n\n /**\n * Execute after each test case.\n *\n * @param {string} name\n * @param {Function} fn\n */\n afterEach: function(name, fn) {\n suites[0].afterEach(name, fn);\n },\n\n suite: {\n /**\n * Create an exclusive Suite; convenience function\n * See docstring for create() below.\n *\n * @param {Object} opts\n * @returns {Suite}\n */\n only: function only(opts) {\n if (mocha.options.forbidOnly) {\n throw createForbiddenExclusivityError(mocha);\n }\n opts.isOnly = true;\n return this.create(opts);\n },\n\n /**\n * Create a Suite, but skip it; convenience function\n * See docstring for create() below.\n *\n * @param {Object} opts\n * @returns {Suite}\n */\n skip: function skip(opts) {\n opts.pending = true;\n return this.create(opts);\n },\n\n /**\n * Creates a suite.\n *\n * @param {Object} opts Options\n * @param {string} opts.title Title of Suite\n * @param {Function} [opts.fn] Suite Function (not always applicable)\n * @param {boolean} [opts.pending] Is Suite pending?\n * @param {string} [opts.file] Filepath where this Suite resides\n * @param {boolean} [opts.isOnly] Is Suite exclusive?\n * @returns {Suite}\n */\n create: function create(opts) {\n var suite = Suite.create(suites[0], opts.title);\n suite.pending = Boolean(opts.pending);\n suite.file = opts.file;\n suites.unshift(suite);\n if (opts.isOnly) {\n suite.markOnly();\n }\n if (\n suite.pending &&\n mocha.options.forbidPending &&\n shouldBeTested(suite)\n ) {\n throw createUnsupportedError('Pending test forbidden');\n }\n if (typeof opts.fn === 'function') {\n opts.fn.call(suite);\n suites.shift();\n } else if (typeof opts.fn === 'undefined' && !suite.pending) {\n throw createMissingArgumentError(\n 'Suite \"' +\n suite.fullTitle() +\n '\" was defined but no callback was supplied. ' +\n 'Supply a callback or explicitly skip the suite.',\n 'callback',\n 'function'\n );\n } else if (!opts.fn && suite.pending) {\n suites.shift();\n }\n\n return suite;\n }\n },\n\n test: {\n /**\n * Exclusive test-case.\n *\n * @param {Object} mocha\n * @param {Function} test\n * @returns {*}\n */\n only: function(mocha, test) {\n if (mocha.options.forbidOnly) {\n throw createForbiddenExclusivityError(mocha);\n }\n test.markOnly();\n return test;\n },\n\n /**\n * Pending test case.\n *\n * @param {string} title\n */\n skip: function(title) {\n context.test(title);\n }\n }\n };\n};\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE = require('../suite').constants\n .EVENT_FILE_PRE_REQUIRE;\n\n/**\n * BDD-style interface:\n *\n * describe('Array', function() {\n * describe('#indexOf()', function() {\n * it('should return -1 when not present', function() {\n * // ...\n * });\n *\n * it('should return the index when present', function() {\n * // ...\n * });\n * });\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function bddInterface(suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.before = common.before;\n context.after = common.after;\n context.beforeEach = common.beforeEach;\n context.afterEach = common.afterEach;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n /**\n * Describe a \"suite\" with the given `title`\n * and callback `fn` containing nested suites\n * and/or tests.\n */\n\n context.describe = context.context = function(title, fn) {\n return common.suite.create({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Pending describe.\n */\n\n context.xdescribe = context.xcontext = context.describe.skip = function(\n title,\n fn\n ) {\n return common.suite.skip({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Exclusive suite.\n */\n\n context.describe.only = function(title, fn) {\n return common.suite.only({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Describe a specification or test-case\n * with the given `title` and callback `fn`\n * acting as a thunk.\n */\n\n context.it = context.specify = function(title, fn) {\n var suite = suites[0];\n if (suite.isPending()) {\n fn = null;\n }\n var test = new Test(title, fn);\n test.file = file;\n suite.addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.it.only = function(title, fn) {\n return common.test.only(mocha, context.it(title, fn));\n };\n\n /**\n * Pending test case.\n */\n\n context.xit = context.xspecify = context.it.skip = function(title) {\n return context.it(title);\n };\n });\n};\n\nmodule.exports.description = 'BDD or RSpec style [default]';\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE = require('../suite').constants\n .EVENT_FILE_PRE_REQUIRE;\n\n/**\n * TDD-style interface:\n *\n * suite('Array', function() {\n * suite('#indexOf()', function() {\n * suiteSetup(function() {\n *\n * });\n *\n * test('should return -1 when not present', function() {\n *\n * });\n *\n * test('should return the index when present', function() {\n *\n * });\n *\n * suiteTeardown(function() {\n *\n * });\n * });\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function(suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.setup = common.beforeEach;\n context.teardown = common.afterEach;\n context.suiteSetup = common.before;\n context.suiteTeardown = common.after;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n\n /**\n * Describe a \"suite\" with the given `title` and callback `fn` containing\n * nested suites and/or tests.\n */\n context.suite = function(title, fn) {\n return common.suite.create({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Pending suite.\n */\n context.suite.skip = function(title, fn) {\n return common.suite.skip({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Exclusive test-case.\n */\n context.suite.only = function(title, fn) {\n return common.suite.only({\n title: title,\n file: file,\n fn: fn\n });\n };\n\n /**\n * Describe a specification or test-case with the given `title` and\n * callback `fn` acting as a thunk.\n */\n context.test = function(title, fn) {\n var suite = suites[0];\n if (suite.isPending()) {\n fn = null;\n }\n var test = new Test(title, fn);\n test.file = file;\n suite.addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.test.only = function(title, fn) {\n return common.test.only(mocha, context.test(title, fn));\n };\n\n context.test.skip = common.test.skip;\n });\n};\n\nmodule.exports.description =\n 'traditional \"suite\"/\"test\" instead of BDD\\'s \"describe\"/\"it\"';\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE = require('../suite').constants\n .EVENT_FILE_PRE_REQUIRE;\n\n/**\n * QUnit-style interface:\n *\n * suite('Array');\n *\n * test('#length', function() {\n * var arr = [1,2,3];\n * ok(arr.length == 3);\n * });\n *\n * test('#indexOf()', function() {\n * var arr = [1,2,3];\n * ok(arr.indexOf(1) == 0);\n * ok(arr.indexOf(2) == 1);\n * ok(arr.indexOf(3) == 2);\n * });\n *\n * suite('String');\n *\n * test('#length', function() {\n * ok('foo'.length == 3);\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function qUnitInterface(suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function(context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.before = common.before;\n context.after = common.after;\n context.beforeEach = common.beforeEach;\n context.afterEach = common.afterEach;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n /**\n * Describe a \"suite\" with the given `title`.\n */\n\n context.suite = function(title) {\n if (suites.length > 1) {\n suites.shift();\n }\n return common.suite.create({\n title: title,\n file: file,\n fn: false\n });\n };\n\n /**\n * Exclusive Suite.\n */\n\n context.suite.only = function(title) {\n if (suites.length > 1) {\n suites.shift();\n }\n return common.suite.only({\n title: title,\n file: file,\n fn: false\n });\n };\n\n /**\n * Describe a specification or test-case\n * with the given `title` and callback `fn`\n * acting as a thunk.\n */\n\n context.test = function(title, fn) {\n var test = new Test(title, fn);\n test.file = file;\n suites[0].addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.test.only = function(title, fn) {\n return common.test.only(mocha, context.test(title, fn));\n };\n\n context.test.skip = common.test.skip;\n });\n};\n\nmodule.exports.description = 'QUnit style';\n","'use strict';\nvar Suite = require('../suite');\nvar Test = require('../test');\n\n/**\n * Exports-style (as Node.js module) interface:\n *\n * exports.Array = {\n * '#indexOf()': {\n * 'should return -1 when the value is not present': function() {\n *\n * },\n *\n * 'should return the correct index when the value is present': function() {\n *\n * }\n * }\n * };\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function(suite) {\n var suites = [suite];\n\n suite.on(Suite.constants.EVENT_FILE_REQUIRE, visit);\n\n function visit(obj, file) {\n var suite;\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n var fn = obj[key];\n switch (key) {\n case 'before':\n suites[0].beforeAll(fn);\n break;\n case 'after':\n suites[0].afterAll(fn);\n break;\n case 'beforeEach':\n suites[0].beforeEach(fn);\n break;\n case 'afterEach':\n suites[0].afterEach(fn);\n break;\n default:\n var test = new Test(key, fn);\n test.file = file;\n suites[0].addTest(test);\n }\n } else {\n suite = Suite.create(suites[0], key);\n suites.unshift(suite);\n visit(obj[key], file);\n suites.shift();\n }\n }\n }\n};\n\nmodule.exports.description = 'Node.js module (\"exports\") style';\n","'use strict';\n\nexports.bdd = require('./bdd');\nexports.tdd = require('./tdd');\nexports.qunit = require('./qunit');\nexports.exports = require('./exports');\n","'use strict';\n/**\n * @module Context\n */\n/**\n * Expose `Context`.\n */\n\nmodule.exports = Context;\n\n/**\n * Initialize a new `Context`.\n *\n * @private\n */\nfunction Context() {}\n\n/**\n * Set or get the context `Runnable` to `runnable`.\n *\n * @private\n * @param {Runnable} runnable\n * @return {Context} context\n */\nContext.prototype.runnable = function(runnable) {\n if (!arguments.length) {\n return this._runnable;\n }\n this.test = this._runnable = runnable;\n return this;\n};\n\n/**\n * Set or get test timeout `ms`.\n *\n * @private\n * @param {number} ms\n * @return {Context} self\n */\nContext.prototype.timeout = function(ms) {\n if (!arguments.length) {\n return this.runnable().timeout();\n }\n this.runnable().timeout(ms);\n return this;\n};\n\n/**\n * Set or get test slowness threshold `ms`.\n *\n * @private\n * @param {number} ms\n * @return {Context} self\n */\nContext.prototype.slow = function(ms) {\n if (!arguments.length) {\n return this.runnable().slow();\n }\n this.runnable().slow(ms);\n return this;\n};\n\n/**\n * Mark a test as skipped.\n *\n * @private\n * @throws Pending\n */\nContext.prototype.skip = function() {\n this.runnable().skip();\n};\n\n/**\n * Set or get a number of allowed retries on failed tests\n *\n * @private\n * @param {number} n\n * @return {Context} self\n */\nContext.prototype.retries = function(n) {\n if (!arguments.length) {\n return this.runnable().retries();\n }\n this.runnable().retries(n);\n return this;\n};\n","'use strict';\n\n/*!\n * mocha\n * Copyright(c) 2011 TJ Holowaychuk \n * MIT Licensed\n */\n\nvar escapeRe = require('escape-string-regexp');\nvar path = require('path');\nvar builtinReporters = require('./reporters');\nvar growl = require('./nodejs/growl');\nvar utils = require('./utils');\nvar mocharc = require('./mocharc.json');\nvar Suite = require('./suite');\nvar esmUtils = utils.supportsEsModules(true)\n ? require('./esm-utils')\n : undefined;\nvar createStatsCollector = require('./stats-collector');\nconst {\n warn,\n createInvalidReporterError,\n createInvalidInterfaceError,\n createMochaInstanceAlreadyDisposedError,\n createMochaInstanceAlreadyRunningError,\n createUnsupportedError\n} = require('./errors');\nconst {\n EVENT_FILE_PRE_REQUIRE,\n EVENT_FILE_POST_REQUIRE,\n EVENT_FILE_REQUIRE\n} = Suite.constants;\nvar sQuote = utils.sQuote;\nvar debug = require('debug')('mocha:mocha');\n\nexports = module.exports = Mocha;\n\n/**\n * A Mocha instance is a finite state machine.\n * These are the states it can be in.\n * @private\n */\nvar mochaStates = utils.defineConstants({\n /**\n * Initial state of the mocha instance\n * @private\n */\n INIT: 'init',\n /**\n * Mocha instance is running tests\n * @private\n */\n RUNNING: 'running',\n /**\n * Mocha instance is done running tests and references to test functions and hooks are cleaned.\n * You can reset this state by unloading the test files.\n * @private\n */\n REFERENCES_CLEANED: 'referencesCleaned',\n /**\n * Mocha instance is disposed and can no longer be used.\n * @private\n */\n DISPOSED: 'disposed'\n});\n\n/**\n * To require local UIs and reporters when running in node.\n */\n\nif (!utils.isBrowser() && typeof module.paths !== 'undefined') {\n var cwd = utils.cwd();\n module.paths.push(cwd, path.join(cwd, 'node_modules'));\n}\n\n/**\n * Expose internals.\n * @private\n */\n\nexports.utils = utils;\nexports.interfaces = require('./interfaces');\n/**\n * @public\n * @memberof Mocha\n */\nexports.reporters = builtinReporters;\nexports.Runnable = require('./runnable');\nexports.Context = require('./context');\n/**\n *\n * @memberof Mocha\n */\nexports.Runner = require('./runner');\nexports.Suite = Suite;\nexports.Hook = require('./hook');\nexports.Test = require('./test');\n\nlet currentContext;\nexports.afterEach = function(...args) {\n return (currentContext.afterEach || currentContext.teardown).apply(\n this,\n args\n );\n};\nexports.after = function(...args) {\n return (currentContext.after || currentContext.suiteTeardown).apply(\n this,\n args\n );\n};\nexports.beforeEach = function(...args) {\n return (currentContext.beforeEach || currentContext.setup).apply(this, args);\n};\nexports.before = function(...args) {\n return (currentContext.before || currentContext.suiteSetup).apply(this, args);\n};\nexports.describe = function(...args) {\n return (currentContext.describe || currentContext.suite).apply(this, args);\n};\nexports.describe.only = function(...args) {\n return (currentContext.describe || currentContext.suite).only.apply(\n this,\n args\n );\n};\nexports.describe.skip = function(...args) {\n return (currentContext.describe || currentContext.suite).skip.apply(\n this,\n args\n );\n};\nexports.it = function(...args) {\n return (currentContext.it || currentContext.test).apply(this, args);\n};\nexports.it.only = function(...args) {\n return (currentContext.it || currentContext.test).only.apply(this, args);\n};\nexports.it.skip = function(...args) {\n return (currentContext.it || currentContext.test).skip.apply(this, args);\n};\nexports.xdescribe = exports.describe.skip;\nexports.xit = exports.it.skip;\nexports.setup = exports.beforeEach;\nexports.suiteSetup = exports.before;\nexports.suiteTeardown = exports.after;\nexports.suite = exports.describe;\nexports.teardown = exports.afterEach;\nexports.test = exports.it;\nexports.run = function(...args) {\n return currentContext.run.apply(this, args);\n};\n\n/**\n * Constructs a new Mocha instance with `options`.\n *\n * @public\n * @class Mocha\n * @param {Object} [options] - Settings object.\n * @param {boolean} [options.allowUncaught] - Propagate uncaught errors?\n * @param {boolean} [options.asyncOnly] - Force `done` callback or promise?\n * @param {boolean} [options.bail] - Bail after first test failure?\n * @param {boolean} [options.checkLeaks] - Check for global variable leaks?\n * @param {boolean} [options.color] - Color TTY output from reporter?\n * @param {boolean} [options.delay] - Delay root suite execution?\n * @param {boolean} [options.diff] - Show diff on failure?\n * @param {string} [options.fgrep] - Test filter given string.\n * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite?\n * @param {boolean} [options.forbidPending] - Pending tests fail the suite?\n * @param {boolean} [options.fullTrace] - Full stacktrace upon failure?\n * @param {string[]} [options.global] - Variables expected in global scope.\n * @param {RegExp|string} [options.grep] - Test filter given regular expression.\n * @param {boolean} [options.growl] - Enable desktop notifications?\n * @param {boolean} [options.inlineDiffs] - Display inline diffs?\n * @param {boolean} [options.invert] - Invert test filter matches?\n * @param {boolean} [options.noHighlighting] - Disable syntax highlighting?\n * @param {string|constructor} [options.reporter] - Reporter name or constructor.\n * @param {Object} [options.reporterOption] - Reporter settings object.\n * @param {number} [options.retries] - Number of times to retry failed tests.\n * @param {number} [options.slow] - Slow threshold value.\n * @param {number|string} [options.timeout] - Timeout threshold value.\n * @param {string} [options.ui] - Interface name.\n * @param {boolean} [options.parallel] - Run jobs in parallel.\n * @param {number} [options.jobs] - Max number of worker processes for parallel runs.\n * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with.\n * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs.\n * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process.\n */\nfunction Mocha(options = {}) {\n options = {...mocharc, ...options};\n this.files = [];\n this.options = options;\n // root suite\n this.suite = new exports.Suite('', new exports.Context(), true);\n this._cleanReferencesAfterRun = true;\n this._state = mochaStates.INIT;\n\n this.grep(options.grep)\n .fgrep(options.fgrep)\n .ui(options.ui)\n .reporter(\n options.reporter,\n options.reporterOption || options.reporterOptions // reporterOptions was previously the only way to specify options to reporter\n )\n .slow(options.slow)\n .global(options.global);\n\n // this guard exists because Suite#timeout does not consider `undefined` to be valid input\n if (typeof options.timeout !== 'undefined') {\n this.timeout(options.timeout === false ? 0 : options.timeout);\n }\n\n if ('retries' in options) {\n this.retries(options.retries);\n }\n\n [\n 'allowUncaught',\n 'asyncOnly',\n 'bail',\n 'checkLeaks',\n 'color',\n 'delay',\n 'diff',\n 'forbidOnly',\n 'forbidPending',\n 'fullTrace',\n 'growl',\n 'inlineDiffs',\n 'invert'\n ].forEach(function(opt) {\n if (options[opt]) {\n this[opt]();\n }\n }, this);\n\n if (options.rootHooks) {\n this.rootHooks(options.rootHooks);\n }\n\n /**\n * The class which we'll instantiate in {@link Mocha#run}. Defaults to\n * {@link Runner} in serial mode; changes in parallel mode.\n * @memberof Mocha\n * @private\n */\n this._runnerClass = exports.Runner;\n\n /**\n * Whether or not to call {@link Mocha#loadFiles} implicitly when calling\n * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call\n * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}.\n * @private\n * @memberof Mocha\n */\n this._lazyLoadFiles = false;\n\n /**\n * It's useful for a Mocha instance to know if it's running in a worker process.\n * We could derive this via other means, but it's helpful to have a flag to refer to.\n * @memberof Mocha\n * @private\n */\n this.isWorker = Boolean(options.isWorker);\n\n this.globalSetup(options.globalSetup)\n .globalTeardown(options.globalTeardown)\n .enableGlobalSetup(options.enableGlobalSetup)\n .enableGlobalTeardown(options.enableGlobalTeardown);\n\n if (\n options.parallel &&\n (typeof options.jobs === 'undefined' || options.jobs > 1)\n ) {\n debug('attempting to enable parallel mode');\n this.parallelMode(true);\n }\n}\n\n/**\n * Enables or disables bailing on the first failure.\n *\n * @public\n * @see [CLI option](../#-bail-b)\n * @param {boolean} [bail=true] - Whether to bail on first error.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.bail = function(bail) {\n this.suite.bail(bail !== false);\n return this;\n};\n\n/**\n * @summary\n * Adds `file` to be loaded for execution.\n *\n * @description\n * Useful for generic setup code that must be included within test suite.\n *\n * @public\n * @see [CLI option](../#-file-filedirectoryglob)\n * @param {string} file - Pathname of file to be loaded.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.addFile = function(file) {\n this.files.push(file);\n return this;\n};\n\n/**\n * Sets reporter to `reporter`, defaults to \"spec\".\n *\n * @public\n * @see [CLI option](../#-reporter-name-r-name)\n * @see [Reporters](../#reporters)\n * @param {String|Function} reporterName - Reporter name or constructor.\n * @param {Object} [reporterOptions] - Options used to configure the reporter.\n * @returns {Mocha} this\n * @chainable\n * @throws {Error} if requested reporter cannot be loaded\n * @example\n *\n * // Use XUnit reporter and direct its output to file\n * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });\n */\nMocha.prototype.reporter = function(reporterName, reporterOptions) {\n if (typeof reporterName === 'function') {\n this._reporter = reporterName;\n } else {\n reporterName = reporterName || 'spec';\n var reporter;\n // Try to load a built-in reporter.\n if (builtinReporters[reporterName]) {\n reporter = builtinReporters[reporterName];\n }\n // Try to load reporters from process.cwd() and node_modules\n if (!reporter) {\n try {\n reporter = require(reporterName);\n } catch (err) {\n if (err.code === 'MODULE_NOT_FOUND') {\n // Try to load reporters from a path (absolute or relative)\n try {\n reporter = require(path.resolve(utils.cwd(), reporterName));\n } catch (_err) {\n _err.code === 'MODULE_NOT_FOUND'\n ? warn(sQuote(reporterName) + ' reporter not found')\n : warn(\n sQuote(reporterName) +\n ' reporter blew up with error:\\n' +\n err.stack\n );\n }\n } else {\n warn(\n sQuote(reporterName) + ' reporter blew up with error:\\n' + err.stack\n );\n }\n }\n }\n if (!reporter) {\n throw createInvalidReporterError(\n 'invalid reporter ' + sQuote(reporterName),\n reporterName\n );\n }\n this._reporter = reporter;\n }\n this.options.reporterOption = reporterOptions;\n // alias option name is used in public reporters xunit/tap/progress\n this.options.reporterOptions = reporterOptions;\n return this;\n};\n\n/**\n * Sets test UI `name`, defaults to \"bdd\".\n *\n * @public\n * @see [CLI option](../#-ui-name-u-name)\n * @see [Interface DSLs](../#interfaces)\n * @param {string|Function} [ui=bdd] - Interface name or class.\n * @returns {Mocha} this\n * @chainable\n * @throws {Error} if requested interface cannot be loaded\n */\nMocha.prototype.ui = function(ui) {\n var bindInterface;\n if (typeof ui === 'function') {\n bindInterface = ui;\n } else {\n ui = ui || 'bdd';\n bindInterface = exports.interfaces[ui];\n if (!bindInterface) {\n try {\n bindInterface = require(ui);\n } catch (err) {\n throw createInvalidInterfaceError(\n 'invalid interface ' + sQuote(ui),\n ui\n );\n }\n }\n }\n bindInterface(this.suite);\n\n this.suite.on(EVENT_FILE_PRE_REQUIRE, function(context) {\n currentContext = context;\n });\n\n return this;\n};\n\n/**\n * Loads `files` prior to execution. Does not support ES Modules.\n *\n * @description\n * The implementation relies on Node's `require` to execute\n * the test interface functions and will be subject to its cache.\n * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync.\n *\n * @private\n * @see {@link Mocha#addFile}\n * @see {@link Mocha#run}\n * @see {@link Mocha#unloadFiles}\n * @see {@link Mocha#loadFilesAsync}\n * @param {Function} [fn] - Callback invoked upon completion.\n */\nMocha.prototype.loadFiles = function(fn) {\n var self = this;\n var suite = this.suite;\n this.files.forEach(function(file) {\n file = path.resolve(file);\n suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);\n suite.emit(EVENT_FILE_REQUIRE, require(file), file, self);\n suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);\n });\n fn && fn();\n};\n\n/**\n * Loads `files` prior to execution. Supports Node ES Modules.\n *\n * @description\n * The implementation relies on Node's `require` and `import` to execute\n * the test interface functions and will be subject to its cache.\n * Supports both CJS and ESM modules.\n *\n * @public\n * @see {@link Mocha#addFile}\n * @see {@link Mocha#run}\n * @see {@link Mocha#unloadFiles}\n * @returns {Promise}\n * @example\n *\n * // loads ESM (and CJS) test files asynchronously, then runs root suite\n * mocha.loadFilesAsync()\n * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))\n * .catch(() => process.exitCode = 1);\n */\nMocha.prototype.loadFilesAsync = function() {\n var self = this;\n var suite = this.suite;\n this.lazyLoadFiles(true);\n\n if (!esmUtils) {\n return new Promise(function(resolve) {\n self.loadFiles(resolve);\n });\n }\n\n return esmUtils.loadFilesAsync(\n this.files,\n function(file) {\n suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);\n },\n function(file, resultModule) {\n suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self);\n suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);\n }\n );\n};\n\n/**\n * Removes a previously loaded file from Node's `require` cache.\n *\n * @private\n * @static\n * @see {@link Mocha#unloadFiles}\n * @param {string} file - Pathname of file to be unloaded.\n */\nMocha.unloadFile = function(file) {\n if (utils.isBrowser()) {\n throw createUnsupportedError(\n 'unloadFile() is only suported in a Node.js environment'\n );\n }\n return require('./nodejs/file-unloader').unloadFile(file);\n};\n\n/**\n * Unloads `files` from Node's `require` cache.\n *\n * @description\n * This allows required files to be \"freshly\" reloaded, providing the ability\n * to reuse a Mocha instance programmatically.\n * Note: does not clear ESM module files from the cache\n *\n * Intended for consumers — not used internally\n *\n * @public\n * @see {@link Mocha#run}\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.unloadFiles = function() {\n if (this._state === mochaStates.DISPOSED) {\n throw createMochaInstanceAlreadyDisposedError(\n 'Mocha instance is already disposed, it cannot be used again.',\n this._cleanReferencesAfterRun,\n this\n );\n }\n\n this.files.forEach(function(file) {\n Mocha.unloadFile(file);\n });\n this._state = mochaStates.INIT;\n return this;\n};\n\n/**\n * Sets `grep` filter after escaping RegExp special characters.\n *\n * @public\n * @see {@link Mocha#grep}\n * @param {string} str - Value to be converted to a regexp.\n * @returns {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title begins with `\"foo\"` followed by a period\n * mocha.fgrep('foo.');\n */\nMocha.prototype.fgrep = function(str) {\n if (!str) {\n return this;\n }\n return this.grep(new RegExp(escapeRe(str)));\n};\n\n/**\n * @summary\n * Sets `grep` filter used to select specific tests for execution.\n *\n * @description\n * If `re` is a regexp-like string, it will be converted to regexp.\n * The regexp is tested against the full title of each test (i.e., the\n * name of the test preceded by titles of each its ancestral suites).\n * As such, using an exact-match fixed pattern against the\n * test name itself will not yield any matches.\n *
          \n * Previous filter value will be overwritten on each call!\n *\n * @public\n * @see [CLI option](../#-grep-regexp-g-regexp)\n * @see {@link Mocha#fgrep}\n * @see {@link Mocha#invert}\n * @param {RegExp|String} re - Regular expression used to select tests.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title contains `\"match\"`, ignoring case\n * mocha.grep(/match/i);\n * @example\n *\n * // Same as above but with regexp-like string argument\n * mocha.grep('/match/i');\n * @example\n *\n * // ## Anti-example\n * // Given embedded test `it('only-this-test')`...\n * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this!\n */\nMocha.prototype.grep = function(re) {\n if (utils.isString(re)) {\n // extract args if it's regex-like, i.e: [string, pattern, flag]\n var arg = re.match(/^\\/(.*)\\/(g|i|)$|.*/);\n this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);\n } else {\n this.options.grep = re;\n }\n return this;\n};\n\n/**\n * Inverts `grep` matches.\n *\n * @public\n * @see {@link Mocha#grep}\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title does *not* contain `\"match\"`, ignoring case\n * mocha.grep(/match/i).invert();\n */\nMocha.prototype.invert = function() {\n this.options.invert = true;\n return this;\n};\n\n/**\n * Enables or disables checking for global variables leaked while running tests.\n *\n * @public\n * @see [CLI option](../#-check-leaks)\n * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.checkLeaks = function(checkLeaks) {\n this.options.checkLeaks = checkLeaks !== false;\n return this;\n};\n\n/**\n * Enables or disables whether or not to dispose after each test run.\n * Disable this to ensure you can run the test suite multiple times.\n * If disabled, be sure to dispose mocha when you're done to prevent memory leaks.\n * @public\n * @see {@link Mocha#dispose}\n * @param {boolean} cleanReferencesAfterRun\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.cleanReferencesAfterRun = function(cleanReferencesAfterRun) {\n this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false;\n return this;\n};\n\n/**\n * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests.\n * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector.\n * @public\n */\nMocha.prototype.dispose = function() {\n if (this._state === mochaStates.RUNNING) {\n throw createMochaInstanceAlreadyRunningError(\n 'Cannot dispose while the mocha instance is still running tests.'\n );\n }\n this.unloadFiles();\n this._previousRunner && this._previousRunner.dispose();\n this.suite.dispose();\n this._state = mochaStates.DISPOSED;\n};\n\n/**\n * Displays full stack trace upon test failure.\n *\n * @public\n * @see [CLI option](../#-full-trace)\n * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.fullTrace = function(fullTrace) {\n this.options.fullTrace = fullTrace !== false;\n return this;\n};\n\n/**\n * Enables desktop notification support if prerequisite software installed.\n *\n * @public\n * @see [CLI option](../#-growl-g)\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.growl = function() {\n this.options.growl = this.isGrowlCapable();\n if (!this.options.growl) {\n var detail = utils.isBrowser()\n ? 'notification support not available in this browser...'\n : 'notification support prerequisites not installed...';\n console.error(detail + ' cannot enable!');\n }\n return this;\n};\n\n/**\n * @summary\n * Determines if Growl support seems likely.\n *\n * @description\n * Not available when run in browser.\n *\n * @private\n * @see {@link Growl#isCapable}\n * @see {@link Mocha#growl}\n * @return {boolean} whether Growl support can be expected\n */\nMocha.prototype.isGrowlCapable = growl.isCapable;\n\n/**\n * Implements desktop notifications using a pseudo-reporter.\n *\n * @private\n * @see {@link Mocha#growl}\n * @see {@link Growl#notify}\n * @param {Runner} runner - Runner instance.\n */\nMocha.prototype._growl = growl.notify;\n\n/**\n * Specifies whitelist of variable names to be expected in global scope.\n *\n * @public\n * @see [CLI option](../#-global-variable-name)\n * @see {@link Mocha#checkLeaks}\n * @param {String[]|String} global - Accepted global variable name(s).\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Specify variables to be expected in global scope\n * mocha.global(['jQuery', 'MyLib']);\n */\nMocha.prototype.global = function(global) {\n this.options.global = (this.options.global || [])\n .concat(global)\n .filter(Boolean)\n .filter(function(elt, idx, arr) {\n return arr.indexOf(elt) === idx;\n });\n return this;\n};\n// for backwards compability, 'globals' is an alias of 'global'\nMocha.prototype.globals = Mocha.prototype.global;\n\n/**\n * Enables or disables TTY color output by screen-oriented reporters.\n *\n * @public\n * @see [CLI option](../#-color-c-colors)\n * @param {boolean} [color=true] - Whether to enable color output.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.color = function(color) {\n this.options.color = color !== false;\n return this;\n};\n\n/**\n * Enables or disables reporter to use inline diffs (rather than +/-)\n * in test failure output.\n *\n * @public\n * @see [CLI option](../#-inline-diffs)\n * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.inlineDiffs = function(inlineDiffs) {\n this.options.inlineDiffs = inlineDiffs !== false;\n return this;\n};\n\n/**\n * Enables or disables reporter to include diff in test failure output.\n *\n * @public\n * @see [CLI option](../#-diff)\n * @param {boolean} [diff=true] - Whether to show diff on failure.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.diff = function(diff) {\n this.options.diff = diff !== false;\n return this;\n};\n\n/**\n * @summary\n * Sets timeout threshold value.\n *\n * @description\n * A string argument can use shorthand (such as \"2s\") and will be converted.\n * If the value is `0`, timeouts will be disabled.\n *\n * @public\n * @see [CLI option](../#-timeout-ms-t-ms)\n * @see [Timeouts](../#timeouts)\n * @param {number|string} msecs - Timeout threshold value.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Sets timeout to one second\n * mocha.timeout(1000);\n * @example\n *\n * // Same as above but using string argument\n * mocha.timeout('1s');\n */\nMocha.prototype.timeout = function(msecs) {\n this.suite.timeout(msecs);\n return this;\n};\n\n/**\n * Sets the number of times to retry failed tests.\n *\n * @public\n * @see [CLI option](../#-retries-n)\n * @see [Retry Tests](../#retry-tests)\n * @param {number} retry - Number of times to retry failed tests.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Allow any failed test to retry one more time\n * mocha.retries(1);\n */\nMocha.prototype.retries = function(retry) {\n this.suite.retries(retry);\n return this;\n};\n\n/**\n * Sets slowness threshold value.\n *\n * @public\n * @see [CLI option](../#-slow-ms-s-ms)\n * @param {number} msecs - Slowness threshold value.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Sets \"slow\" threshold to half a second\n * mocha.slow(500);\n * @example\n *\n * // Same as above but using string argument\n * mocha.slow('0.5s');\n */\nMocha.prototype.slow = function(msecs) {\n this.suite.slow(msecs);\n return this;\n};\n\n/**\n * Forces all tests to either accept a `done` callback or return a promise.\n *\n * @public\n * @see [CLI option](../#-async-only-a)\n * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.asyncOnly = function(asyncOnly) {\n this.options.asyncOnly = asyncOnly !== false;\n return this;\n};\n\n/**\n * Disables syntax highlighting (in browser).\n *\n * @public\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.noHighlighting = function() {\n this.options.noHighlighting = true;\n return this;\n};\n\n/**\n * Enables or disables uncaught errors to propagate.\n *\n * @public\n * @see [CLI option](../#-allow-uncaught)\n * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.allowUncaught = function(allowUncaught) {\n this.options.allowUncaught = allowUncaught !== false;\n return this;\n};\n\n/**\n * @summary\n * Delays root suite execution.\n *\n * @description\n * Used to perform async operations before any suites are run.\n *\n * @public\n * @see [delayed root suite](../#delayed-root-suite)\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.delay = function delay() {\n this.options.delay = true;\n return this;\n};\n\n/**\n * Causes tests marked `only` to fail the suite.\n *\n * @public\n * @see [CLI option](../#-forbid-only)\n * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.forbidOnly = function(forbidOnly) {\n this.options.forbidOnly = forbidOnly !== false;\n return this;\n};\n\n/**\n * Causes pending tests and tests marked `skip` to fail the suite.\n *\n * @public\n * @see [CLI option](../#-forbid-pending)\n * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.forbidPending = function(forbidPending) {\n this.options.forbidPending = forbidPending !== false;\n return this;\n};\n\n/**\n * Throws an error if mocha is in the wrong state to be able to transition to a \"running\" state.\n * @private\n */\nMocha.prototype._guardRunningStateTransition = function() {\n if (this._state === mochaStates.RUNNING) {\n throw createMochaInstanceAlreadyRunningError(\n 'Mocha instance is currently running tests, cannot start a next test run until this one is done',\n this\n );\n }\n if (\n this._state === mochaStates.DISPOSED ||\n this._state === mochaStates.REFERENCES_CLEANED\n ) {\n throw createMochaInstanceAlreadyDisposedError(\n 'Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.',\n this._cleanReferencesAfterRun,\n this\n );\n }\n};\n\n/**\n * Mocha version as specified by \"package.json\".\n *\n * @name Mocha#version\n * @type string\n * @readonly\n */\nObject.defineProperty(Mocha.prototype, 'version', {\n value: require('../package.json').version,\n configurable: false,\n enumerable: true,\n writable: false\n});\n\n/**\n * Callback to be invoked when test execution is complete.\n *\n * @private\n * @callback DoneCB\n * @param {number} failures - Number of failures that occurred.\n */\n\n/**\n * Runs root suite and invokes `fn()` when complete.\n *\n * @description\n * To run tests multiple times (or to run tests in files that are\n * already in the `require` cache), make sure to clear them from\n * the cache first!\n *\n * @public\n * @see {@link Mocha#unloadFiles}\n * @see {@link Runner#run}\n * @param {DoneCB} [fn] - Callback invoked when test execution completed.\n * @returns {Runner} runner instance\n * @example\n *\n * // exit with non-zero status if there were test failures\n * mocha.run(failures => process.exitCode = failures ? 1 : 0);\n */\nMocha.prototype.run = function(fn) {\n this._guardRunningStateTransition();\n this._state = mochaStates.RUNNING;\n if (this._previousRunner) {\n this._previousRunner.dispose();\n this.suite.reset();\n }\n if (this.files.length && !this._lazyLoadFiles) {\n this.loadFiles();\n }\n var suite = this.suite;\n var options = this.options;\n options.files = this.files;\n const runner = new this._runnerClass(suite, {\n delay: options.delay,\n cleanReferencesAfterRun: this._cleanReferencesAfterRun\n });\n createStatsCollector(runner);\n var reporter = new this._reporter(runner, options);\n runner.checkLeaks = options.checkLeaks === true;\n runner.fullStackTrace = options.fullTrace;\n runner.asyncOnly = options.asyncOnly;\n runner.allowUncaught = options.allowUncaught;\n runner.forbidOnly = options.forbidOnly;\n runner.forbidPending = options.forbidPending;\n if (options.grep) {\n runner.grep(options.grep, options.invert);\n }\n if (options.global) {\n runner.globals(options.global);\n }\n if (options.growl) {\n this._growl(runner);\n }\n if (options.color !== undefined) {\n exports.reporters.Base.useColors = options.color;\n }\n exports.reporters.Base.inlineDiffs = options.inlineDiffs;\n exports.reporters.Base.hideDiff = !options.diff;\n\n const done = failures => {\n this._previousRunner = runner;\n this._state = this._cleanReferencesAfterRun\n ? mochaStates.REFERENCES_CLEANED\n : mochaStates.INIT;\n fn = fn || utils.noop;\n if (typeof reporter.done === 'function') {\n reporter.done(failures, fn);\n } else {\n fn(failures);\n }\n };\n\n const runAsync = async runner => {\n const context =\n this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()\n ? await this.runGlobalSetup(runner)\n : {};\n const failureCount = await runner.runAsync({\n files: this.files,\n options\n });\n if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {\n await this.runGlobalTeardown(runner, {context});\n }\n return failureCount;\n };\n\n // no \"catch\" here is intentional. errors coming out of\n // Runner#run are considered uncaught/unhandled and caught\n // by the `process` event listeners.\n // also: returning anything other than `runner` would be a breaking\n // change\n runAsync(runner).then(done);\n\n return runner;\n};\n\n/**\n * Assigns hooks to the root suite\n * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite\n * @chainable\n */\nMocha.prototype.rootHooks = function rootHooks({\n beforeAll = [],\n beforeEach = [],\n afterAll = [],\n afterEach = []\n} = {}) {\n beforeAll = utils.castArray(beforeAll);\n beforeEach = utils.castArray(beforeEach);\n afterAll = utils.castArray(afterAll);\n afterEach = utils.castArray(afterEach);\n beforeAll.forEach(hook => {\n this.suite.beforeAll(hook);\n });\n beforeEach.forEach(hook => {\n this.suite.beforeEach(hook);\n });\n afterAll.forEach(hook => {\n this.suite.afterAll(hook);\n });\n afterEach.forEach(hook => {\n this.suite.afterEach(hook);\n });\n return this;\n};\n\n/**\n * Toggles parallel mode.\n *\n * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to\n * use; also enables lazy file loading if not already done so.\n *\n * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel\n * mode, but parallel mode is _not_ a prerequisite for lazy loading!\n * @param {boolean} [enable] - If `true`, enable; otherwise disable.\n * @throws If run in browser\n * @throws If Mocha not in `INIT` state\n * @returns {Mocha}\n * @chainable\n * @public\n */\nMocha.prototype.parallelMode = function parallelMode(enable = true) {\n if (utils.isBrowser()) {\n throw createUnsupportedError('parallel mode is only supported in Node.js');\n }\n const parallel = Boolean(enable);\n if (\n parallel === this.options.parallel &&\n this._lazyLoadFiles &&\n this._runnerClass !== exports.Runner\n ) {\n return this;\n }\n if (this._state !== mochaStates.INIT) {\n throw createUnsupportedError(\n 'cannot change parallel mode after having called run()'\n );\n }\n this.options.parallel = parallel;\n\n // swap Runner class\n this._runnerClass = parallel\n ? require('./nodejs/parallel-buffered-runner')\n : exports.Runner;\n\n // lazyLoadFiles may have been set `true` otherwise (for ESM loading),\n // so keep `true` if so.\n return this.lazyLoadFiles(this._lazyLoadFiles || parallel);\n};\n\n/**\n * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This\n * setting is used by watch mode, parallel mode, and for loading ESM files.\n * @todo This should throw if we've already loaded files; such behavior\n * necessitates adding a new state.\n * @param {boolean} [enable] - If `true`, disable eager loading of files in\n * {@link Mocha#run}\n * @chainable\n * @public\n */\nMocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {\n this._lazyLoadFiles = enable === true;\n debug('set lazy load to %s', enable);\n return this;\n};\n\n/**\n * Configures one or more global setup fixtures.\n *\n * If given no parameters, _unsets_ any previously-set fixtures.\n * @chainable\n * @public\n * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s)\n * @returns {Mocha}\n */\nMocha.prototype.globalSetup = function globalSetup(setupFns = []) {\n setupFns = utils.castArray(setupFns);\n this.options.globalSetup = setupFns;\n debug('configured %d global setup functions', setupFns.length);\n return this;\n};\n\n/**\n * Configures one or more global teardown fixtures.\n *\n * If given no parameters, _unsets_ any previously-set fixtures.\n * @chainable\n * @public\n * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s)\n * @returns {Mocha}\n */\nMocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {\n teardownFns = utils.castArray(teardownFns);\n this.options.globalTeardown = teardownFns;\n debug('configured %d global teardown functions', teardownFns.length);\n return this;\n};\n\n/**\n * Run any global setup fixtures sequentially, if any.\n *\n * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}.\n *\n * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.\n * @param {object} [context] - Context object if already have one\n * @public\n * @returns {Promise} Context object\n */\nMocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {\n const {globalSetup} = this.options;\n if (globalSetup && globalSetup.length) {\n debug('run(): global setup starting');\n await this._runGlobalFixtures(globalSetup, context);\n debug('run(): global setup complete');\n }\n return context;\n};\n\n/**\n * Run any global teardown fixtures sequentially, if any.\n *\n * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}.\n *\n * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.\n * @param {object} [context] - Context object if already have one\n * @public\n * @returns {Promise} Context object\n */\nMocha.prototype.runGlobalTeardown = async function runGlobalTeardown(\n context = {}\n) {\n const {globalTeardown} = this.options;\n if (globalTeardown && globalTeardown.length) {\n debug('run(): global teardown starting');\n await this._runGlobalFixtures(globalTeardown, context);\n }\n debug('run(): global teardown complete');\n return context;\n};\n\n/**\n * Run global fixtures sequentially with context `context`\n * @private\n * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run\n * @param {object} [context] - context object\n * @returns {Promise} context object\n */\nMocha.prototype._runGlobalFixtures = async function _runGlobalFixtures(\n fixtureFns = [],\n context = {}\n) {\n for await (const fixtureFn of fixtureFns) {\n await fixtureFn.call(context);\n }\n return context;\n};\n\n/**\n * Toggle execution of any global setup fixture(s)\n *\n * @chainable\n * @public\n * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture\n * @returns {Mocha}\n */\nMocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) {\n this.options.enableGlobalSetup = Boolean(enabled);\n return this;\n};\n\n/**\n * Toggle execution of any global teardown fixture(s)\n *\n * @chainable\n * @public\n * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture\n * @returns {Mocha}\n */\nMocha.prototype.enableGlobalTeardown = function enableGlobalTeardown(\n enabled = true\n) {\n this.options.enableGlobalTeardown = Boolean(enabled);\n return this;\n};\n\n/**\n * Returns `true` if one or more global setup fixtures have been supplied.\n * @public\n * @returns {boolean}\n */\nMocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() {\n return Boolean(this.options.globalSetup.length);\n};\n\n/**\n * Returns `true` if one or more global teardown fixtures have been supplied.\n * @public\n * @returns {boolean}\n */\nMocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures() {\n return Boolean(this.options.globalTeardown.length);\n};\n\n/**\n * An alternative way to define root hooks that works with parallel runs.\n * @typedef {Object} MochaRootHookObject\n * @property {Function|Function[]} [beforeAll] - \"Before all\" hook(s)\n * @property {Function|Function[]} [beforeEach] - \"Before each\" hook(s)\n * @property {Function|Function[]} [afterAll] - \"After all\" hook(s)\n * @property {Function|Function[]} [afterEach] - \"After each\" hook(s)\n */\n\n/**\n * An function that returns a {@link MochaRootHookObject}, either sync or async.\n @callback MochaRootHookFunction\n * @returns {MochaRootHookObject|Promise}\n */\n\n/**\n * A function that's invoked _once_ which is either sync or async.\n * Can be a \"teardown\" or \"setup\". These will all share the same context.\n * @callback MochaGlobalFixture\n * @returns {void|Promise}\n */\n\n/**\n * An object making up all necessary parts of a plugin loader and aggregator\n * @typedef {Object} PluginDefinition\n * @property {string} exportName - Named export to use\n * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted)\n * @property {PluginValidator} [validate] - Validator function\n * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function\n */\n\n/**\n * A (sync) function to assert a user-supplied plugin implementation is valid.\n *\n * Defined in a {@link PluginDefinition}.\n\n * @callback PluginValidator\n * @param {*} value - Value to check\n * @this {PluginDefinition}\n * @returns {void}\n */\n\n/**\n * A function to finalize plugins impls of a particular ilk\n * @callback PluginFinalizer\n * @param {Array<*>} impls - User-supplied implementations\n * @returns {Promise<*>|*}\n */\n","'use strict';\n\n/* eslint no-unused-vars: off */\n/* eslint-env commonjs */\n\n/**\n * Shim process.stdout.\n */\n\nprocess.stdout = require('browser-stdout')({label: false});\n\nvar parseQuery = require('./lib/browser/parse-query');\nvar highlightTags = require('./lib/browser/highlight-tags');\nvar Mocha = require('./lib/mocha');\n\n/**\n * Create a Mocha instance.\n *\n * @return {undefined}\n */\n\nvar mocha = new Mocha({reporter: 'html'});\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\n\nvar Date = global.Date;\nvar setTimeout = global.setTimeout;\nvar setInterval = global.setInterval;\nvar clearTimeout = global.clearTimeout;\nvar clearInterval = global.clearInterval;\n\nvar uncaughtExceptionHandlers = [];\n\nvar originalOnerrorHandler = global.onerror;\n\n/**\n * Remove uncaughtException listener.\n * Revert to original onerror handler if previously defined.\n */\n\nprocess.removeListener = function(e, fn) {\n if (e === 'uncaughtException') {\n if (originalOnerrorHandler) {\n global.onerror = originalOnerrorHandler;\n } else {\n global.onerror = function() {};\n }\n var i = uncaughtExceptionHandlers.indexOf(fn);\n if (i !== -1) {\n uncaughtExceptionHandlers.splice(i, 1);\n }\n }\n};\n\n/**\n * Implements listenerCount for 'uncaughtException'.\n */\n\nprocess.listenerCount = function(name) {\n if (name === 'uncaughtException') {\n return uncaughtExceptionHandlers.length;\n }\n return 0;\n};\n\n/**\n * Implements uncaughtException listener.\n */\n\nprocess.on = function(e, fn) {\n if (e === 'uncaughtException') {\n global.onerror = function(err, url, line) {\n fn(new Error(err + ' (' + url + ':' + line + ')'));\n return !mocha.options.allowUncaught;\n };\n uncaughtExceptionHandlers.push(fn);\n }\n};\n\nprocess.listeners = function(e) {\n if (e === 'uncaughtException') {\n return uncaughtExceptionHandlers;\n }\n return [];\n};\n\n// The BDD UI is registered by default, but no UI will be functional in the\n// browser without an explicit call to the overridden `mocha.ui` (see below).\n// Ensure that this default UI does not expose its methods to the global scope.\nmocha.suite.removeAllListeners('pre-require');\n\nvar immediateQueue = [];\nvar immediateTimeout;\n\nfunction timeslice() {\n var immediateStart = new Date().getTime();\n while (immediateQueue.length && new Date().getTime() - immediateStart < 100) {\n immediateQueue.shift()();\n }\n if (immediateQueue.length) {\n immediateTimeout = setTimeout(timeslice, 0);\n } else {\n immediateTimeout = null;\n }\n}\n\n/**\n * High-performance override of Runner.immediately.\n */\n\nMocha.Runner.immediately = function(callback) {\n immediateQueue.push(callback);\n if (!immediateTimeout) {\n immediateTimeout = setTimeout(timeslice, 0);\n }\n};\n\n/**\n * Function to allow assertion libraries to throw errors directly into mocha.\n * This is useful when running tests in a browser because window.onerror will\n * only receive the 'message' attribute of the Error.\n */\nmocha.throwError = function(err) {\n uncaughtExceptionHandlers.forEach(function(fn) {\n fn(err);\n });\n throw err;\n};\n\n/**\n * Override ui to ensure that the ui functions are initialized.\n * Normally this would happen in Mocha.prototype.loadFiles.\n */\n\nmocha.ui = function(ui) {\n Mocha.prototype.ui.call(this, ui);\n this.suite.emit('pre-require', global, null, this);\n return this;\n};\n\n/**\n * Setup mocha with the given setting options.\n */\n\nmocha.setup = function(opts) {\n if (typeof opts === 'string') {\n opts = {ui: opts};\n }\n if (opts.delay === true) {\n this.delay();\n }\n var self = this;\n Object.keys(opts)\n .filter(function(opt) {\n return opt !== 'delay';\n })\n .forEach(function(opt) {\n if (Object.prototype.hasOwnProperty.call(opts, opt)) {\n self[opt](opts[opt]);\n }\n });\n return this;\n};\n\n/**\n * Run mocha, returning the Runner.\n */\n\nmocha.run = function(fn) {\n var options = mocha.options;\n mocha.globals('location');\n\n var query = parseQuery(global.location.search || '');\n if (query.grep) {\n mocha.grep(query.grep);\n }\n if (query.fgrep) {\n mocha.fgrep(query.fgrep);\n }\n if (query.invert) {\n mocha.invert();\n }\n\n return Mocha.prototype.run.call(mocha, function(err) {\n // The DOM Document is not available in Web Workers.\n var document = global.document;\n if (\n document &&\n document.getElementById('mocha') &&\n options.noHighlighting !== true\n ) {\n highlightTags('code');\n }\n if (fn) {\n fn(err);\n }\n });\n};\n\n/**\n * Expose the process shim.\n * https://github.com/mochajs/mocha/pull/916\n */\n\nMocha.process = process;\n\n/**\n * Expose mocha.\n */\n\nglobal.Mocha = Mocha;\nglobal.mocha = mocha;\n\n// this allows test/acceptance/required-tokens.js to pass; thus,\n// you can now do `const describe = require('mocha').describe` in a\n// browser context (assuming browserification). should fix #880\nmodule.exports = Object.assign(mocha, global);\n"],"names":["global","classof","IndexedObject","document","DESCRIPTORS","createElement","IE8_DOM_DEFINE","propertyIsEnumerableModule","definePropertyModule","store","WeakMap","has","NATIVE_WEAK_MAP","shared","objectHas","InternalStateModule","min","require$$0","hiddenKeys","internalObjectKeys","getOwnPropertyNamesModule","getOwnPropertySymbolsModule","getOwnPropertyDescriptorModule","getOwnPropertyDescriptor","isForced","aFunction","NATIVE_SYMBOL","Symbol","USE_SYMBOL_AS_UID","createMethod","bind","userAgent","SPECIES","V8_VERSION","$","HAS_SPECIES_SUPPORT","USES_TO_LENGTH","max","defineProperty","assign","nativeKeys","UNSUPPORTED_Y","stickyHelpers","exec","fixRegExpWellKnownSymbolLogic","regExpExec","DOMIterables","forEach","MAX_SAFE_INTEGER","self","window","defaultSetTimout","Error","defaultClearTimeout","cachedSetTimeout","cachedClearTimeout","setTimeout","clearTimeout","runTimeout","fun","e","call","runClearTimeout","marker","queue","draining","currentQueue","queueIndex","cleanUpNextTick","length","concat","drainQueue","timeout","len","run","nextTick","args","Array","arguments","i","push","Item","array","prototype","apply","title","platform","browser","env","argv","version","versions","release","config","noop","on","addListener","once","off","removeListener","removeAllListeners","emit","binding","name","cwd","chdir","dir","umask","performance","performanceNow","now","mozNow","msNow","oNow","webkitNow","Date","getTime","hrtime","previousTimestamp","clocktime","seconds","Math","floor","nanoseconds","startTime","uptime","currentTime","dif","TO_STRING_TAG","TO_STRING_TAG_SUPPORT","toString","flags","CORRECT_PROTOTYPE_GETTER","FAILS_ON_PRIMITIVES","nativeGetPrototypeOf","domain","EventHandlers","Object","create","EventEmitter","init","usingDomains","undefined","_events","_maxListeners","defaultMaxListeners","active","getPrototypeOf","_eventsCount","setMaxListeners","n","isNaN","TypeError","$getMaxListeners","that","getMaxListeners","emitNone","handler","isFn","listeners","arrayClone","emitOne","arg1","emitTwo","arg2","emitThree","arg3","emitMany","type","er","events","doError","error","domainEmitter","domainThrown","err","context","_addListener","target","listener","prepend","m","existing","newListener","unshift","warned","w","emitter","count","emitWarning","console","warn","log","prependListener","_onceWrap","fired","g","prependOnceListener","list","position","originalListener","spliceOne","keys","key","evlistener","ret","unwrapListeners","listenerCount","eventNames","Reflect","ownKeys","index","k","pop","arr","copy","STRICT_METHOD","setPrototypeOf","IE_PROTO","defineProperties","require$$1","require$$2","require$$3","nativeGetOwnPropertyDescriptor","FORCED","nativeGetOwnPropertyNames","getOwnPropertyNames","MATCH","RegExpPrototype","isRegExp","getFlags","callRegExpExec","wrappedWellKnownSymbolModule","$forEach","PROTOTYPE","setInternalState","ObjectPrototype","nativeDefineProperty","getOwnPropertyNamesExternal","nativePropertyIsEnumerable","WellKnownSymbolsStore","nativeObjectCreate","fill","IteratorPrototype","returnThis","Iterators","IteratorsCore","BUGGY_SAFARI_ITERATORS","ITERATOR","getInternalState","Infinity","RangeError","IEEE754","get","set","NATIVE_ARRAY_BUFFER","j","ARRAY_BUFFER","ArrayBuffer","arrayBufferModule","NativeArrayBuffer","correctIsRegExpLogic","notARegExp","forcedStringTrimMethod","Int8Array","NAME","NATIVE_ARRAY_BUFFER_VIEWS","ArrayPrototype","aTypedArrayConstructor","ArrayBufferModule","ArrayBufferViewCore","TYPED_ARRAYS_CONSTRUCTORS_REQUIRES_WRAPPERS","createTypedArrayConstructor","aTypedArray","exportTypedArrayMethod","$copyWithin","$fill","$filter","$includes","Uint8Array","ArrayIterators","$lastIndexOf","$map","$slice","lookup","revLookup","Arr","inited","code","charCodeAt","toByteArray","b64","l","tmp","placeHolders","L","tripletToBase64","num","encodeChunk","uint8","start","end","output","join","fromByteArray","extraBytes","parts","maxChunkLength","len2","read","buffer","offset","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","d","s","NaN","pow","write","value","c","rt","abs","LN2","isArray","INSPECT_MAX_BYTES","Buffer","TYPED_ARRAY_SUPPORT","kMaxLength","createBuffer","__proto__","arg","encodingOrOffset","allocUnsafe","from","poolSize","_augment","fromArrayBuffer","fromString","fromObject","assertSize","size","alloc","encoding","checked","allocUnsafeSlow","string","isEncoding","byteLength","actual","slice","fromArrayLike","byteOffset","obj","internalIsBuffer","isnan","data","isBuffer","b","_isBuffer","compare","a","x","y","String","toLowerCase","pos","buf","isView","loweredCase","utf8ToBytes","base64ToBytes","slowToString","hexSlice","utf8Slice","asciiSlice","latin1Slice","base64Slice","utf16leSlice","swap","swap16","swap32","swap64","equals","inspect","str","match","thisStart","thisEnd","thisCopy","targetCopy","bidirectionalIndexOf","val","arrayIndexOf","indexOf","lastIndexOf","indexSize","arrLength","valLength","readUInt16BE","foundIndex","found","includes","hexWrite","Number","remaining","strLen","parsed","parseInt","substr","utf8Write","blitBuffer","asciiWrite","asciiToBytes","latin1Write","base64Write","ucs2Write","utf16leToBytes","isFinite","toJSON","_arr","base64","res","firstByte","codePoint","bytesPerSequence","secondByte","thirdByte","fourthByte","tempCodePoint","decodeCodePointsArray","MAX_ARGUMENTS_LENGTH","codePoints","fromCharCode","out","toHex","bytes","newBuf","subarray","sliceLen","checkOffset","ext","readUIntLE","noAssert","mul","readUIntBE","readUInt8","readUInt16LE","readUInt32LE","readUInt32BE","readIntLE","readIntBE","readInt8","readInt16LE","readInt16BE","readInt32LE","readInt32BE","readFloatLE","ieee754","readFloatBE","readDoubleLE","readDoubleBE","checkInt","writeUIntLE","maxBytes","writeUIntBE","writeUInt8","objectWriteUInt16","littleEndian","writeUInt16LE","writeUInt16BE","objectWriteUInt32","writeUInt32LE","writeUInt32BE","writeIntLE","limit","sub","writeIntBE","writeInt8","writeInt16LE","writeInt16BE","writeInt32LE","writeInt32BE","checkIEEE754","writeFloat","writeFloatLE","writeFloatBE","writeDouble","writeDoubleLE","writeDoubleBE","targetStart","INVALID_BASE64_RE","base64clean","stringtrim","replace","trim","units","leadSurrogate","byteArray","hi","lo","src","dst","isFastBuffer","isSlowBuffer","constructor","inherits","ctor","superCtor","super_","enumerable","writable","configurable","TempCtor","formatRegExp","format","f","isString","objects","JSON","stringify","_","isNull","isObject","deprecate","fn","msg","isUndefined","process","deprecated","debugs","debugEnviron","debuglog","toUpperCase","RegExp","test","pid","opts","ctx","seen","stylize","stylizeNoColor","depth","colors","isBoolean","showHidden","_extend","customInspect","stylizeWithColor","formatValue","styles","styleType","style","arrayToHash","hash","idx","recurseTimes","isFunction","primitive","formatPrimitive","visibleKeys","isError","formatError","isDate","base","braces","toUTCString","formatArray","map","formatProperty","reduceToSingleString","simple","isNumber","hasOwnProperty","desc","split","line","reduce","prev","cur","numLinesEst","ar","isNullOrUndefined","isSymbol","re","objectToString","isPrimitive","maybeBuf","Buffer.isBuffer","o","pad","months","timestamp","time","getHours","getMinutes","getSeconds","getDate","getMonth","origin","add","prop","BufferList","head","tail","v","entry","next","shift","clear","p","isBufferEncoding","assertEncoding","StringDecoder","surrogateSize","detectIncompleteChar","utf16DetectIncompleteChar","base64DetectIncompleteChar","passThroughWrite","charBuffer","charReceived","charLength","charStr","available","charCode","substring","cr","enc","Readable","ReadableState","debug","event","options","stream","objectMode","Duplex","readableObjectMode","hwm","highWaterMark","defaultHwm","pipes","pipesCount","flowing","ended","endEmitted","reading","sync","needReadable","emittedReadable","readableListening","resumeScheduled","defaultEncoding","ranOut","awaitDrain","readingMore","decoder","_readableState","readable","_read","chunk","state","readableAddChunk","isPaused","addToFront","chunkInvalid","onEofChunk","_e","skipAdd","emitReadable","maybeReadMore","needMoreData","setEncoding","MAX_HWM","computeNewHighWaterMark","howMuchToRead","nOrig","endReadable","doRead","fromList","emitReadable_","flow","maybeReadMore_","pipe","dest","pipeOpts","doEnd","endFn","onend","cleanup","onunpipe","ondrain","pipeOnDrain","cleanedUp","onclose","onfinish","onerror","ondata","_writableState","needDrain","increasedAwaitDrain","pause","unpipe","resume","dests","_i","splice","ev","nReadingNextTick","resume_","wrap","paused","method","_fromList","fromListPartial","hasStrings","copyFromBufferString","copyFromBuffer","nb","endReadableNT","xs","Writable","WritableState","nop","WriteReq","cb","callback","getBuffer","writableObjectMode","ending","finished","noDecode","decodeStrings","writing","corked","bufferProcessing","onwrite","writecb","writelen","bufferedRequest","lastBufferedRequest","pendingcb","prefinished","errorEmitted","bufferedRequestCount","corkedRequestsFree","CorkedRequest","writableStateGetBuffer","current","_write","writev","_writev","writeAfterEnd","validChunk","valid","writeOrBuffer","cork","uncork","clearBuffer","setDefaultEncoding","decodeChunk","last","doWrite","onwriteError","onwriteStateUpdate","needFinish","afterWrite","onwriteDrain","finishMaybe","holder","finish","endWritable","prefinish","need","_this","allowHalfOpen","onEndNT","Transform","TransformState","afterTransform","needTransform","transforming","writechunk","writeencoding","ts","_transformState","rs","transform","_transform","flush","_flush","done","ws","PassThrough","Stream","EE","source","_isStdio","didOnEnd","destroy","WritableStream","BrowserStdout","label","chunks","process.nextTick","parseQuery","qs","pair","decodeURIComponent","highlight","js","highlightTags","getElementById","getElementsByTagName","innerHTML","location","IS_NODE","IS_IOS","Promise","IS_WEBOS_WEBKIT","task","NativePromise","newPromiseCapability","newPromiseCapabilityModule","notify","charAt","ArrayIteratorMethods","COLLECTION_NAME","Collection","CollectionPrototype","runtime","exports","Op","hasOwn","$Symbol","iteratorSymbol","iterator","asyncIteratorSymbol","asyncIterator","toStringTagSymbol","toStringTag","define","innerFn","outerFn","tryLocsList","protoGenerator","Generator","generator","Context","_invoke","makeInvokeMethod","tryCatch","GenStateSuspendedStart","GenStateSuspendedYield","GenStateExecuting","GenStateCompleted","ContinueSentinel","GeneratorFunction","GeneratorFunctionPrototype","getProto","NativeIteratorPrototype","values","Gp","displayName","defineIteratorMethods","isGeneratorFunction","genFun","mark","awrap","__await","AsyncIterator","PromiseImpl","invoke","resolve","reject","record","result","then","unwrapped","previousPromise","enqueue","callInvokeWithMethodAndArg","async","iter","doneResult","delegate","delegateResult","maybeInvokeDelegate","sent","_sent","dispatchException","abrupt","info","resultName","nextLoc","pushTryEntry","locs","tryLoc","catchLoc","finallyLoc","afterLoc","tryEntries","resetTryEntry","completion","reset","object","reverse","iterable","iteratorMethod","skipTempReset","stop","rootEntry","rootRecord","rval","exception","handle","loc","caught","hasCatch","hasFinally","finallyEntry","complete","thrown","delegateYield","module","regeneratorRuntime","accidentalStrictMode","Function","normalizeArray","allowAboveRoot","up","splitPathRe","splitPath","filename","resolvedPath","resolvedAbsolute","path","filter","normalize","isPathAbsolute","isAbsolute","trailingSlash","paths","relative","to","fromParts","toParts","samePartsLength","outputParts","sep","delimiter","dirname","root","basename","extname","INCORRECT_ITERATION","factory","this","Diff","diff","oldString","newString","castInput","removeEmpty","tokenize","newLen","oldLen","editLength","maxEditLength","bestPath","newPos","components","oldPos","extractCommon","execEditLength","diagonalPath","basePath","addPath","removePath","_oldPos","canAdd","canRemove","clonePath","pushComponent","buildValues","useLongestToken","added","removed","commonCount","left","right","comparator","ignoreCase","chars","componentPos","componentLen","component","oldValue","lastComponent","characterDiff","diffChars","oldStr","newStr","generateOptions","defaults","extendedWordChars","reWhitespace","wordDiff","ignoreWhitespace","tokens","diffWords","diffWordsWithSpace","lineDiff","retLines","linesAndNewlines","newlineIsToken","diffLines","diffTrimmedLines","sentenceDiff","diffSentences","cssDiff","diffCss","_typeof","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_arrayLikeToArray","minLen","arr2","objectPrototypeToString","jsonDiff","_this$options","undefinedReplacement","_this$options$stringi","stringifyReplacer","canonicalize","diffJson","oldObj","newObj","stack","replacementStack","replacer","canonicalizedObj","sortedKeys","_key","sort","arrayDiff","diffArrays","oldArr","newArr","parsePatch","uniDiff","diffstr","delimiters","parseIndex","header","parseFileHeader","hunks","_line","parseHunk","strict","fileHeader","keyPrefix","fileName","chunkHeaderIndex","chunkHeaderLine","chunkHeader","hunk","oldStart","oldLines","newStart","newLines","lines","linedelimiters","addCount","removeCount","operation","distanceIterator","minLine","maxLine","wantForward","backwardExhausted","forwardExhausted","localOffset","applyPatch","compareLine","lineNumber","patchContent","errorCount","fuzzFactor","removeEOFNL","addEOFNL","hunkFits","toPos","content","diffOffset","_hunk","_toPos","previousOperation","_k","applyPatches","currentIndex","processIndex","loadFile","updatedContent","patched","structuredPatch","oldFileName","newFileName","oldHeader","newHeader","contextLines","oldRangeStart","newRangeStart","curRange","oldLine","newLine","_loop","_curRange","_curRange2","_curRange3","contextSize","oldEOFNewline","newEOFNewline","noNlBeforeAdds","formatPatch","createTwoFilesPatch","createPatch","arrayEqual","arrayStartsWith","calcLineCount","_calcOldNewLineCount","calcOldNewLineCount","merge","mine","theirs","loadPatch","fileNameChanged","selectField","mineIndex","theirsIndex","mineOffset","theirsOffset","mineCurrent","theirsCurrent","hunkBefore","cloneHunk","mergedHunk","mergeLines","param","patch","conflict","check","mineLines","theirOffset","theirLines","their","insertLeading","theirCurrent","mutualChange","_hunk$lines","collectChange","_hunk$lines2","removal","insertTrailing","myChanges","theirChanges","allRemoves","skipRemoveSuperset","_hunk$lines3","_hunk$lines4","_hunk$lines5","collectContext","merged","_hunk$lines6","insert","matchChanges","changes","matchIndex","contextChanges","conflicted","change","removeChanges","delta","changeContent","myCount","theirCount","convertChangesToDMP","convertChangesToXML","escapeHTML","h","parse","fmtLong","fmtShort","parseFloat","ms","msAbs","round","plural","isPlural","FREEZING","InternalMetadataModule","urlAlphabet","customAlphabet","alphabet","id","random","nanoid","freeExports","freeModule","freeGlobal","regexAstralSymbols","regexAsciiWhitelist","regexBmpWhitelist","regexEncodeNonAscii","encodeMap","regexEscape","escapeMap","regexInvalidEntity","regexInvalidRawCodePoint","regexDecode","decodeMap","decodeMapLegacy","decodeMapNumeric","invalidReferenceCodePoints","stringFromCharCode","propertyName","contains","codePointToSymbol","parseError","hexEscape","decEscape","message","encode","encodeEverything","useNamedReferences","allowUnsafeSymbols","escapeCodePoint","decimal","escapeBmpSymbol","symbol","$0","high","low","decode","html","$1","$2","$3","$4","$5","$6","$7","$8","semicolon","decDigits","hexDigits","reference","isAttributeValue","escape","he","nodeType","cache","constants","FATAL","INVALID_ARG_TYPE","INVALID_ARG_VALUE","INVALID_EXCEPTION","INVALID_INTERFACE","INVALID_REPORTER","MULTIPLE_DONE","NO_FILES_MATCH_PATTERN","UNSUPPORTED","INSTANCE_ALREADY_RUNNING","INSTANCE_ALREADY_DISPOSED","FORBIDDEN_EXCLUSIVITY","INVALID_PLUGIN_IMPLEMENTATION","INVALID_PLUGIN_DEFINITION","TIMEOUT","UNPARSABLE_FILE","MOCHA_ERRORS","Set","createNoFilesMatchPatternError","pattern","createInvalidReporterError","reporter","createInvalidInterfaceError","ui","createUnsupportedError","createMissingArgumentError","argument","expected","createInvalidArgumentTypeError","createInvalidArgumentValueError","reason","createInvalidExceptionError","valueType","createFatalError","createInvalidLegacyPluginError","pluginType","pluginId","createInvalidPluginError","createMochaInstanceAlreadyDisposedError","cleanReferencesAfterRun","instance","createMochaInstanceAlreadyRunningError","createMultipleDoneError","runnable","originalErr","fullTitle","parent","ignored","file","createForbiddenExclusivityError","mocha","isWorker","createInvalidPluginDefinitionError","pluginDef","createInvalidPluginImplementationError","pluginImpl","createTimeoutError","createUnparsableFileError","isMochaError","Boolean","MOCHA_ID_PROP_NAME","util","spaces","tabs","emptyRepresentation","typeHint","canonicalType","primitives","_type","json","jsonStringify","acc","char","_stringify","space","repeat","sDate","toISOString","withStack","item","is","node","slash","href","isMochaInternal","isNodeInternal","isPromise","clamp","range","freeze","createMap","partialSupport","isBrowser","versionFields","major","minor","process.browser","errors","lookupFiles","castArray","defineConstants","uniqueID","Pending","setup","createDebug","coerce","disable","enable","enabled","humanize","names","skips","formatters","selectColor","namespace","prevTime","enableOverride","curr","formatter","formatArgs","logFn","useColors","color","extend","newDebug","namespaces","save","toNamespace","regexp","load","localstorage","__nwjs","navigator","documentElement","WebkitAppearance","firebug","table","lastC","storage","setItem","removeItem","r","getItem","DEBUG","localStorage","Runnable","body","_timeout","_slow","_retries","utils","assignNewMochaID","getMochaID","timedOut","_currentRetry","pending","milliseconds","INT_MAX","timer","resetTimeout","slow","skip","isPending","isFailed","STATE_FAILED","isPassed","STATE_PASSED","retries","currentRetry","titlePath","_timeoutError","globals","_allowedGlobals","errorWasHandled","multiple","duration","asyncSkip","callFnAsync","allowUncaught","toValueOrError","callFn","asyncOnly","STATE_PENDING","Hook","_error","serialize","$$isPending","$$titlePath","currentTest","utilsConstants","Suite","suite","addSuite","parentContext","isRoot","suites","tests","_beforeEach","_beforeAll","_afterEach","_afterAll","_bail","_onlyTests","_onlySuites","deprecatedEvents","delayed","doReset","thingToReset","clone","bail","_createHook","hook","beforeAll","EVENT_SUITE_ADD_HOOK_BEFORE_ALL","afterAll","EVENT_SUITE_ADD_HOOK_AFTER_ALL","beforeEach","EVENT_SUITE_ADD_HOOK_BEFORE_EACH","afterEach","EVENT_SUITE_ADD_HOOK_AFTER_EACH","EVENT_SUITE_ADD_SUITE","addTest","EVENT_SUITE_ADD_TEST","total","sum","eachTest","EVENT_ROOT_SUITE_RUN","hasOnly","some","filterOnly","onlySuite","onlySuites","childSuite","appendOnlySuite","markOnly","appendOnlyTest","getHooks","dispose","cleanReferences","cleanArrReferences","$$fullTitle","EVENT_FILE_POST_REQUIRE","EVENT_FILE_PRE_REQUIRE","EVENT_FILE_REQUIRE","HOOK_TYPE_AFTER_ALL","HOOK_TYPE_AFTER_EACH","HOOK_TYPE_BEFORE_ALL","HOOK_TYPE_BEFORE_EACH","constant","dQuote","sQuote","stackFilter","stackTraceFilter","errorConstants","EVENT_HOOK_BEGIN","EVENT_HOOK_END","EVENT_RUN_BEGIN","EVENT_DELAY_BEGIN","EVENT_DELAY_END","EVENT_RUN_END","EVENT_SUITE_BEGIN","EVENT_SUITE_END","EVENT_TEST_BEGIN","EVENT_TEST_END","EVENT_TEST_FAIL","EVENT_TEST_PASS","EVENT_TEST_PENDING","EVENT_TEST_RETRY","STATE_IDLE","STATE_RUNNING","STATE_STOPPED","Runner","_delay","delay","_globals","_abort","_opts","failures","_eventListeners","Map","retriedTest","checkGlobals","_defaultGrep","grep","globalProps","uncaught","_uncaught","unhandled","promise","_removeEventListener","_addEventListener","immediately","setImmediate","eventName","targetListeners","targetEventListeners","invert","_grep","_invert","grepTotal","props","checkLeaks","ok","leaks","prevGlobalsLength","filterLeaks","fail","force","thrown2Error","fullStackTrace","ignore","hooks","currentRunnable","setHookTitle","cbHookRun","testError","errForbid","originalTitle","parentTitle","orig","errSuite","hookUp","parents","hookDown","runTest","runTests","hookErr","after","err2","errSuite2","forbidPending","origSuite","eSuite","retry","clonedTest","runSuite","nextSuite","abort","rootSuite","begin","prepare","linkPartialObjects","runAsync","isParallelMode","workerReporter","matched","getBrowserWindowSize","innerHeight","innerWidth","Base","isatty","stdout","isTTY","stderr","consoleLog","supportsColor","MOCHA_COLORS","pass","checkmark","fast","medium","green","light","dot","comma","bang","symbols","width","getWindowSize","hide","show","deleteLine","beginningOfLine","CR","cursor","showDiff","sameType","stringifyDiffObjs","generateDiff","inlineDiffs","inlineDiff","unifiedDiff","multipleErr","multipleTest","fmt","hideDiff","testTitle","runner","stats","speed","epilogue","passes","errorDiff","indent","cleanUp","colorLines","notBlank","objToString","Dot","description","Doc","indents","clean","sprintf","TAP","tapVersion","reporterOptions","_producer","createProducer","writeVersion","writePending","writePass","writeFail","writeEpilogue","println","varArgs","vargs","producers","TAP12Producer","TAP13Producer","producer","TAPProducer","writePlan","ntests","emitYamlBlock","level","JSONReporter","testResults","errorJSON","cleanCycles","Progress","percent","fontSize","font","_size","text","_text","_fontSize","family","_font","update","draw","half","rad","angle","PI","clearRect","strokeStyle","beginPath","arc","stroke","measureText","fillText","HTML","statsTemplate","playIcon","stat","fragment","items","passesLink","failuresLink","canvas","report","progress","getContext","ratio","devicePixelRatio","height","scale","evt","preventDefault","unhide","className","hideSuitesWithout","appendChild","url","suiteURL","el","updateStats","testURL","markup","addCodeToggle","appendToStack","stackString","indexOfMessage","sourceURL","htmlMessage","toFixed","makeUrl","search","pathname","encodeURIComponent","escapeRe","contents","h2","pre","display","div","firstChild","classname","getElementsByClassName","els","textContent","innerText","addEventListener","attachEvent","browserOnly","List","Min","Spec","NyanCat","nyanCatWidth","colorIndex","numberOfLines","rainbowColors","generateColors","scoreboardWidth","tick","trajectories","trajectoryWidthMax","appendRainbow","drawScoreboard","drawRainbow","drawNyanCat","cursorUp","segment","rainbowified","rainbowify","trajectory","startWidth","dist","padding","face","cursorDown","pi3","sin","XUnit","suiteName","DEFAULT_SUITE_NAME","fs","createWriteStream","mkdirSync","recursive","fileStream","tag","skipped","t","attrs","close","pairs","SUITE_PREFIX","Markdown","mapTOC","stringifyTOC","link","slug","generateTOC","lastN","open","incomplete","verbose","Landing","plane","runway","crashed","col","kill","JSONStream","writeEvent","require$$4","require$$5","require$$6","require$$7","require$$8","require$$9","require$$10","require$$11","require$$12","require$$13","require$$14","hasNotificationSupport","hasPromiseSupport","isPermitted","sendNotification","race","canNotify","notPermitted","permitted","granted","allow","denied","deny","ask","Notification","requestPermission","permission","why","cross","logo","notifyLogo","_message","badge","icon","lang","requireInteraction","notification","FORCE_DURATION","createStatsCollector","Test","_retriedTest","$$currentRetry","$$retriedTest","$$slow","shouldBeTested","runWithSuite","before","only","forbidOnly","isOnly","bddInterface","common","describe","xdescribe","xcontext","it","specify","xit","xspecify","teardown","suiteSetup","suiteTeardown","qUnitInterface","visit","_runnable","esmUtils","supportsEsModules","Mocha","mochaStates","INIT","RUNNING","REFERENCES_CLEANED","DISPOSED","builtinReporters","currentContext","mocharc","files","_cleanReferencesAfterRun","_state","fgrep","reporterOption","opt","rootHooks","_runnerClass","_lazyLoadFiles","globalSetup","globalTeardown","enableGlobalSetup","enableGlobalTeardown","parallel","jobs","parallelMode","addFile","reporterName","_reporter","require","_err","bindInterface","interfaces","loadFiles","loadFilesAsync","lazyLoadFiles","resultModule","unloadFile","unloadFiles","_previousRunner","fullTrace","growl","isGrowlCapable","detail","isCapable","_growl","elt","msecs","noHighlighting","_guardRunningStateTransition","reporters","hasGlobalSetupFixtures","runGlobalSetup","failureCount","hasGlobalTeardownFixtures","runGlobalTeardown","setupFns","teardownFns","_runGlobalFixtures","fixtureFns","fixtureFn","uncaughtExceptionHandlers","originalOnerrorHandler","immediateQueue","immediateTimeout","timeslice","immediateStart","throwError","query"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;CAAA,IAAI,KAAK,GAAG,UAAU,EAAE,EAAE;CAC1B,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;CACrC,CAAC,CAAC;AACF;CACA;CACA,YAAc;CACd;CACA,EAAE,KAAK,CAAC,OAAO,UAAU,IAAI,QAAQ,IAAI,UAAU,CAAC;CACpD,EAAE,KAAK,CAAC,OAAO,MAAM,IAAI,QAAQ,IAAI,MAAM,CAAC;CAC5C,EAAE,KAAK,CAAC,OAAO,IAAI,IAAI,QAAQ,IAAI,IAAI,CAAC;CACxC,EAAE,KAAK,CAAC,OAAOA,cAAM,IAAI,QAAQ,IAAIA,cAAM,CAAC;CAC5C;CACA,EAAE,CAAC,YAAY,EAAE,OAAO,IAAI,CAAC,EAAE,GAAG,IAAI,QAAQ,CAAC,aAAa,CAAC,EAAE;;CCZ/D,SAAc,GAAG,UAAU,IAAI,EAAE;CACjC,EAAE,IAAI;CACN,IAAI,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;CACpB,GAAG,CAAC,OAAO,KAAK,EAAE;CAClB,IAAI,OAAO,IAAI,CAAC;CAChB,GAAG;CACH,CAAC;;CCJD;CACA,eAAc,GAAG,CAAC,KAAK,CAAC,YAAY;CACpC,EAAE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,cAAT,CAAwB,OAAxB,CADA,IAEAnL,OAAO,CAACoyC,cAAR,KAA2B,IAH7B,EAIE;CACAlnC,MAAAA,aAAa,CAAC,MAAD,CAAb;CACD;;CACD,QAAI7R,EAAJ,EAAQ;CACNA,MAAAA,EAAE,CAACnW,GAAD,CAAF;CACD;CACF,GAbM,CAAP;CAcD,CA7BD;;;;;;;AAoCAmsD,MAAK,CAAC71C,OAAN,GAAgBA,SAAhB;;;;;AAMArhB,eAAAA,CAAOk3D,KAAPl3D,GAAek3D,KAAfl3D;AACAA,eAAAA,CAAOwyC,KAAPxyC,GAAewyC,OAAfxyC;;;;iBAKc,GAAGyI,MAAM,CAAClG,MAAP,CAAciwC,OAAd,EAAqBxyC,cAArB;;;;;;;;"} \ No newline at end of file +{"version":3,"file":"mocha.js","sources":["node_modules/rollup-plugin-node-globals/src/global.js","node_modules/process-es6/browser.js","node_modules/browser-stdout/index.js","lib/browser/parse-query.js","lib/browser/highlight-tags.js","node_modules/escape-string-regexp/index.js","node_modules/diff/lib/diff/base.js","node_modules/diff/lib/diff/character.js","node_modules/diff/lib/util/params.js","node_modules/diff/lib/diff/word.js","node_modules/diff/lib/diff/line.js","node_modules/diff/lib/diff/sentence.js","node_modules/diff/lib/diff/css.js","node_modules/diff/lib/diff/json.js","node_modules/diff/lib/diff/array.js","node_modules/diff/lib/patch/parse.js","node_modules/diff/lib/util/distance-iterator.js","node_modules/diff/lib/patch/apply.js","node_modules/diff/lib/patch/create.js","node_modules/diff/lib/util/array.js","node_modules/diff/lib/patch/merge.js","node_modules/diff/lib/convert/dmp.js","node_modules/diff/lib/convert/xml.js","node_modules/diff/lib/index.js","node_modules/ms/index.js","node_modules/buffer-es6/base64.js","node_modules/buffer-es6/ieee754.js","node_modules/buffer-es6/isArray.js","node_modules/buffer-es6/index.js","node_modules/rollup-plugin-node-globals/src/browser.js","node_modules/he/he.js","lib/utils.js","node_modules/log-symbols/browser.js","lib/pending.js","node_modules/debug/node_modules/ms/index.js","node_modules/debug/src/common.js","node_modules/debug/src/browser.js","lib/errors.js","lib/runnable.js","lib/hook.js","lib/suite.js","lib/runner.js","lib/reporters/base.js","lib/reporters/dot.js","lib/reporters/doc.js","lib/reporters/tap.js","lib/reporters/json.js","lib/browser/progress.js","lib/reporters/html.js","lib/reporters/list.js","lib/reporters/min.js","lib/reporters/spec.js","lib/reporters/nyan.js","lib/reporters/xunit.js","lib/reporters/markdown.js","lib/reporters/progress.js","lib/reporters/landing.js","lib/reporters/json-stream.js","lib/reporters/index.js","lib/stats-collector.js","lib/test.js","lib/interfaces/common.js","lib/interfaces/bdd.js","lib/interfaces/tdd.js","lib/interfaces/qunit.js","lib/interfaces/exports.js","lib/interfaces/index.js","lib/context.js","lib/mocha.js","browser-entry.js"],"sourcesContent":["export default (typeof global !== \"undefined\" ? global :\n typeof self !== \"undefined\" ? self :\n typeof window !== \"undefined\" ? window : {});\n","// shim for using process in browser\n// based off https://github.com/defunctzombie/node-process/blob/master/browser.js\n\nfunction defaultSetTimout() {\n throw new Error('setTimeout has not been defined');\n}\nfunction defaultClearTimeout () {\n throw new Error('clearTimeout has not been defined');\n}\nvar cachedSetTimeout = defaultSetTimout;\nvar cachedClearTimeout = defaultClearTimeout;\nif (typeof global.setTimeout === 'function') {\n cachedSetTimeout = setTimeout;\n}\nif (typeof global.clearTimeout === 'function') {\n cachedClearTimeout = clearTimeout;\n}\n\nfunction runTimeout(fun) {\n if (cachedSetTimeout === setTimeout) {\n //normal enviroments in sane situations\n return setTimeout(fun, 0);\n }\n // if setTimeout wasn't available but was latter defined\n if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {\n cachedSetTimeout = setTimeout;\n return setTimeout(fun, 0);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedSetTimeout(fun, 0);\n } catch(e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedSetTimeout.call(null, fun, 0);\n } catch(e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error\n return cachedSetTimeout.call(this, fun, 0);\n }\n }\n\n\n}\nfunction runClearTimeout(marker) {\n if (cachedClearTimeout === clearTimeout) {\n //normal enviroments in sane situations\n return clearTimeout(marker);\n }\n // if clearTimeout wasn't available but was latter defined\n if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {\n cachedClearTimeout = clearTimeout;\n return clearTimeout(marker);\n }\n try {\n // when when somebody has screwed with setTimeout but no I.E. maddness\n return cachedClearTimeout(marker);\n } catch (e){\n try {\n // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally\n return cachedClearTimeout.call(null, marker);\n } catch (e){\n // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.\n // Some versions of I.E. have different rules for clearTimeout vs setTimeout\n return cachedClearTimeout.call(this, marker);\n }\n }\n\n\n\n}\nvar queue = [];\nvar draining = false;\nvar currentQueue;\nvar queueIndex = -1;\n\nfunction cleanUpNextTick() {\n if (!draining || !currentQueue) {\n return;\n }\n draining = false;\n if (currentQueue.length) {\n queue = currentQueue.concat(queue);\n } else {\n queueIndex = -1;\n }\n if (queue.length) {\n drainQueue();\n }\n}\n\nfunction drainQueue() {\n if (draining) {\n return;\n }\n var timeout = runTimeout(cleanUpNextTick);\n draining = true;\n\n var len = queue.length;\n while(len) {\n currentQueue = queue;\n queue = [];\n while (++queueIndex < len) {\n if (currentQueue) {\n currentQueue[queueIndex].run();\n }\n }\n queueIndex = -1;\n len = queue.length;\n }\n currentQueue = null;\n draining = false;\n runClearTimeout(timeout);\n}\nexport function nextTick(fun) {\n var args = new Array(arguments.length - 1);\n if (arguments.length > 1) {\n for (var i = 1; i < arguments.length; i++) {\n args[i - 1] = arguments[i];\n }\n }\n queue.push(new Item(fun, args));\n if (queue.length === 1 && !draining) {\n runTimeout(drainQueue);\n }\n}\n// v8 likes predictible objects\nfunction Item(fun, array) {\n this.fun = fun;\n this.array = array;\n}\nItem.prototype.run = function () {\n this.fun.apply(null, this.array);\n};\nexport var title = 'browser';\nexport var platform = 'browser';\nexport var browser = true;\nexport var env = {};\nexport var argv = [];\nexport var version = ''; // empty string to avoid regexp issues\nexport var versions = {};\nexport var release = {};\nexport var config = {};\n\nfunction noop() {}\n\nexport var on = noop;\nexport var addListener = noop;\nexport var once = noop;\nexport var off = noop;\nexport var removeListener = noop;\nexport var removeAllListeners = noop;\nexport var emit = noop;\n\nexport function binding(name) {\n throw new Error('process.binding is not supported');\n}\n\nexport function cwd () { return '/' }\nexport function chdir (dir) {\n throw new Error('process.chdir is not supported');\n};\nexport function umask() { return 0; }\n\n// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js\nvar performance = global.performance || {}\nvar performanceNow =\n performance.now ||\n performance.mozNow ||\n performance.msNow ||\n performance.oNow ||\n performance.webkitNow ||\n function(){ return (new Date()).getTime() }\n\n// generate timestamp or delta\n// see http://nodejs.org/api/process.html#process_process_hrtime\nexport function hrtime(previousTimestamp){\n var clocktime = performanceNow.call(performance)*1e-3\n var seconds = Math.floor(clocktime)\n var nanoseconds = Math.floor((clocktime%1)*1e9)\n if (previousTimestamp) {\n seconds = seconds - previousTimestamp[0]\n nanoseconds = nanoseconds - previousTimestamp[1]\n if (nanoseconds<0) {\n seconds--\n nanoseconds += 1e9\n }\n }\n return [seconds,nanoseconds]\n}\n\nvar startTime = new Date();\nexport function uptime() {\n var currentTime = new Date();\n var dif = currentTime - startTime;\n return dif / 1000;\n}\n\nexport default {\n nextTick: nextTick,\n title: title,\n browser: browser,\n env: env,\n argv: argv,\n version: version,\n versions: versions,\n on: on,\n addListener: addListener,\n once: once,\n off: off,\n removeListener: removeListener,\n removeAllListeners: removeAllListeners,\n emit: emit,\n binding: binding,\n cwd: cwd,\n chdir: chdir,\n umask: umask,\n hrtime: hrtime,\n platform: platform,\n release: release,\n config: config,\n uptime: uptime\n};\n","var WritableStream = require('stream').Writable\nvar inherits = require('util').inherits\n\nmodule.exports = BrowserStdout\n\n\ninherits(BrowserStdout, WritableStream)\n\nfunction BrowserStdout(opts) {\n if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)\n\n opts = opts || {}\n WritableStream.call(this, opts)\n this.label = (opts.label !== undefined) ? opts.label : 'stdout'\n}\n\nBrowserStdout.prototype._write = function(chunks, encoding, cb) {\n var output = chunks.toString ? chunks.toString() : chunks\n if (this.label === false) {\n console.log(output)\n } else {\n console.log(this.label+':', output)\n }\n process.nextTick(cb)\n}\n","'use strict';\n\n/**\n * Parse the given `qs`.\n *\n * @private\n * @param {string} qs\n * @return {Object}\n */\nmodule.exports = function parseQuery(qs) {\n return qs\n .replace('?', '')\n .split('&')\n .reduce(function (obj, pair) {\n var i = pair.indexOf('=');\n var key = pair.slice(0, i);\n var val = pair.slice(++i);\n\n // Due to how the URLSearchParams API treats spaces\n obj[key] = decodeURIComponent(val.replace(/\\+/g, '%20'));\n\n return obj;\n }, {});\n};\n","'use strict';\n\n/**\n * Highlight the given string of `js`.\n *\n * @private\n * @param {string} js\n * @return {string}\n */\nfunction highlight(js) {\n return js\n .replace(//g, '>')\n .replace(/\\/\\/(.*)/gm, '//$1')\n .replace(/('.*?')/gm, '$1')\n .replace(/(\\d+\\.\\d+)/gm, '$1')\n .replace(/(\\d+)/gm, '$1')\n .replace(\n /\\bnew[ \\t]+(\\w+)/gm,\n 'new $1'\n )\n .replace(\n /\\b(function|new|throw|return|var|if|else)\\b/gm,\n '$1'\n );\n}\n\n/**\n * Highlight the contents of tag `name`.\n *\n * @private\n * @param {string} name\n */\nmodule.exports = function highlightTags(name) {\n var code = document.getElementById('mocha').getElementsByTagName(name);\n for (var i = 0, len = code.length; i < len; ++i) {\n code[i].innerHTML = highlight(code[i].innerHTML);\n }\n};\n","'use strict';\n\nmodule.exports = string => {\n\tif (typeof string !== 'string') {\n\t\tthrow new TypeError('Expected a string');\n\t}\n\n\t// Escape characters with special meaning either inside or outside character sets.\n\t// Use a simple backslash escape when it’s always valid, and a \\unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar.\n\treturn string\n\t\t.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&')\n\t\t.replace(/-/g, '\\\\x2d');\n};\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = Diff;\n\n/*istanbul ignore end*/\nfunction Diff() {}\n\nDiff.prototype = {\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n diff: function diff(oldString, newString) {\n /*istanbul ignore start*/\n var\n /*istanbul ignore end*/\n options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var callback = options.callback;\n\n if (typeof options === 'function') {\n callback = options;\n options = {};\n }\n\n this.options = options;\n var self = this;\n\n function done(value) {\n if (callback) {\n setTimeout(function () {\n callback(undefined, value);\n }, 0);\n return true;\n } else {\n return value;\n }\n } // Allow subclasses to massage the input prior to running\n\n\n oldString = this.castInput(oldString);\n newString = this.castInput(newString);\n oldString = this.removeEmpty(this.tokenize(oldString));\n newString = this.removeEmpty(this.tokenize(newString));\n var newLen = newString.length,\n oldLen = oldString.length;\n var editLength = 1;\n var maxEditLength = newLen + oldLen;\n var bestPath = [{\n newPos: -1,\n components: []\n }]; // Seed editLength = 0, i.e. the content starts with the same values\n\n var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);\n\n if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {\n // Identity per the equality and tokenizer\n return done([{\n value: this.join(newString),\n count: newString.length\n }]);\n } // Main worker method. checks all permutations of a given edit length for acceptance.\n\n\n function execEditLength() {\n for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {\n var basePath =\n /*istanbul ignore start*/\n void 0\n /*istanbul ignore end*/\n ;\n\n var addPath = bestPath[diagonalPath - 1],\n removePath = bestPath[diagonalPath + 1],\n _oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;\n\n if (addPath) {\n // No one else is going to attempt to use this value, clear it\n bestPath[diagonalPath - 1] = undefined;\n }\n\n var canAdd = addPath && addPath.newPos + 1 < newLen,\n canRemove = removePath && 0 <= _oldPos && _oldPos < oldLen;\n\n if (!canAdd && !canRemove) {\n // If this path is a terminal then prune\n bestPath[diagonalPath] = undefined;\n continue;\n } // Select the diagonal that we want to branch from. We select the prior\n // path whose position in the new string is the farthest from the origin\n // and does not pass the bounds of the diff graph\n\n\n if (!canAdd || canRemove && addPath.newPos < removePath.newPos) {\n basePath = clonePath(removePath);\n self.pushComponent(basePath.components, undefined, true);\n } else {\n basePath = addPath; // No need to clone, we've pulled it from the list\n\n basePath.newPos++;\n self.pushComponent(basePath.components, true, undefined);\n }\n\n _oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); // If we have hit the end of both strings, then we are done\n\n if (basePath.newPos + 1 >= newLen && _oldPos + 1 >= oldLen) {\n return done(buildValues(self, basePath.components, newString, oldString, self.useLongestToken));\n } else {\n // Otherwise track this path as a potential candidate and continue.\n bestPath[diagonalPath] = basePath;\n }\n }\n\n editLength++;\n } // Performs the length of edit iteration. Is a bit fugly as this has to support the\n // sync and async mode which is never fun. Loops over execEditLength until a value\n // is produced.\n\n\n if (callback) {\n (function exec() {\n setTimeout(function () {\n // This should not happen, but we want to be safe.\n\n /* istanbul ignore next */\n if (editLength > maxEditLength) {\n return callback();\n }\n\n if (!execEditLength()) {\n exec();\n }\n }, 0);\n })();\n } else {\n while (editLength <= maxEditLength) {\n var ret = execEditLength();\n\n if (ret) {\n return ret;\n }\n }\n }\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n pushComponent: function pushComponent(components, added, removed) {\n var last = components[components.length - 1];\n\n if (last && last.added === added && last.removed === removed) {\n // We need to clone here as the component clone operation is just\n // as shallow array clone\n components[components.length - 1] = {\n count: last.count + 1,\n added: added,\n removed: removed\n };\n } else {\n components.push({\n count: 1,\n added: added,\n removed: removed\n });\n }\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n extractCommon: function extractCommon(basePath, newString, oldString, diagonalPath) {\n var newLen = newString.length,\n oldLen = oldString.length,\n newPos = basePath.newPos,\n oldPos = newPos - diagonalPath,\n commonCount = 0;\n\n while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {\n newPos++;\n oldPos++;\n commonCount++;\n }\n\n if (commonCount) {\n basePath.components.push({\n count: commonCount\n });\n }\n\n basePath.newPos = newPos;\n return oldPos;\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n equals: function equals(left, right) {\n if (this.options.comparator) {\n return this.options.comparator(left, right);\n } else {\n return left === right || this.options.ignoreCase && left.toLowerCase() === right.toLowerCase();\n }\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n removeEmpty: function removeEmpty(array) {\n var ret = [];\n\n for (var i = 0; i < array.length; i++) {\n if (array[i]) {\n ret.push(array[i]);\n }\n }\n\n return ret;\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n castInput: function castInput(value) {\n return value;\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n tokenize: function tokenize(value) {\n return value.split('');\n },\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n join: function join(chars) {\n return chars.join('');\n }\n};\n\nfunction buildValues(diff, components, newString, oldString, useLongestToken) {\n var componentPos = 0,\n componentLen = components.length,\n newPos = 0,\n oldPos = 0;\n\n for (; componentPos < componentLen; componentPos++) {\n var component = components[componentPos];\n\n if (!component.removed) {\n if (!component.added && useLongestToken) {\n var value = newString.slice(newPos, newPos + component.count);\n value = value.map(function (value, i) {\n var oldValue = oldString[oldPos + i];\n return oldValue.length > value.length ? oldValue : value;\n });\n component.value = diff.join(value);\n } else {\n component.value = diff.join(newString.slice(newPos, newPos + component.count));\n }\n\n newPos += component.count; // Common case\n\n if (!component.added) {\n oldPos += component.count;\n }\n } else {\n component.value = diff.join(oldString.slice(oldPos, oldPos + component.count));\n oldPos += component.count; // Reverse add and remove so removes are output first to match common convention\n // The diffing algorithm is tied to add then remove output and this is the simplest\n // route to get the desired output with minimal overhead.\n\n if (componentPos && components[componentPos - 1].added) {\n var tmp = components[componentPos - 1];\n components[componentPos - 1] = components[componentPos];\n components[componentPos] = tmp;\n }\n }\n } // Special case handle for when one terminal is ignored (i.e. whitespace).\n // For this case we merge the terminal into the prior string and drop the change.\n // This is only available for string mode.\n\n\n var lastComponent = components[componentLen - 1];\n\n if (componentLen > 1 && typeof lastComponent.value === 'string' && (lastComponent.added || lastComponent.removed) && diff.equals('', lastComponent.value)) {\n components[componentLen - 2].value += lastComponent.value;\n components.pop();\n }\n\n return components;\n}\n\nfunction clonePath(path) {\n return {\n newPos: path.newPos,\n components: path.components.slice(0)\n };\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Jhc2UuanMiXSwibmFtZXMiOlsiRGlmZiIsInByb3RvdHlwZSIsImRpZmYiLCJvbGRTdHJpbmciLCJuZXdTdHJpbmciLCJvcHRpb25zIiwiY2FsbGJhY2siLCJzZWxmIiwiZG9uZSIsInZhbHVlIiwic2V0VGltZW91dCIsInVuZGVmaW5lZCIsImNhc3RJbnB1dCIsInJlbW92ZUVtcHR5IiwidG9rZW5pemUiLCJuZXdMZW4iLCJsZW5ndGgiLCJvbGRMZW4iLCJlZGl0TGVuZ3RoIiwibWF4RWRpdExlbmd0aCIsImJlc3RQYXRoIiwibmV3UG9zIiwiY29tcG9uZW50cyIsIm9sZFBvcyIsImV4dHJhY3RDb21tb24iLCJqb2luIiwiY291bnQiLCJleGVjRWRpdExlbmd0aCIsImRpYWdvbmFsUGF0aCIsImJhc2VQYXRoIiwiYWRkUGF0aCIsInJlbW92ZVBhdGgiLCJjYW5BZGQiLCJjYW5SZW1vdmUiLCJjbG9uZVBhdGgiLCJwdXNoQ29tcG9uZW50IiwiYnVpbGRWYWx1ZXMi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VBhdGgocGF0aCkge1xuICByZXR1cm4geyBuZXdQb3M6IHBhdGgubmV3UG9zLCBjb21wb25lbnRzOiBwYXRoLmNvbXBvbmVudHMuc2xpY2UoMCkgfTtcbn1cbiJdfQ==\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffChars = diffChars;\nexports.characterDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nvar characterDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.characterDiff = characterDiff;\n\n/*istanbul ignore end*/\nfunction diffChars(oldStr, newStr, options) {\n return characterDiff.diff(oldStr, newStr, options);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2NoYXJhY3Rlci5qcyJdLCJuYW1lcyI6WyJjaGFyYWN0ZXJEaWZmIiwiRGlmZiIsImRpZmZDaGFycyIsIm9sZFN0ciIsIm5ld1N0ciIsIm9wdGlvbnMiLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFFTyxJQUFNQSxhQUFhLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUF0Qjs7Ozs7O0FBQ0EsU0FBU0MsU0FBVCxDQUFtQkMsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxFQUE0QztBQUFFLFNBQU9MLGFBQWEsQ0FBQ00sSUFBZCxDQUFtQkgsTUFBbkIsRUFBMkJDLE1BQTNCLEVBQW1DQyxPQUFuQyxDQUFQO0FBQXFEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNoYXJhY3RlckRpZmYgPSBuZXcgRGlmZigpO1xuZXhwb3J0IGZ1bmN0aW9uIGRpZmZDaGFycyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykgeyByZXR1cm4gY2hhcmFjdGVyRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTsgfVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.generateOptions = generateOptions;\n\n/*istanbul ignore end*/\nfunction generateOptions(options, defaults) {\n if (typeof options === 'function') {\n defaults.callback = options;\n } else if (options) {\n for (var name in options) {\n /* istanbul ignore else */\n if (options.hasOwnProperty(name)) {\n defaults[name] = options[name];\n }\n }\n }\n\n return defaults;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL3BhcmFtcy5qcyJdLCJuYW1lcyI6WyJnZW5lcmF0ZU9wdGlvbnMiLCJvcHRpb25zIiwiZGVmYXVsdHMiLCJjYWxsYmFjayIsIm5hbWUiLCJoYXNPd25Qcm9wZXJ0eSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsZUFBVCxDQUF5QkMsT0FBekIsRUFBa0NDLFFBQWxDLEVBQTRDO0FBQ2pELE1BQUksT0FBT0QsT0FBUCxLQUFtQixVQUF2QixFQUFtQztBQUNqQ0MsSUFBQUEsUUFBUSxDQUFDQyxRQUFULEdBQW9CRixPQUFwQjtBQUNELEdBRkQsTUFFTyxJQUFJQSxPQUFKLEVBQWE7QUFDbEIsU0FBSyxJQUFJRyxJQUFULElBQWlCSCxPQUFqQixFQUEwQjtBQUN4QjtBQUNBLFVBQUlBLE9BQU8sQ0FBQ0ksY0FBUixDQUF1QkQsSUFBdkIsQ0FBSixFQUFrQztBQUNoQ0YsUUFBQUEsUUFBUSxDQUFDRSxJQUFELENBQVIsR0FBaUJILE9BQU8sQ0FBQ0csSUFBRCxDQUF4QjtBQUNEO0FBQ0Y7QUFDRjs7QUFDRCxTQUFPRixRQUFQO0FBQ0QiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZnVuY3Rpb24gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIGRlZmF1bHRzKSB7XG4gIGlmICh0eXBlb2Ygb3B0aW9ucyA9PT0gJ2Z1bmN0aW9uJykge1xuICAgIGRlZmF1bHRzLmNhbGxiYWNrID0gb3B0aW9ucztcbiAgfSBlbHNlIGlmIChvcHRpb25zKSB7XG4gICAgZm9yIChsZXQgbmFtZSBpbiBvcHRpb25zKSB7XG4gICAgICAvKiBpc3RhbmJ1bCBpZ25vcmUgZWxzZSAqL1xuICAgICAgaWYgKG9wdGlvbnMuaGFzT3duUHJvcGVydHkobmFtZSkpIHtcbiAgICAgICAgZGVmYXVsdHNbbmFtZV0gPSBvcHRpb25zW25hbWVdO1xuICAgICAgfVxuICAgIH1cbiAgfVxuICByZXR1cm4gZGVmYXVsdHM7XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffWords = diffWords;\nexports.diffWordsWithSpace = diffWordsWithSpace;\nexports.wordDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_params = require(\"../util/params\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\n// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode\n//\n// Ranges and exceptions:\n// Latin-1 Supplement, 0080–00FF\n// - U+00D7 × Multiplication sign\n// - U+00F7 ÷ Division sign\n// Latin Extended-A, 0100–017F\n// Latin Extended-B, 0180–024F\n// IPA Extensions, 0250–02AF\n// Spacing Modifier Letters, 02B0–02FF\n// - U+02C7 ˇ ˇ Caron\n// - U+02D8 ˘ ˘ Breve\n// - U+02D9 ˙ ˙ Dot Above\n// - U+02DA ˚ ˚ Ring Above\n// - U+02DB ˛ ˛ Ogonek\n// - U+02DC ˜ ˜ Small Tilde\n// - U+02DD ˝ ˝ Double Acute Accent\n// Latin Extended Additional, 1E00–1EFF\nvar extendedWordChars = /^[A-Za-z\\xC0-\\u02C6\\u02C8-\\u02D7\\u02DE-\\u02FF\\u1E00-\\u1EFF]+$/;\nvar reWhitespace = /\\S/;\nvar wordDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.wordDiff = wordDiff;\n\n/*istanbul ignore end*/\nwordDiff.equals = function (left, right) {\n if (this.options.ignoreCase) {\n left = left.toLowerCase();\n right = right.toLowerCase();\n }\n\n return left === right || this.options.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right);\n};\n\nwordDiff.tokenize = function (value) {\n // All whitespace symbols except newline group into one token, each newline - in separate token\n var tokens = value.split(/([^\\S\\r\\n]+|[()[\\]{}'\"\\r\\n]|\\b)/); // Join the boundary splits that we do not consider to be boundaries. This is primarily the extended Latin character set.\n\n for (var i = 0; i < tokens.length - 1; i++) {\n // If we have an empty string in the next field and we have only word chars before and after, merge\n if (!tokens[i + 1] && tokens[i + 2] && extendedWordChars.test(tokens[i]) && extendedWordChars.test(tokens[i + 2])) {\n tokens[i] += tokens[i + 2];\n tokens.splice(i + 1, 2);\n i--;\n }\n }\n\n return tokens;\n};\n\nfunction diffWords(oldStr, newStr, options) {\n options =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _params\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n generateOptions)\n /*istanbul ignore end*/\n (options, {\n ignoreWhitespace: true\n });\n return wordDiff.diff(oldStr, newStr, options);\n}\n\nfunction diffWordsWithSpace(oldStr, newStr, options) {\n return wordDiff.diff(oldStr, newStr, options);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3dvcmQuanMiXSwibmFtZXMiOlsiZXh0ZW5kZWRXb3JkQ2hhcnMiLCJyZVdoaXRlc3BhY2UiLCJ3b3JkRGlmZiIsIkRpZmYiLCJlcXVhbHMiLCJsZWZ0IiwicmlnaHQiLCJvcHRpb25zIiwiaWdub3JlQ2FzZSIsInRvTG93ZXJDYXNlIiwiaWdub3JlV2hpdGVzcGFjZSIsInRlc3QiLCJ0b2tlbml6ZSIsInZhbHVlIiwidG9rZW5zIiwic3BsaXQiLCJpIiwibGVuZ3RoIiwic3BsaWNlIiwiZGlmZldvcmRzIiwib2xkU3RyIiwibmV3U3RyIiwiZ2VuZXJhdGVPcHRpb25zIiwiZGlmZiIsImRpZmZXb3Jkc1dpdGhTcGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7Ozs7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsSUFBTUEsaUJBQWlCLEdBQUcsK0RBQTFCO0FBRUEsSUFBTUMsWUFBWSxHQUFHLElBQXJ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WxkIGFuZCB3ZSBoYXZlIG9ubHkgd29yZCBjaGFycyBiZWZvcmUgYW5kIGFmdGVyLCBtZXJnZVxuICAgIGlmICghdG9rZW5zW2kgKyAxXSAmJiB0b2tlbnNbaSArIDJdXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaV0pXG4gICAgICAgICAgJiYgZXh0ZW5kZWRXb3JkQ2hhcnMudGVzdCh0b2tlbnNbaSArIDJdKSkge1xuICAgICAgdG9rZW5zW2ldICs9IHRva2Vuc1tpICsgMl07XG4gICAgICB0b2tlbnMuc3BsaWNlKGkgKyAxLCAyKTtcbiAgICAgIGktLTtcbiAgICB9XG4gIH1cblxuICByZXR1cm4gdG9rZW5zO1xufTtcblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3JkcyhvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICBvcHRpb25zID0gZ2VuZXJhdGVPcHRpb25zKG9wdGlvbnMsIHtpZ25vcmVXaGl0ZXNwYWNlOiB0cnVlfSk7XG4gIHJldHVybiB3b3JkRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBvcHRpb25zKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGRpZmZXb3Jkc1dpdGhTcGFjZShvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucykge1xuICByZXR1cm4gd29yZERpZmYuZGlmZihvbGRTdHIsIG5ld1N0ciwgb3B0aW9ucyk7XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffLines = diffLines;\nexports.diffTrimmedLines = diffTrimmedLines;\nexports.lineDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_params = require(\"../util/params\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nvar lineDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.lineDiff = lineDiff;\n\n/*istanbul ignore end*/\nlineDiff.tokenize = function (value) {\n var retLines = [],\n linesAndNewlines = value.split(/(\\n|\\r\\n)/); // Ignore the final empty token that occurs if the string ends with a new line\n\n if (!linesAndNewlines[linesAndNewlines.length - 1]) {\n linesAndNewlines.pop();\n } // Merge the content and line separators into single tokens\n\n\n for (var i = 0; i < linesAndNewlines.length; i++) {\n var line = linesAndNewlines[i];\n\n if (i % 2 && !this.options.newlineIsToken) {\n retLines[retLines.length - 1] += line;\n } else {\n if (this.options.ignoreWhitespace) {\n line = line.trim();\n }\n\n retLines.push(line);\n }\n }\n\n return retLines;\n};\n\nfunction diffLines(oldStr, newStr, callback) {\n return lineDiff.diff(oldStr, newStr, callback);\n}\n\nfunction diffTrimmedLines(oldStr, newStr, callback) {\n var options =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _params\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n generateOptions)\n /*istanbul ignore end*/\n (callback, {\n ignoreWhitespace: true\n });\n return lineDiff.diff(oldStr, newStr, options);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2xpbmUuanMiXSwibmFtZXMiOlsibGluZURpZmYiLCJEaWZmIiwidG9rZW5pemUiLCJ2YWx1ZSIsInJldExpbmVzIiwibGluZXNBbmROZXdsaW5lcyIsInNwbGl0IiwibGVuZ3RoIiwicG9wIiwiaSIsImxpbmUiLCJvcHRpb25zIiwibmV3bGluZUlzVG9rZW4iLCJpZ25vcmVXaGl0ZXN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U3RyLCBjYWxsYmFjayk7IH1cbmV4cG9ydCBmdW5jdGlvbiBkaWZmVHJpbW1lZExpbmVzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykge1xuICBsZXQgb3B0aW9ucyA9IGdlbmVyYXRlT3B0aW9ucyhjYWxsYmFjaywge2lnbm9yZVdoaXRlc3BhY2U6IHRydWV9KTtcbiAgcmV0dXJuIGxpbmVEaWZmLmRpZmYob2xkU3RyLCBuZXdTdHIsIG9wdGlvbnMpO1xufVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffSentences = diffSentences;\nexports.sentenceDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nvar sentenceDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.sentenceDiff = sentenceDiff;\n\n/*istanbul ignore end*/\nsentenceDiff.tokenize = function (value) {\n return value.split(/(\\S.+?[.!?])(?=\\s+|$)/);\n};\n\nfunction diffSentences(oldStr, newStr, callback) {\n return sentenceDiff.diff(oldStr, newStr, callback);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL3NlbnRlbmNlLmpzIl0sIm5hbWVzIjpbInNlbnRlbmNlRGlmZiIsIkRpZmYiLCJ0b2tlbml6ZSIsInZhbHVlIiwic3BsaXQiLCJkaWZmU2VudGVuY2VzIiwib2xkU3RyIiwibmV3U3RyIiwiY2FsbGJhY2siLCJkaWZmIl0sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7O0FBQUE7QUFBQTtBQUFBO0FBQUE7QUFBQTs7Ozs7QUFHTyxJQUFNQSxZQUFZLEdBQUc7QUFBSUM7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUE7QUFBQUEsQ0FBSixFQUFyQjs7Ozs7O0FBQ1BELFlBQVksQ0FBQ0UsUUFBYixHQUF3QixVQUFTQyxLQUFULEVBQWdCO0FBQ3RDLFNBQU9BLEtBQUssQ0FBQ0MsS0FBTixDQUFZLHVCQUFaLENBQVA7QUFDRCxDQUZEOztBQUlPLFNBQVNDLGFBQVQsQ0FBdUJDLE1BQXZCLEVBQStCQyxNQUEvQixFQUF1Q0MsUUFBdkMsRUFBaUQ7QUFBRSxTQUFPUixZQUFZLENBQUNTLElBQWIsQ0FBa0JILE1BQWxCLEVBQTBCQyxNQUExQixFQUFrQ0MsUUFBbEMsQ0FBUDtBQUFxRCIsInNvdXJjZXNDb250ZW50IjpbImltcG9ydCBEaWZmIGZyb20gJy4vYmFzZSc7XG5cblxuZXhwb3J0IGNvbnN0IHNlbnRlbmNlRGlmZiA9IG5ldyBEaWZmKCk7XG5zZW50ZW5jZURpZmYudG9rZW5pemUgPSBmdW5jdGlvbih2YWx1ZSkge1xuICByZXR1cm4gdmFsdWUuc3BsaXQoLyhcXFMuKz9bLiE/XSkoPz1cXHMrfCQpLyk7XG59O1xuXG5leHBvcnQgZnVuY3Rpb24gZGlmZlNlbnRlbmNlcyhvbGRTdHIsIG5ld1N0ciwgY2FsbGJhY2spIHsgcmV0dXJuIHNlbnRlbmNlRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ==\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffCss = diffCss;\nexports.cssDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nvar cssDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.cssDiff = cssDiff;\n\n/*istanbul ignore end*/\ncssDiff.tokenize = function (value) {\n return value.split(/([{}:;,]|\\s+)/);\n};\n\nfunction diffCss(oldStr, newStr, callback) {\n return cssDiff.diff(oldStr, newStr, callback);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2Nzcy5qcyJdLCJuYW1lcyI6WyJjc3NEaWZmIiwiRGlmZiIsInRva2VuaXplIiwidmFsdWUiLCJzcGxpdCIsImRpZmZDc3MiLCJvbGRTdHIiLCJuZXdTdHIiLCJjYWxsYmFjayIsImRpZmYiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBOzs7OztBQUVPLElBQU1BLE9BQU8sR0FBRztBQUFJQztBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQTtBQUFBQSxDQUFKLEVBQWhCOzs7Ozs7QUFDUEQsT0FBTyxDQUFDRSxRQUFSLEdBQW1CLFVBQVNDLEtBQVQsRUFBZ0I7QUFDakMsU0FBT0EsS0FBSyxDQUFDQyxLQUFOLENBQVksZUFBWixDQUFQO0FBQ0QsQ0FGRDs7QUFJTyxTQUFTQyxPQUFULENBQWlCQyxNQUFqQixFQUF5QkMsTUFBekIsRUFBaUNDLFFBQWpDLEVBQTJDO0FBQUUsU0FBT1IsT0FBTyxDQUFDUyxJQUFSLENBQWFILE1BQWIsRUFBcUJDLE1BQXJCLEVBQTZCQyxRQUE3QixDQUFQO0FBQWdEIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IERpZmYgZnJvbSAnLi9iYXNlJztcblxuZXhwb3J0IGNvbnN0IGNzc0RpZmYgPSBuZXcgRGlmZigpO1xuY3NzRGlmZi50b2tlbml6ZSA9IGZ1bmN0aW9uKHZhbHVlKSB7XG4gIHJldHVybiB2YWx1ZS5zcGxpdCgvKFt7fTo7LF18XFxzKykvKTtcbn07XG5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQ3NzKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjaykgeyByZXR1cm4gY3NzRGlmZi5kaWZmKG9sZFN0ciwgbmV3U3RyLCBjYWxsYmFjayk7IH1cbiJdfQ==\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffJson = diffJson;\nexports.canonicalize = canonicalize;\nexports.jsonDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_line = require(\"./line\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\nfunction _typeof(obj) { \"@babel/helpers - typeof\"; if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; }; } return _typeof(obj); }\n\n/*istanbul ignore end*/\nvar objectPrototypeToString = Object.prototype.toString;\nvar jsonDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n](); // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a\n// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:\n\n/*istanbul ignore start*/\nexports.jsonDiff = jsonDiff;\n\n/*istanbul ignore end*/\njsonDiff.useLongestToken = true;\njsonDiff.tokenize =\n/*istanbul ignore start*/\n_line\n/*istanbul ignore end*/\n.\n/*istanbul ignore start*/\nlineDiff\n/*istanbul ignore end*/\n.tokenize;\n\njsonDiff.castInput = function (value) {\n /*istanbul ignore start*/\n var _this$options =\n /*istanbul ignore end*/\n this.options,\n undefinedReplacement = _this$options.undefinedReplacement,\n _this$options$stringi = _this$options.stringifyReplacer,\n stringifyReplacer = _this$options$stringi === void 0 ? function (k, v)\n /*istanbul ignore start*/\n {\n return (\n /*istanbul ignore end*/\n typeof v === 'undefined' ? undefinedReplacement : v\n );\n } : _this$options$stringi;\n return typeof value === 'string' ? value : JSON.stringify(canonicalize(value, null, null, stringifyReplacer), stringifyReplacer, ' ');\n};\n\njsonDiff.equals = function (left, right) {\n return (\n /*istanbul ignore start*/\n _base\n /*istanbul ignore end*/\n [\n /*istanbul ignore start*/\n \"default\"\n /*istanbul ignore end*/\n ].prototype.equals.call(jsonDiff, left.replace(/,([\\r\\n])/g, '$1'), right.replace(/,([\\r\\n])/g, '$1'))\n );\n};\n\nfunction diffJson(oldObj, newObj, options) {\n return jsonDiff.diff(oldObj, newObj, options);\n} // This function handles the presence of circular references by bailing out when encountering an\n// object that is already on the \"stack\" of items being processed. Accepts an optional replacer\n\n\nfunction canonicalize(obj, stack, replacementStack, replacer, key) {\n stack = stack || [];\n replacementStack = replacementStack || [];\n\n if (replacer) {\n obj = replacer(key, obj);\n }\n\n var i;\n\n for (i = 0; i < stack.length; i += 1) {\n if (stack[i] === obj) {\n return replacementStack[i];\n }\n }\n\n var canonicalizedObj;\n\n if ('[object Array]' === objectPrototypeToString.call(obj)) {\n stack.push(obj);\n canonicalizedObj = new Array(obj.length);\n replacementStack.push(canonicalizedObj);\n\n for (i = 0; i < obj.length; i += 1) {\n canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack, replacer, key);\n }\n\n stack.pop();\n replacementStack.pop();\n return canonicalizedObj;\n }\n\n if (obj && obj.toJSON) {\n obj = obj.toJSON();\n }\n\n if (\n /*istanbul ignore start*/\n _typeof(\n /*istanbul ignore end*/\n obj) === 'object' && obj !== null) {\n stack.push(obj);\n canonicalizedObj = {};\n replacementStack.push(canonicalizedObj);\n\n var sortedKeys = [],\n _key;\n\n for (_key in obj) {\n /* istanbul ignore else */\n if (obj.hasOwnProperty(_key)) {\n sortedKeys.push(_key);\n }\n }\n\n sortedKeys.sort();\n\n for (i = 0; i < sortedKeys.length; i += 1) {\n _key = sortedKeys[i];\n canonicalizedObj[_key] = canonicalize(obj[_key], stack, replacementStack, replacer, _key);\n }\n\n stack.pop();\n replacementStack.pop();\n } else {\n canonicalizedObj = obj;\n }\n\n return canonicalizedObj;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2pzb24uanMiXSwibmFtZXMiOlsib2JqZWN0UHJvdG90eXBlVG9TdHJpbmciLCJPYmplY3QiLCJwcm90b3R5cGUiLCJ0b1N0cmluZyIsImpzb25EaWZmIiwiRGlmZiIsInVzZUxvbmdlc3RUb2tlbiIsInRva2VuaXplIiwibGluZURpZmYiLCJjYXN0SW5wdXQiLCJ2YWx1ZSIsIm9wdGlvbnMiLCJ1bmRlZmluZWRSZXBsYWNlbWVudCIsInN0cmluZ2lmeVJlcGxhY2VyIiwiayIsInYiLCJKU09OIiwic3RyaW5naWZ5IiwiY2Fub25pY2FsaXplIiwiZXF1YWxzIiwibGVmdCIsInJpZ2h0IiwiY2FsbCIsInJlcGxhY2UiLCJkaWZmSnNvbiIsIm9sZE9iaiIsIm5ld09iaiIsImRpZmYiLCJvYmoiLCJzdGFjayIsInJlcGxhY2VtZW50U3RhY2siLCJyZXBsYWNlciIsImtleSIsImkiLCJsZW5ndGgiLCJjYW5vbmljYWxpemVkT2JqIiwicHVzaCIsIkFycmF5IiwicG9w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b3IgKGkgPSAwOyBpIDwgc29ydGVkS2V5cy5sZW5ndGg7IGkgKz0gMSkge1xuICAgICAga2V5ID0gc29ydGVkS2V5c1tpXTtcbiAgICAgIGNhbm9uaWNhbGl6ZWRPYmpba2V5XSA9IGNhbm9uaWNhbGl6ZShvYmpba2V5XSwgc3RhY2ssIHJlcGxhY2VtZW50U3RhY2ssIHJlcGxhY2VyLCBrZXkpO1xuICAgIH1cbiAgICBzdGFjay5wb3AoKTtcbiAgICByZXBsYWNlbWVudFN0YWNrLnBvcCgpO1xuICB9IGVsc2Uge1xuICAgIGNhbm9uaWNhbGl6ZWRPYmogPSBvYmo7XG4gIH1cbiAgcmV0dXJuIGNhbm9uaWNhbGl6ZWRPYmo7XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.diffArrays = diffArrays;\nexports.arrayDiff = void 0;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./base\"))\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nvar arrayDiff = new\n/*istanbul ignore start*/\n_base\n/*istanbul ignore end*/\n[\n/*istanbul ignore start*/\n\"default\"\n/*istanbul ignore end*/\n]();\n\n/*istanbul ignore start*/\nexports.arrayDiff = arrayDiff;\n\n/*istanbul ignore end*/\narrayDiff.tokenize = function (value) {\n return value.slice();\n};\n\narrayDiff.join = arrayDiff.removeEmpty = function (value) {\n return value;\n};\n\nfunction diffArrays(oldArr, newArr, callback) {\n return arrayDiff.diff(oldArr, newArr, callback);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kaWZmL2FycmF5LmpzIl0sIm5hbWVzIjpbImFycmF5RGlmZiIsIkRpZmYiLCJ0b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5cbmV4cG9ydCBmdW5jdGlvbiBkaWZmQXJyYXlzKG9sZEFyciwgbmV3QXJyLCBjYWxsYmFjaykgeyByZXR1cm4gYXJyYXlEaWZmLmRpZmYob2xkQXJyLCBuZXdBcnIsIGNhbGxiYWNrKTsgfVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.parsePatch = parsePatch;\n\n/*istanbul ignore end*/\nfunction parsePatch(uniDiff) {\n /*istanbul ignore start*/\n var\n /*istanbul ignore end*/\n options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var diffstr = uniDiff.split(/\\r\\n|[\\n\\v\\f\\r\\x85]/),\n delimiters = uniDiff.match(/\\r\\n|[\\n\\v\\f\\r\\x85]/g) || [],\n list = [],\n i = 0;\n\n function parseIndex() {\n var index = {};\n list.push(index); // Parse diff metadata\n\n while (i < diffstr.length) {\n var line = diffstr[i]; // File header found, end parsing diff metadata\n\n if (/^(\\-\\-\\-|\\+\\+\\+|@@)\\s/.test(line)) {\n break;\n } // Diff index\n\n\n var header = /^(?:Index:|diff(?: -r \\w+)+)\\s+(.+?)\\s*$/.exec(line);\n\n if (header) {\n index.index = header[1];\n }\n\n i++;\n } // Parse file headers if they are defined. Unified diff requires them, but\n // there's no technical issues to have an isolated hunk without file header\n\n\n parseFileHeader(index);\n parseFileHeader(index); // Parse hunks\n\n index.hunks = [];\n\n while (i < diffstr.length) {\n var _line = diffstr[i];\n\n if (/^(Index:|diff|\\-\\-\\-|\\+\\+\\+)\\s/.test(_line)) {\n break;\n } else if (/^@@/.test(_line)) {\n index.hunks.push(parseHunk());\n } else if (_line && options.strict) {\n // Ignore unexpected content unless in strict mode\n throw new Error('Unknown line ' + (i + 1) + ' ' + JSON.stringify(_line));\n } else {\n i++;\n }\n }\n } // Parses the --- and +++ headers, if none are found, no lines\n // are consumed.\n\n\n function parseFileHeader(index) {\n var fileHeader = /^(---|\\+\\+\\+)\\s+(.*)$/.exec(diffstr[i]);\n\n if (fileHeader) {\n var keyPrefix = fileHeader[1] === '---' ? 'old' : 'new';\n var data = fileHeader[2].split('\\t', 2);\n var fileName = data[0].replace(/\\\\\\\\/g, '\\\\');\n\n if (/^\".*\"$/.test(fileName)) {\n fileName = fileName.substr(1, fileName.length - 2);\n }\n\n index[keyPrefix + 'FileName'] = fileName;\n index[keyPrefix + 'Header'] = (data[1] || '').trim();\n i++;\n }\n } // Parses a hunk\n // This assumes that we are at the start of a hunk.\n\n\n function parseHunk() {\n var chunkHeaderIndex = i,\n chunkHeaderLine = diffstr[i++],\n chunkHeader = chunkHeaderLine.split(/@@ -(\\d+)(?:,(\\d+))? \\+(\\d+)(?:,(\\d+))? @@/);\n var hunk = {\n oldStart: +chunkHeader[1],\n oldLines: typeof chunkHeader[2] === 'undefined' ? 1 : +chunkHeader[2],\n newStart: +chunkHeader[3],\n newLines: typeof chunkHeader[4] === 'undefined' ? 1 : +chunkHeader[4],\n lines: [],\n linedelimiters: []\n }; // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n\n if (hunk.oldLines === 0) {\n hunk.oldStart += 1;\n }\n\n if (hunk.newLines === 0) {\n hunk.newStart += 1;\n }\n\n var addCount = 0,\n removeCount = 0;\n\n for (; i < diffstr.length; i++) {\n // Lines starting with '---' could be mistaken for the \"remove line\" operation\n // But they could be the header for the next file. Therefore prune such cases out.\n if (diffstr[i].indexOf('--- ') === 0 && i + 2 < diffstr.length && diffstr[i + 1].indexOf('+++ ') === 0 && diffstr[i + 2].indexOf('@@') === 0) {\n break;\n }\n\n var operation = diffstr[i].length == 0 && i != diffstr.length - 1 ? ' ' : diffstr[i][0];\n\n if (operation === '+' || operation === '-' || operation === ' ' || operation === '\\\\') {\n hunk.lines.push(diffstr[i]);\n hunk.linedelimiters.push(delimiters[i] || '\\n');\n\n if (operation === '+') {\n addCount++;\n } else if (operation === '-') {\n removeCount++;\n } else if (operation === ' ') {\n addCount++;\n removeCount++;\n }\n } else {\n break;\n }\n } // Handle the empty block count case\n\n\n if (!addCount && hunk.newLines === 1) {\n hunk.newLines = 0;\n }\n\n if (!removeCount && hunk.oldLines === 1) {\n hunk.oldLines = 0;\n } // Perform optional sanity checking\n\n\n if (options.strict) {\n if (addCount !== hunk.newLines) {\n throw new Error('Added line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n\n if (removeCount !== hunk.oldLines) {\n throw new Error('Removed line count did not match for hunk at line ' + (chunkHeaderIndex + 1));\n }\n }\n\n return hunk;\n }\n\n while (i < diffstr.length) {\n parseIndex();\n }\n\n return list;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9wYXJzZS5qcyJdLCJuYW1lcyI6WyJwYXJzZVBhdGNoIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJkaWZmc3RyIiwic3BsaXQiLCJkZWxpbWl0ZXJzIiwibWF0Y2giLCJsaXN0IiwiaSIsInBhcnNlSW5kZXgiLCJpbmRleCIsInB1c2giLCJsZW5ndGgiLCJsaW5lIiwidGVzdCIsImhlYWRlciIsImV4ZWMiLCJwYXJzZUZpbGVIZWFkZXIiLCJodW5rcyIsInBhcnNlSHVuayIsInN0cmljdCIsIkVycm9yIiwiSlNPTiIsInN0cmluZ2lmeSIsImZpbGVIZWFkZXIiLCJrZXlQcmVmaXgiLCJkYXRhIiwiZmlsZU5hbWUiLCJyZXBsYWNlIiwic3Vic3RyIiwidHJpbSIsImNodW5rSGVhZGVySW5kZXgiLCJjaHVua0hlYWRlckxpbmUiLCJjaHVua0hlYWRlciIsImh1bmsiLCJvbGRTdGFydCIsIm9sZExpbmVzIiwibmV3U3RhcnQiLCJuZXdMaW5lcyIsImxpbmVzIiwibGluZWRlbGltaXRlcnMiLCJhZGRDb3VudCIsInJlbW92ZUNvdW50IiwiaW5kZXhPZiIsIm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bnMuc3RyaWN0KSB7XG4gICAgICBpZiAoYWRkQ291bnQgIT09IGh1bmsubmV3TGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdBZGRlZCBsaW5lIGNvdW50IGRpZCBub3QgbWF0Y2ggZm9yIGh1bmsgYXQgbGluZSAnICsgKGNodW5rSGVhZGVySW5kZXggKyAxKSk7XG4gICAgICB9XG4gICAgICBpZiAocmVtb3ZlQ291bnQgIT09IGh1bmsub2xkTGluZXMpIHtcbiAgICAgICAgdGhyb3cgbmV3IEVycm9yKCdSZW1vdmVkIGxpbmUgY291bnQgZGlkIG5vdCBtYXRjaCBmb3IgaHVuayBhdCBsaW5lICcgKyAoY2h1bmtIZWFkZXJJbmRleCArIDEpKTtcbiAgICAgIH1cbiAgICB9XG5cbiAgICByZXR1cm4gaHVuaztcbiAgfVxuXG4gIHdoaWxlIChpIDwgZGlmZnN0ci5sZW5ndGgpIHtcbiAgICBwYXJzZUluZGV4KCk7XG4gIH1cblxuICByZXR1cm4gbGlzdDtcbn1cbiJdfQ==\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports[\"default\"] = _default;\n\n/*istanbul ignore end*/\n// Iterator that traverses in the range of [min, max], stepping\n// by distance from a given start position. I.e. for [0, 4], with\n// start of 2, this will iterate 2, 3, 1, 4, 0.\nfunction\n/*istanbul ignore start*/\n_default\n/*istanbul ignore end*/\n(start, minLine, maxLine) {\n var wantForward = true,\n backwardExhausted = false,\n forwardExhausted = false,\n localOffset = 1;\n return function iterator() {\n if (wantForward && !forwardExhausted) {\n if (backwardExhausted) {\n localOffset++;\n } else {\n wantForward = false;\n } // Check if trying to fit beyond text length, and if not, check it fits\n // after offset location (or desired location on first iteration)\n\n\n if (start + localOffset <= maxLine) {\n return localOffset;\n }\n\n forwardExhausted = true;\n }\n\n if (!backwardExhausted) {\n if (!forwardExhausted) {\n wantForward = true;\n } // Check if trying to fit before text beginning, and if not, check it fits\n // before offset location\n\n\n if (minLine <= start - localOffset) {\n return -localOffset++;\n }\n\n backwardExhausted = true;\n return iterator();\n } // We tried to fit hunk before text beginning and beyond text length, then\n // hunk can't fit on the text. Return undefined\n\n };\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2Rpc3RhbmNlLWl0ZXJhdG9yLmpzIl0sIm5hbWVzIjpbInN0YXJ0IiwibWluTGluZSIsIm1heExpbmUiLCJ3YW50Rm9yd2FyZCIsImJhY2t3YXJkRXhoYXVzdGVkIiwiZm9yd2FyZEV4aGF1c3RlZCIsImxvY2FsT2Zmc2V0IiwiaXRlcmF0b3IiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ0E7QUFDQTtBQUNlO0FBQUE7QUFBQTtBQUFBO0FBQUEsQ0FBU0EsS0FBVCxFQUFnQkMsT0FBaEIsRUFBeUJDLE9BQXpCLEVBQWtDO0FBQy9DLE1BQUlDLFdBQVcsR0FBRyxJQUFsQjtBQUFBLE1BQ0lDLGlCQUFpQixHQUFHLEtBRHhCO0FBQUEsTUFFSUMsZ0JBQWdCLEdBQUcsS0FGdkI7QUFBQSxNQUdJQyxXQUFXLEdBQUcsQ0FIbEI7QUFLQSxTQUFPLFNBQVNDLFFBQVQsR0FBb0I7QUFDekIsUUFBSUosV0FBVyxJQUFJLENBQUNFLGdCQUFwQixFQUFzQztBQUNwQyxVQUFJRCxpQkFBSixFQUF1QjtBQUNyQkUsUUFBQUEsV0FBVztBQUNaLE9BRkQsTUFFTztBQUNMSCxRQUFBQSxXQUFXLEdBQUcsS0FBZDtBQUNELE9BTG1DLENBT3BDO0FBQ0E7OztBQUNBLFVBQUlILEtBQUssR0FBR00sV0FBUixJQUF1QkosT0FBM0IsRUFBb0M7QUFDbEMsZUFBT0ksV0FBUDtBQUNEOztBQUVERCxNQUFBQSxnQkFBZ0IsR0FBRyxJQUFu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0IG9uIHRoZSB0ZXh0LiBSZXR1cm4gdW5kZWZpbmVkXG4gIH07XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.applyPatch = applyPatch;\nexports.applyPatches = applyPatches;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_parse = require(\"./parse\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_distanceIterator = _interopRequireDefault(require(\"../util/distance-iterator\"))\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\nfunction applyPatch(source, uniDiff) {\n /*istanbul ignore start*/\n var\n /*istanbul ignore end*/\n options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n\n if (typeof uniDiff === 'string') {\n uniDiff =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _parse\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n parsePatch)\n /*istanbul ignore end*/\n (uniDiff);\n }\n\n if (Array.isArray(uniDiff)) {\n if (uniDiff.length > 1) {\n throw new Error('applyPatch only works with a single input.');\n }\n\n uniDiff = uniDiff[0];\n } // Apply the diff to the input\n\n\n var lines = source.split(/\\r\\n|[\\n\\v\\f\\r\\x85]/),\n delimiters = source.match(/\\r\\n|[\\n\\v\\f\\r\\x85]/g) || [],\n hunks = uniDiff.hunks,\n compareLine = options.compareLine || function (lineNumber, line, operation, patchContent)\n /*istanbul ignore start*/\n {\n return (\n /*istanbul ignore end*/\n line === patchContent\n );\n },\n errorCount = 0,\n fuzzFactor = options.fuzzFactor || 0,\n minLine = 0,\n offset = 0,\n removeEOFNL,\n addEOFNL;\n /**\n * Checks if the hunk exactly fits on the provided location\n */\n\n\n function hunkFits(hunk, toPos) {\n for (var j = 0; j < hunk.lines.length; j++) {\n var line = hunk.lines[j],\n operation = line.length > 0 ? line[0] : ' ',\n content = line.length > 0 ? line.substr(1) : line;\n\n if (operation === ' ' || operation === '-') {\n // Context sanity check\n if (!compareLine(toPos + 1, lines[toPos], operation, content)) {\n errorCount++;\n\n if (errorCount > fuzzFactor) {\n return false;\n }\n }\n\n toPos++;\n }\n }\n\n return true;\n } // Search best fit offsets for each hunk based on the previous ones\n\n\n for (var i = 0; i < hunks.length; i++) {\n var hunk = hunks[i],\n maxLine = lines.length - hunk.oldLines,\n localOffset = 0,\n toPos = offset + hunk.oldStart - 1;\n var iterator =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _distanceIterator\n /*istanbul ignore end*/\n [\n /*istanbul ignore start*/\n \"default\"\n /*istanbul ignore end*/\n ])(toPos, minLine, maxLine);\n\n for (; localOffset !== undefined; localOffset = iterator()) {\n if (hunkFits(hunk, toPos + localOffset)) {\n hunk.offset = offset += localOffset;\n break;\n }\n }\n\n if (localOffset === undefined) {\n return false;\n } // Set lower text limit to end of the current hunk, so next ones don't try\n // to fit over already patched text\n\n\n minLine = hunk.offset + hunk.oldStart + hunk.oldLines;\n } // Apply patch hunks\n\n\n var diffOffset = 0;\n\n for (var _i = 0; _i < hunks.length; _i++) {\n var _hunk = hunks[_i],\n _toPos = _hunk.oldStart + _hunk.offset + diffOffset - 1;\n\n diffOffset += _hunk.newLines - _hunk.oldLines;\n\n for (var j = 0; j < _hunk.lines.length; j++) {\n var line = _hunk.lines[j],\n operation = line.length > 0 ? line[0] : ' ',\n content = line.length > 0 ? line.substr(1) : line,\n delimiter = _hunk.linedelimiters[j];\n\n if (operation === ' ') {\n _toPos++;\n } else if (operation === '-') {\n lines.splice(_toPos, 1);\n delimiters.splice(_toPos, 1);\n /* istanbul ignore else */\n } else if (operation === '+') {\n lines.splice(_toPos, 0, content);\n delimiters.splice(_toPos, 0, delimiter);\n _toPos++;\n } else if (operation === '\\\\') {\n var previousOperation = _hunk.lines[j - 1] ? _hunk.lines[j - 1][0] : null;\n\n if (previousOperation === '+') {\n removeEOFNL = true;\n } else if (previousOperation === '-') {\n addEOFNL = true;\n }\n }\n }\n } // Handle EOFNL insertion/removal\n\n\n if (removeEOFNL) {\n while (!lines[lines.length - 1]) {\n lines.pop();\n delimiters.pop();\n }\n } else if (addEOFNL) {\n lines.push('');\n delimiters.push('\\n');\n }\n\n for (var _k = 0; _k < lines.length - 1; _k++) {\n lines[_k] = lines[_k] + delimiters[_k];\n }\n\n return lines.join('');\n} // Wrapper that supports multiple file patches via callbacks.\n\n\nfunction applyPatches(uniDiff, options) {\n if (typeof uniDiff === 'string') {\n uniDiff =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _parse\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n parsePatch)\n /*istanbul ignore end*/\n (uniDiff);\n }\n\n var currentIndex = 0;\n\n function processIndex() {\n var index = uniDiff[currentIndex++];\n\n if (!index) {\n return options.complete();\n }\n\n options.loadFile(index, function (err, data) {\n if (err) {\n return options.complete(err);\n }\n\n var updatedContent = applyPatch(data, index, options);\n options.patched(index, updatedContent, function (err) {\n if (err) {\n return options.complete(err);\n }\n\n processIndex();\n });\n });\n }\n\n processIndex();\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9hcHBseS5qcyJdLCJuYW1lcyI6WyJhcHBseVBhdGNoIiwic291cmNlIiwidW5pRGlmZiIsIm9wdGlvbnMiLCJwYXJzZVBhdGNoIiwiQXJyYXkiLCJpc0FycmF5IiwibGVuZ3RoIiwiRXJyb3IiLCJsaW5lcyIsInNwbGl0IiwiZGVsaW1pdGVycyIsIm1hdGNoIiwiaHVua3MiLCJjb21wYXJlTGluZSIsImxpbmVOdW1iZXIiLCJsaW5lIiwib3BlcmF0aW9uIiwicGF0Y2hDb250ZW50IiwiZXJyb3JDb3Vud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GxlIGZpbGUgcGF0Y2hlcyB2aWEgY2FsbGJhY2tzLlxuZXhwb3J0IGZ1bmN0aW9uIGFwcGx5UGF0Y2hlcyh1bmlEaWZmLCBvcHRpb25zKSB7XG4gIGlmICh0eXBlb2YgdW5pRGlmZiA9PT0gJ3N0cmluZycpIHtcbiAgICB1bmlEaWZmID0gcGFyc2VQYXRjaCh1bmlEaWZmKTtcbiAgfVxuXG4gIGxldCBjdXJyZW50SW5kZXggPSAwO1xuICBmdW5jdGlvbiBwcm9jZXNzSW5kZXgoKSB7XG4gICAgbGV0IGluZGV4ID0gdW5pRGlmZltjdXJyZW50SW5kZXgrK107XG4gICAgaWYgKCFpbmRleCkge1xuICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoKTtcbiAgICB9XG5cbiAgICBvcHRpb25zLmxvYWRGaWxlKGluZGV4LCBmdW5jdGlvbihlcnIsIGRhdGEpIHtcbiAgICAgIGlmIChlcnIpIHtcbiAgICAgICAgcmV0dXJuIG9wdGlvbnMuY29tcGxldGUoZXJyKTtcbiAgICAgIH1cblxuICAgICAgbGV0IHVwZGF0ZWRDb250ZW50ID0gYXBwbHlQYXRjaChkYXRhLCBpbmRleCwgb3B0aW9ucyk7XG4gICAgICBvcHRpb25zLnBhdGNoZWQoaW5kZXgsIHVwZGF0ZWRDb250ZW50LCBmdW5jdGlvbihlcnIpIHtcbiAgICAgICAgaWYgKGVycikge1xuICAgICAgICAgIHJldHVybiBvcHRpb25zLmNvbXBsZXRlKGVycik7XG4gICAgICAgIH1cblxuICAgICAgICBwcm9jZXNzSW5kZXgoKTtcbiAgICAgIH0pO1xuICAgIH0pO1xuICB9XG4gIHByb2Nlc3NJbmRleCgpO1xufVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.structuredPatch = structuredPatch;\nexports.formatPatch = formatPatch;\nexports.createTwoFilesPatch = createTwoFilesPatch;\nexports.createPatch = createPatch;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_line = require(\"../diff/line\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\n/*istanbul ignore end*/\nfunction structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n if (!options) {\n options = {};\n }\n\n if (typeof options.context === 'undefined') {\n options.context = 4;\n }\n\n var diff =\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _line\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n diffLines)\n /*istanbul ignore end*/\n (oldStr, newStr, options);\n diff.push({\n value: '',\n lines: []\n }); // Append an empty value to make cleanup easier\n\n function contextLines(lines) {\n return lines.map(function (entry) {\n return ' ' + entry;\n });\n }\n\n var hunks = [];\n var oldRangeStart = 0,\n newRangeStart = 0,\n curRange = [],\n oldLine = 1,\n newLine = 1;\n\n /*istanbul ignore start*/\n var _loop = function _loop(\n /*istanbul ignore end*/\n i) {\n var current = diff[i],\n lines = current.lines || current.value.replace(/\\n$/, '').split('\\n');\n current.lines = lines;\n\n if (current.added || current.removed) {\n /*istanbul ignore start*/\n var _curRange;\n\n /*istanbul ignore end*/\n // If we have previous context, start with that\n if (!oldRangeStart) {\n var prev = diff[i - 1];\n oldRangeStart = oldLine;\n newRangeStart = newLine;\n\n if (prev) {\n curRange = options.context > 0 ? contextLines(prev.lines.slice(-options.context)) : [];\n oldRangeStart -= curRange.length;\n newRangeStart -= curRange.length;\n }\n } // Output our changes\n\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_curRange =\n /*istanbul ignore end*/\n curRange).push.apply(\n /*istanbul ignore start*/\n _curRange\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n lines.map(function (entry) {\n return (current.added ? '+' : '-') + entry;\n }))); // Track the updated file position\n\n\n if (current.added) {\n newLine += lines.length;\n } else {\n oldLine += lines.length;\n }\n } else {\n // Identical context lines. Track line changes\n if (oldRangeStart) {\n // Close out any changes that have been output (or join overlapping)\n if (lines.length <= options.context * 2 && i < diff.length - 2) {\n /*istanbul ignore start*/\n var _curRange2;\n\n /*istanbul ignore end*/\n // Overlapping\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_curRange2 =\n /*istanbul ignore end*/\n curRange).push.apply(\n /*istanbul ignore start*/\n _curRange2\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n contextLines(lines)));\n } else {\n /*istanbul ignore start*/\n var _curRange3;\n\n /*istanbul ignore end*/\n // end the range and output\n var contextSize = Math.min(lines.length, options.context);\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_curRange3 =\n /*istanbul ignore end*/\n curRange).push.apply(\n /*istanbul ignore start*/\n _curRange3\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n contextLines(lines.slice(0, contextSize))));\n\n var hunk = {\n oldStart: oldRangeStart,\n oldLines: oldLine - oldRangeStart + contextSize,\n newStart: newRangeStart,\n newLines: newLine - newRangeStart + contextSize,\n lines: curRange\n };\n\n if (i >= diff.length - 2 && lines.length <= options.context) {\n // EOF is inside this hunk\n var oldEOFNewline = /\\n$/.test(oldStr);\n var newEOFNewline = /\\n$/.test(newStr);\n var noNlBeforeAdds = lines.length == 0 && curRange.length > hunk.oldLines;\n\n if (!oldEOFNewline && noNlBeforeAdds && oldStr.length > 0) {\n // special case: old has no eol and no trailing context; no-nl can end up before adds\n // however, if the old file is empty, do not output the no-nl line\n curRange.splice(hunk.oldLines, 0, '\\\\ No newline at end of file');\n }\n\n if (!oldEOFNewline && !noNlBeforeAdds || !newEOFNewline) {\n curRange.push('\\\\ No newline at end of file');\n }\n }\n\n hunks.push(hunk);\n oldRangeStart = 0;\n newRangeStart = 0;\n curRange = [];\n }\n }\n\n oldLine += lines.length;\n newLine += lines.length;\n }\n };\n\n for (var i = 0; i < diff.length; i++) {\n /*istanbul ignore start*/\n _loop(\n /*istanbul ignore end*/\n i);\n }\n\n return {\n oldFileName: oldFileName,\n newFileName: newFileName,\n oldHeader: oldHeader,\n newHeader: newHeader,\n hunks: hunks\n };\n}\n\nfunction formatPatch(diff) {\n var ret = [];\n\n if (diff.oldFileName == diff.newFileName) {\n ret.push('Index: ' + diff.oldFileName);\n }\n\n ret.push('===================================================================');\n ret.push('--- ' + diff.oldFileName + (typeof diff.oldHeader === 'undefined' ? '' : '\\t' + diff.oldHeader));\n ret.push('+++ ' + diff.newFileName + (typeof diff.newHeader === 'undefined' ? '' : '\\t' + diff.newHeader));\n\n for (var i = 0; i < diff.hunks.length; i++) {\n var hunk = diff.hunks[i]; // Unified Diff Format quirk: If the chunk size is 0,\n // the first number is one lower than one would expect.\n // https://www.artima.com/weblogs/viewpost.jsp?thread=164293\n\n if (hunk.oldLines === 0) {\n hunk.oldStart -= 1;\n }\n\n if (hunk.newLines === 0) {\n hunk.newStart -= 1;\n }\n\n ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines + ' +' + hunk.newStart + ',' + hunk.newLines + ' @@');\n ret.push.apply(ret, hunk.lines);\n }\n\n return ret.join('\\n') + '\\n';\n}\n\nfunction createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) {\n return formatPatch(structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options));\n}\n\nfunction createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) {\n return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options);\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9jcmVhdGUuanMiXSwibmFtZXMiOlsic3RydWN0dXJlZFBhdGNoIiwib2xkRmlsZU5hbWUiLCJuZXdGaWxlTmFtZSIsIm9sZFN0ciIsIm5ld1N0ciIsIm9sZEhlYWRlciIsIm5ld0hlYWRlciIsIm9wdGlvbnMiLCJjb250ZXh0IiwiZGlmZiIsImRpZmZMaW5lcyIsInB1c2giLCJ2YWx1ZSIsImxpbmVzIiwiY29udGV4dExpbmVzIiwibWFwIiwiZW50cnkiLCJodW5rcyIsIm9sZFJhbmdlU3RhcnQiLCJuZXdSYW5nZVN0YXJ0IiwiY3VyUmFuZ2UiLCJvbGRMaW5lIiwibmV3TGluZSIsImkiLCJjdXJyZW50IiwicmVwbGFjZSIsInNwbGl0IiwiYWRkZWQiLCJyZW1vdmVkIiwicHJldiIsInNsaWNlIiwibGVuZ3RoIiwiY29udGV4dFNpemUiLCJNYXRoIiwibWluIiwiaHVuayIsIm9sZFN0YXJ0Iiwib2xkTGluZXMiLCJuZXd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ldC5wdXNoLmFwcGx5KHJldCwgaHVuay5saW5lcyk7XG4gIH1cblxuICByZXR1cm4gcmV0LmpvaW4oJ1xcbicpICsgJ1xcbic7XG59XG5cbmV4cG9ydCBmdW5jdGlvbiBjcmVhdGVUd29GaWxlc1BhdGNoKG9sZEZpbGVOYW1lLCBuZXdGaWxlTmFtZSwgb2xkU3RyLCBuZXdTdHIsIG9sZEhlYWRlciwgbmV3SGVhZGVyLCBvcHRpb25zKSB7XG4gIHJldHVybiBmb3JtYXRQYXRjaChzdHJ1Y3R1cmVkUGF0Y2gob2xkRmlsZU5hbWUsIG5ld0ZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpKTtcbn1cblxuZXhwb3J0IGZ1bmN0aW9uIGNyZWF0ZVBhdGNoKGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpIHtcbiAgcmV0dXJuIGNyZWF0ZVR3b0ZpbGVzUGF0Y2goZmlsZU5hbWUsIGZpbGVOYW1lLCBvbGRTdHIsIG5ld1N0ciwgb2xkSGVhZGVyLCBuZXdIZWFkZXIsIG9wdGlvbnMpO1xufVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.arrayEqual = arrayEqual;\nexports.arrayStartsWith = arrayStartsWith;\n\n/*istanbul ignore end*/\nfunction arrayEqual(a, b) {\n if (a.length !== b.length) {\n return false;\n }\n\n return arrayStartsWith(a, b);\n}\n\nfunction arrayStartsWith(array, start) {\n if (start.length > array.length) {\n return false;\n }\n\n for (var i = 0; i < start.length; i++) {\n if (start[i] !== array[i]) {\n return false;\n }\n }\n\n return true;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy91dGlsL2FycmF5L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XJ0c1dpdGgoYXJyYXksIHN0YXJ0KSB7XG4gIGlmIChzdGFydC5sZW5ndGggPiBhcnJheS5sZW5ndGgpIHtcbiAgICByZXR1cm4gZmFsc2U7XG4gIH1cblxuICBmb3IgKGxldCBpID0gMDsgaSA8IHN0YXJ0Lmxlbmd0aDsgaSsrKSB7XG4gICAgaWYgKHN0YXJ0W2ldICE9PSBhcnJheVtpXSkge1xuICAgICAgcmV0dXJuIGZhbHNlO1xuICAgIH1cbiAgfVxuXG4gIHJldHVybiB0cnVlO1xufVxuIl19\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.calcLineCount = calcLineCount;\nexports.merge = merge;\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_create = require(\"./create\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_parse = require(\"./parse\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_array = require(\"../util/array\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }\n\nfunction _nonIterableSpread() { throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\"); }\n\nfunction _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === \"string\") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === \"Object\" && o.constructor) n = o.constructor.name; if (n === \"Map\" || n === \"Set\") return Array.from(o); if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }\n\nfunction _iterableToArray(iter) { if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter); }\n\nfunction _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }\n\nfunction _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }\n\n/*istanbul ignore end*/\nfunction calcLineCount(hunk) {\n /*istanbul ignore start*/\n var _calcOldNewLineCount =\n /*istanbul ignore end*/\n calcOldNewLineCount(hunk.lines),\n oldLines = _calcOldNewLineCount.oldLines,\n newLines = _calcOldNewLineCount.newLines;\n\n if (oldLines !== undefined) {\n hunk.oldLines = oldLines;\n } else {\n delete hunk.oldLines;\n }\n\n if (newLines !== undefined) {\n hunk.newLines = newLines;\n } else {\n delete hunk.newLines;\n }\n}\n\nfunction merge(mine, theirs, base) {\n mine = loadPatch(mine, base);\n theirs = loadPatch(theirs, base);\n var ret = {}; // For index we just let it pass through as it doesn't have any necessary meaning.\n // Leaving sanity checks on this to the API consumer that may know more about the\n // meaning in their own context.\n\n if (mine.index || theirs.index) {\n ret.index = mine.index || theirs.index;\n }\n\n if (mine.newFileName || theirs.newFileName) {\n if (!fileNameChanged(mine)) {\n // No header or no change in ours, use theirs (and ours if theirs does not exist)\n ret.oldFileName = theirs.oldFileName || mine.oldFileName;\n ret.newFileName = theirs.newFileName || mine.newFileName;\n ret.oldHeader = theirs.oldHeader || mine.oldHeader;\n ret.newHeader = theirs.newHeader || mine.newHeader;\n } else if (!fileNameChanged(theirs)) {\n // No header or no change in theirs, use ours\n ret.oldFileName = mine.oldFileName;\n ret.newFileName = mine.newFileName;\n ret.oldHeader = mine.oldHeader;\n ret.newHeader = mine.newHeader;\n } else {\n // Both changed... figure it out\n ret.oldFileName = selectField(ret, mine.oldFileName, theirs.oldFileName);\n ret.newFileName = selectField(ret, mine.newFileName, theirs.newFileName);\n ret.oldHeader = selectField(ret, mine.oldHeader, theirs.oldHeader);\n ret.newHeader = selectField(ret, mine.newHeader, theirs.newHeader);\n }\n }\n\n ret.hunks = [];\n var mineIndex = 0,\n theirsIndex = 0,\n mineOffset = 0,\n theirsOffset = 0;\n\n while (mineIndex < mine.hunks.length || theirsIndex < theirs.hunks.length) {\n var mineCurrent = mine.hunks[mineIndex] || {\n oldStart: Infinity\n },\n theirsCurrent = theirs.hunks[theirsIndex] || {\n oldStart: Infinity\n };\n\n if (hunkBefore(mineCurrent, theirsCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(mineCurrent, mineOffset));\n mineIndex++;\n theirsOffset += mineCurrent.newLines - mineCurrent.oldLines;\n } else if (hunkBefore(theirsCurrent, mineCurrent)) {\n // This patch does not overlap with any of the others, yay.\n ret.hunks.push(cloneHunk(theirsCurrent, theirsOffset));\n theirsIndex++;\n mineOffset += theirsCurrent.newLines - theirsCurrent.oldLines;\n } else {\n // Overlap, merge as best we can\n var mergedHunk = {\n oldStart: Math.min(mineCurrent.oldStart, theirsCurrent.oldStart),\n oldLines: 0,\n newStart: Math.min(mineCurrent.newStart + mineOffset, theirsCurrent.oldStart + theirsOffset),\n newLines: 0,\n lines: []\n };\n mergeLines(mergedHunk, mineCurrent.oldStart, mineCurrent.lines, theirsCurrent.oldStart, theirsCurrent.lines);\n theirsIndex++;\n mineIndex++;\n ret.hunks.push(mergedHunk);\n }\n }\n\n return ret;\n}\n\nfunction loadPatch(param, base) {\n if (typeof param === 'string') {\n if (/^@@/m.test(param) || /^Index:/m.test(param)) {\n return (\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _parse\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n parsePatch)\n /*istanbul ignore end*/\n (param)[0]\n );\n }\n\n if (!base) {\n throw new Error('Must provide a base reference or pass in a patch');\n }\n\n return (\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _create\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n structuredPatch)\n /*istanbul ignore end*/\n (undefined, undefined, base, param)\n );\n }\n\n return param;\n}\n\nfunction fileNameChanged(patch) {\n return patch.newFileName && patch.newFileName !== patch.oldFileName;\n}\n\nfunction selectField(index, mine, theirs) {\n if (mine === theirs) {\n return mine;\n } else {\n index.conflict = true;\n return {\n mine: mine,\n theirs: theirs\n };\n }\n}\n\nfunction hunkBefore(test, check) {\n return test.oldStart < check.oldStart && test.oldStart + test.oldLines < check.oldStart;\n}\n\nfunction cloneHunk(hunk, offset) {\n return {\n oldStart: hunk.oldStart,\n oldLines: hunk.oldLines,\n newStart: hunk.newStart + offset,\n newLines: hunk.newLines,\n lines: hunk.lines\n };\n}\n\nfunction mergeLines(hunk, mineOffset, mineLines, theirOffset, theirLines) {\n // This will generally result in a conflicted hunk, but there are cases where the context\n // is the only overlap where we can successfully merge the content here.\n var mine = {\n offset: mineOffset,\n lines: mineLines,\n index: 0\n },\n their = {\n offset: theirOffset,\n lines: theirLines,\n index: 0\n }; // Handle any leading content\n\n insertLeading(hunk, mine, their);\n insertLeading(hunk, their, mine); // Now in the overlap content. Scan through and select the best changes from each.\n\n while (mine.index < mine.lines.length && their.index < their.lines.length) {\n var mineCurrent = mine.lines[mine.index],\n theirCurrent = their.lines[their.index];\n\n if ((mineCurrent[0] === '-' || mineCurrent[0] === '+') && (theirCurrent[0] === '-' || theirCurrent[0] === '+')) {\n // Both modified ...\n mutualChange(hunk, mine, their);\n } else if (mineCurrent[0] === '+' && theirCurrent[0] === ' ') {\n /*istanbul ignore start*/\n var _hunk$lines;\n\n /*istanbul ignore end*/\n // Mine inserted\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n collectChange(mine)));\n } else if (theirCurrent[0] === '+' && mineCurrent[0] === ' ') {\n /*istanbul ignore start*/\n var _hunk$lines2;\n\n /*istanbul ignore end*/\n // Theirs inserted\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines2 =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines2\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n collectChange(their)));\n } else if (mineCurrent[0] === '-' && theirCurrent[0] === ' ') {\n // Mine removed or edited\n removal(hunk, mine, their);\n } else if (theirCurrent[0] === '-' && mineCurrent[0] === ' ') {\n // Their removed or edited\n removal(hunk, their, mine, true);\n } else if (mineCurrent === theirCurrent) {\n // Context identity\n hunk.lines.push(mineCurrent);\n mine.index++;\n their.index++;\n } else {\n // Context mismatch\n conflict(hunk, collectChange(mine), collectChange(their));\n }\n } // Now push anything that may be remaining\n\n\n insertTrailing(hunk, mine);\n insertTrailing(hunk, their);\n calcLineCount(hunk);\n}\n\nfunction mutualChange(hunk, mine, their) {\n var myChanges = collectChange(mine),\n theirChanges = collectChange(their);\n\n if (allRemoves(myChanges) && allRemoves(theirChanges)) {\n // Special case for remove changes that are supersets of one another\n if (\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _array\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n arrayStartsWith)\n /*istanbul ignore end*/\n (myChanges, theirChanges) && skipRemoveSuperset(their, myChanges, myChanges.length - theirChanges.length)) {\n /*istanbul ignore start*/\n var _hunk$lines3;\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines3 =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines3\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n myChanges));\n\n return;\n } else if (\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _array\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n arrayStartsWith)\n /*istanbul ignore end*/\n (theirChanges, myChanges) && skipRemoveSuperset(mine, theirChanges, theirChanges.length - myChanges.length)) {\n /*istanbul ignore start*/\n var _hunk$lines4;\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines4 =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines4\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n theirChanges));\n\n return;\n }\n } else if (\n /*istanbul ignore start*/\n (0,\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n _array\n /*istanbul ignore end*/\n .\n /*istanbul ignore start*/\n arrayEqual)\n /*istanbul ignore end*/\n (myChanges, theirChanges)) {\n /*istanbul ignore start*/\n var _hunk$lines5;\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines5 =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines5\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n myChanges));\n\n return;\n }\n\n conflict(hunk, myChanges, theirChanges);\n}\n\nfunction removal(hunk, mine, their, swap) {\n var myChanges = collectChange(mine),\n theirChanges = collectContext(their, myChanges);\n\n if (theirChanges.merged) {\n /*istanbul ignore start*/\n var _hunk$lines6;\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n\n /*istanbul ignore end*/\n\n /*istanbul ignore start*/\n (_hunk$lines6 =\n /*istanbul ignore end*/\n hunk.lines).push.apply(\n /*istanbul ignore start*/\n _hunk$lines6\n /*istanbul ignore end*/\n ,\n /*istanbul ignore start*/\n _toConsumableArray(\n /*istanbul ignore end*/\n theirChanges.merged));\n } else {\n conflict(hunk, swap ? theirChanges : myChanges, swap ? myChanges : theirChanges);\n }\n}\n\nfunction conflict(hunk, mine, their) {\n hunk.conflict = true;\n hunk.lines.push({\n conflict: true,\n mine: mine,\n theirs: their\n });\n}\n\nfunction insertLeading(hunk, insert, their) {\n while (insert.offset < their.offset && insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n insert.offset++;\n }\n}\n\nfunction insertTrailing(hunk, insert) {\n while (insert.index < insert.lines.length) {\n var line = insert.lines[insert.index++];\n hunk.lines.push(line);\n }\n}\n\nfunction collectChange(state) {\n var ret = [],\n operation = state.lines[state.index][0];\n\n while (state.index < state.lines.length) {\n var line = state.lines[state.index]; // Group additions that are immediately after subtractions and treat them as one \"atomic\" modify change.\n\n if (operation === '-' && line[0] === '+') {\n operation = '+';\n }\n\n if (operation === line[0]) {\n ret.push(line);\n state.index++;\n } else {\n break;\n }\n }\n\n return ret;\n}\n\nfunction collectContext(state, matchChanges) {\n var changes = [],\n merged = [],\n matchIndex = 0,\n contextChanges = false,\n conflicted = false;\n\n while (matchIndex < matchChanges.length && state.index < state.lines.length) {\n var change = state.lines[state.index],\n match = matchChanges[matchIndex]; // Once we've hit our add, then we are done\n\n if (match[0] === '+') {\n break;\n }\n\n contextChanges = contextChanges || change[0] !== ' ';\n merged.push(match);\n matchIndex++; // Consume any additions in the other block as a conflict to attempt\n // to pull in the remaining context after this\n\n if (change[0] === '+') {\n conflicted = true;\n\n while (change[0] === '+') {\n changes.push(change);\n change = state.lines[++state.index];\n }\n }\n\n if (match.substr(1) === change.substr(1)) {\n changes.push(change);\n state.index++;\n } else {\n conflicted = true;\n }\n }\n\n if ((matchChanges[matchIndex] || '')[0] === '+' && contextChanges) {\n conflicted = true;\n }\n\n if (conflicted) {\n return changes;\n }\n\n while (matchIndex < matchChanges.length) {\n merged.push(matchChanges[matchIndex++]);\n }\n\n return {\n merged: merged,\n changes: changes\n };\n}\n\nfunction allRemoves(changes) {\n return changes.reduce(function (prev, change) {\n return prev && change[0] === '-';\n }, true);\n}\n\nfunction skipRemoveSuperset(state, removeChanges, delta) {\n for (var i = 0; i < delta; i++) {\n var changeContent = removeChanges[removeChanges.length - delta + i].substr(1);\n\n if (state.lines[state.index + i] !== ' ' + changeContent) {\n return false;\n }\n }\n\n state.index += delta;\n return true;\n}\n\nfunction calcOldNewLineCount(lines) {\n var oldLines = 0;\n var newLines = 0;\n lines.forEach(function (line) {\n if (typeof line !== 'string') {\n var myCount = calcOldNewLineCount(line.mine);\n var theirCount = calcOldNewLineCount(line.theirs);\n\n if (oldLines !== undefined) {\n if (myCount.oldLines === theirCount.oldLines) {\n oldLines += myCount.oldLines;\n } else {\n oldLines = undefined;\n }\n }\n\n if (newLines !== undefined) {\n if (myCount.newLines === theirCount.newLines) {\n newLines += myCount.newLines;\n } else {\n newLines = undefined;\n }\n }\n } else {\n if (newLines !== undefined && (line[0] === '+' || line[0] === ' ')) {\n newLines++;\n }\n\n if (oldLines !== undefined && (line[0] === '-' || line[0] === ' ')) {\n oldLines++;\n }\n }\n });\n return {\n oldLines: oldLines,\n newLines: newLines\n };\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9wYXRjaC9tZXJnZS5qcyJdLCJuYW1lcyI6WyJjYWxjTGluZUNvdW50IiwiaHVuayIsImNhbGNPbGROZXdMaW5lQ291bnQiLCJsaW5lcyIsIm9sZExpbmVzIiwibmV3TGluZXMiLCJ1bmRlZmluZWQiLCJtZXJnZSIsIm1pbmUiLCJ0aGVpcnMiLCJiYXNlIiwibG9hZFBhdGNoIiwicmV0IiwiaW5kZXgiLCJuZXdGaWxlTmFtZSIsImZpbGVOYW1lQ2hhbmdlZCIsIm9sZEZpbGVOYW1lIiwib2xkSGVhZGVyIiwibmV3SGVhZGVyIiwic2VsZWN0RmllbGQiLCJodW5rcyIsIm1pbmVJbmRleCIsInRoZWlyc0luZGV4Iiw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vZiBsaW5lICE9PSAnc3RyaW5nJykge1xuICAgICAgbGV0IG15Q291bnQgPSBjYWxjT2xkTmV3TGluZUNvdW50KGxpbmUubWluZSk7XG4gICAgICBsZXQgdGhlaXJDb3VudCA9IGNhbGNPbGROZXdMaW5lQ291bnQobGluZS50aGVpcnMpO1xuXG4gICAgICBpZiAob2xkTGluZXMgIT09IHVuZGVmaW5lZCkge1xuICAgICAgICBpZiAobXlDb3VudC5vbGRMaW5lcyA9PT0gdGhlaXJDb3VudC5vbGRMaW5lcykge1xuICAgICAgICAgIG9sZExpbmVzICs9IG15Q291bnQub2xkTGluZXM7XG4gICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgb2xkTGluZXMgPSB1bmRlZmluZWQ7XG4gICAgICAgIH1cbiAgICAgIH1cblxuICAgICAgaWYgKG5ld0xpbmVzICE9PSB1bmRlZmluZWQpIHtcbiAgICAgICAgaWYgKG15Q291bnQubmV3TGluZXMgPT09IHRoZWlyQ291bnQubmV3TGluZXMpIHtcbiAgICAgICAgICBuZXdMaW5lcyArPSBteUNvdW50Lm5ld0xpbmVzO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgIG5ld0xpbmVzID0gdW5kZWZpbmVkO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfSBlbHNlIHtcbiAgICAgIGlmIChuZXdMaW5lcyAhPT0gdW5kZWZpbmVkICYmIChsaW5lWzBdID09PSAnKycgfHwgbGluZVswXSA9PT0gJyAnKSkge1xuICAgICAgICBuZXdMaW5lcysrO1xuICAgICAgfVxuICAgICAgaWYgKG9sZExpbmVzICE9PSB1bmRlZmluZWQgJiYgKGxpbmVbMF0gPT09ICctJyB8fCBsaW5lWzBdID09PSAnICcpKSB7XG4gICAgICAgIG9sZExpbmVzKys7XG4gICAgICB9XG4gICAgfVxuICB9KTtcblxuICByZXR1cm4ge29sZExpbmVzLCBuZXdMaW5lc307XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.convertChangesToDMP = convertChangesToDMP;\n\n/*istanbul ignore end*/\n// See: http://code.google.com/p/google-diff-match-patch/wiki/API\nfunction convertChangesToDMP(changes) {\n var ret = [],\n change,\n operation;\n\n for (var i = 0; i < changes.length; i++) {\n change = changes[i];\n\n if (change.added) {\n operation = 1;\n } else if (change.removed) {\n operation = -1;\n } else {\n operation = 0;\n }\n\n ret.push([operation, change.value]);\n }\n\n return ret;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L2RtcC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvRE1QIiwiY2hhbmdlcyIsInJldCIsImNoYW5nZSIsIm9wZXJhdGlvbiIsImkiLCJsZW5ndGgiLCJhZGRlZCIsInJlbW92ZWQiLCJwdXNoIiwidmFsdWUiXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBO0FBQ08sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWO0FBQUEsTUFDSUMsTUFESjtBQUFBLE1BRUlDLFNBRko7O0FBR0EsT0FBSyxJQUFJQyxDQUFDLEdBQUcsQ0FBYixFQUFnQkEsQ0FBQyxHQUFHSixPQUFPLENBQUNLLE1BQTVCLEVBQW9DRCxDQUFDLEVBQXJDLEVBQXlDO0FBQ3ZDRixJQUFBQSxNQUFNLEdBQUdGLE9BQU8sQ0FBQ0ksQ0FBRCxDQUFoQjs7QUFDQSxRQUFJRixNQUFNLENBQUNJLEtBQVgsRUFBa0I7QUFDaEJILE1BQUFBLFNBQVMsR0FBRyxDQUFaO0FBQ0QsS0FGRCxNQUVPLElBQUlELE1BQU0sQ0FBQ0ssT0FBWCxFQUFvQjtBQUN6QkosTUFBQUEsU0FBUyxHQUFHLENBQUMsQ0FBYjtBQUNELEtBRk0sTUFFQTtBQUNMQSxNQUFBQSxTQUFTLEdBQUcsQ0FBWjtBQUNEOztBQUVERixJQUFBQSxHQUFHLENBQUNPLElBQUosQ0FBUyxDQUFDTCxTQUFELEVBQVlELE1BQU0sQ0FBQ08sS0FBbkIsQ0FBVDtBQUNEOztBQUNELFNBQU9SLEdBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8vIFNlZTogaHR0cDovL2NvZGUuZ29vZ2xlLmNvbS9wL2dvb2dsZS1kaWZmLW1hdGNoLXBhdGNoL3dpa2kvQVBJXG5leHBvcnQgZnVuY3Rpb24gY29udmVydENoYW5nZXNUb0RNUChjaGFuZ2VzKSB7XG4gIGxldCByZXQgPSBbXSxcbiAgICAgIGNoYW5nZSxcbiAgICAgIG9wZXJhdGlvbjtcbiAgZm9yIChsZXQgaSA9IDA7IGkgPCBjaGFuZ2VzLmxlbmd0aDsgaSsrKSB7XG4gICAgY2hhbmdlID0gY2hhbmdlc1tpXTtcbiAgICBpZiAoY2hhbmdlLmFkZGVkKSB7XG4gICAgICBvcGVyYXRpb24gPSAxO1xuICAgIH0gZWxzZSBpZiAoY2hhbmdlLnJlbW92ZWQpIHtcbiAgICAgIG9wZXJhdGlvbiA9IC0xO1xuICAgIH0gZWxzZSB7XG4gICAgICBvcGVyYXRpb24gPSAwO1xuICAgIH1cblxuICAgIHJldC5wdXNoKFtvcGVyYXRpb24sIGNoYW5nZS52YWx1ZV0pO1xuICB9XG4gIHJldHVybiByZXQ7XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.convertChangesToXML = convertChangesToXML;\n\n/*istanbul ignore end*/\nfunction convertChangesToXML(changes) {\n var ret = [];\n\n for (var i = 0; i < changes.length; i++) {\n var change = changes[i];\n\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n\n ret.push(escapeHTML(change.value));\n\n if (change.added) {\n ret.push('');\n } else if (change.removed) {\n ret.push('');\n }\n }\n\n return ret.join('');\n}\n\nfunction escapeHTML(s) {\n var n = s;\n n = n.replace(/&/g, '&');\n n = n.replace(//g, '>');\n n = n.replace(/\"/g, '"');\n return n;\n}\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jb252ZXJ0L3htbC5qcyJdLCJuYW1lcyI6WyJjb252ZXJ0Q2hhbmdlc1RvWE1MIiwiY2hhbmdlcyIsInJldCIsImkiLCJsZW5ndGgiLCJjaGFuZ2UiLCJhZGRlZCIsInB1c2giLCJyZW1vdmVkIiwiZXNjYXBlSFRNTCIsInZhbHVlIiwiam9pbiIsInMiLCJuIiwicmVwbGFjZSJdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQU8sU0FBU0EsbUJBQVQsQ0FBNkJDLE9BQTdCLEVBQXNDO0FBQzNDLE1BQUlDLEdBQUcsR0FBRyxFQUFWOztBQUNBLE9BQUssSUFBSUMsQ0FBQyxHQUFHLENBQWIsRUFBZ0JBLENBQUMsR0FBR0YsT0FBTyxDQUFDRyxNQUE1QixFQUFvQ0QsQ0FBQyxFQUFyQyxFQUF5QztBQUN2QyxRQUFJRSxNQUFNLEdBQUdKLE9BQU8sQ0FBQ0UsQ0FBRCxDQUFwQjs7QUFDQSxRQUFJRSxNQUFNLENBQUNDLEtBQVgsRUFBa0I7QUFDaEJKLE1BQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTLE9BQVQ7QUFDRCxLQUZELE1BRU8sSUFBSUYsTUFBTSxDQUFDRyxPQUFYLEVBQW9CO0FBQ3pCTixNQUFBQSxHQUFHLENBQUNLLElBQUosQ0FBUyxPQUFUO0FBQ0Q7O0FBRURMLElBQUFBLEdBQUcsQ0FBQ0ssSUFBSixDQUFTRSxVQUFVLENBQUNKLE1BQU0sQ0FBQ0ssS0FBUixDQUFuQjs7QUFFQSxRQUFJTCxNQUFNLEN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1xuICAgICAgcmV0LnB1c2goJzxkZWw+Jyk7XG4gICAgfVxuXG4gICAgcmV0LnB1c2goZXNjYXBlSFRNTChjaGFuZ2UudmFsdWUpKTtcblxuICAgIGlmIChjaGFuZ2UuYWRkZWQpIHtcbiAgICAgIHJldC5wdXNoKCc8L2lucz4nKTtcbiAgICB9IGVsc2UgaWYgKGNoYW5nZS5yZW1vdmVkKSB7XG4gICAgICByZXQucHVzaCgnPC9kZWw+Jyk7XG4gICAgfVxuICB9XG4gIHJldHVybiByZXQuam9pbignJyk7XG59XG5cbmZ1bmN0aW9uIGVzY2FwZUhUTUwocykge1xuICBsZXQgbiA9IHM7XG4gIG4gPSBuLnJlcGxhY2UoLyYvZywgJyZhbXA7Jyk7XG4gIG4gPSBuLnJlcGxhY2UoLzwvZywgJyZsdDsnKTtcbiAgbiA9IG4ucmVwbGFjZSgvPi9nLCAnJmd0OycpO1xuICBuID0gbi5yZXBsYWNlKC9cIi9nLCAnJnF1b3Q7Jyk7XG5cbiAgcmV0dXJuIG47XG59XG4iXX0=\n","/*istanbul ignore start*/\n\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"Diff\", {\n enumerable: true,\n get: function get() {\n return _base[\"default\"];\n }\n});\nObject.defineProperty(exports, \"diffChars\", {\n enumerable: true,\n get: function get() {\n return _character.diffChars;\n }\n});\nObject.defineProperty(exports, \"diffWords\", {\n enumerable: true,\n get: function get() {\n return _word.diffWords;\n }\n});\nObject.defineProperty(exports, \"diffWordsWithSpace\", {\n enumerable: true,\n get: function get() {\n return _word.diffWordsWithSpace;\n }\n});\nObject.defineProperty(exports, \"diffLines\", {\n enumerable: true,\n get: function get() {\n return _line.diffLines;\n }\n});\nObject.defineProperty(exports, \"diffTrimmedLines\", {\n enumerable: true,\n get: function get() {\n return _line.diffTrimmedLines;\n }\n});\nObject.defineProperty(exports, \"diffSentences\", {\n enumerable: true,\n get: function get() {\n return _sentence.diffSentences;\n }\n});\nObject.defineProperty(exports, \"diffCss\", {\n enumerable: true,\n get: function get() {\n return _css.diffCss;\n }\n});\nObject.defineProperty(exports, \"diffJson\", {\n enumerable: true,\n get: function get() {\n return _json.diffJson;\n }\n});\nObject.defineProperty(exports, \"canonicalize\", {\n enumerable: true,\n get: function get() {\n return _json.canonicalize;\n }\n});\nObject.defineProperty(exports, \"diffArrays\", {\n enumerable: true,\n get: function get() {\n return _array.diffArrays;\n }\n});\nObject.defineProperty(exports, \"applyPatch\", {\n enumerable: true,\n get: function get() {\n return _apply.applyPatch;\n }\n});\nObject.defineProperty(exports, \"applyPatches\", {\n enumerable: true,\n get: function get() {\n return _apply.applyPatches;\n }\n});\nObject.defineProperty(exports, \"parsePatch\", {\n enumerable: true,\n get: function get() {\n return _parse.parsePatch;\n }\n});\nObject.defineProperty(exports, \"merge\", {\n enumerable: true,\n get: function get() {\n return _merge.merge;\n }\n});\nObject.defineProperty(exports, \"structuredPatch\", {\n enumerable: true,\n get: function get() {\n return _create.structuredPatch;\n }\n});\nObject.defineProperty(exports, \"createTwoFilesPatch\", {\n enumerable: true,\n get: function get() {\n return _create.createTwoFilesPatch;\n }\n});\nObject.defineProperty(exports, \"createPatch\", {\n enumerable: true,\n get: function get() {\n return _create.createPatch;\n }\n});\nObject.defineProperty(exports, \"convertChangesToDMP\", {\n enumerable: true,\n get: function get() {\n return _dmp.convertChangesToDMP;\n }\n});\nObject.defineProperty(exports, \"convertChangesToXML\", {\n enumerable: true,\n get: function get() {\n return _xml.convertChangesToXML;\n }\n});\n\n/*istanbul ignore end*/\nvar\n/*istanbul ignore start*/\n_base = _interopRequireDefault(require(\"./diff/base\"))\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_character = require(\"./diff/character\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_word = require(\"./diff/word\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_line = require(\"./diff/line\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_sentence = require(\"./diff/sentence\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_css = require(\"./diff/css\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_json = require(\"./diff/json\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_array = require(\"./diff/array\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_apply = require(\"./patch/apply\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_parse = require(\"./patch/parse\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_merge = require(\"./patch/merge\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_create = require(\"./patch/create\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_dmp = require(\"./convert/dmp\")\n/*istanbul ignore end*/\n;\n\nvar\n/*istanbul ignore start*/\n_xml = require(\"./convert/xml\")\n/*istanbul ignore end*/\n;\n\n/*istanbul ignore start*/ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { \"default\": obj }; }\n\n/*istanbul ignore end*/\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQWdCQTtBQUFBO0FBQUE7QUFBQTtBQUFBOztBQUNBO0FBQUE7QUFBQTtBQUFBO0FBQUE7O0FBQ0E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VydC94bWwnO1xuXG5leHBvcnQge1xuICBEaWZmLFxuXG4gIGRpZmZDaGFycyxcbiAgZGlmZldvcmRzLFxuICBkaWZmV29yZHNXaXRoU3BhY2UsXG4gIGRpZmZMaW5lcyxcbiAgZGlmZlRyaW1tZWRMaW5lcyxcbiAgZGlmZlNlbnRlbmNlcyxcblxuICBkaWZmQ3NzLFxuICBkaWZmSnNvbixcblxuICBkaWZmQXJyYXlzLFxuXG4gIHN0cnVjdHVyZWRQYXRjaCxcbiAgY3JlYXRlVHdvRmlsZXNQYXRjaCxcbiAgY3JlYXRlUGF0Y2gsXG4gIGFwcGx5UGF0Y2gsXG4gIGFwcGx5UGF0Y2hlcyxcbiAgcGFyc2VQYXRjaCxcbiAgbWVyZ2UsXG4gIGNvbnZlcnRDaGFuZ2VzVG9ETVAsXG4gIGNvbnZlcnRDaGFuZ2VzVG9YTUwsXG4gIGNhbm9uaWNhbGl6ZVxufTtcbiJdfQ==\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\nvar inited = false;\nfunction init () {\n inited = true;\n var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\n for (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n }\n\n revLookup['-'.charCodeAt(0)] = 62\n revLookup['_'.charCodeAt(0)] = 63\n}\n\nexport function toByteArray (b64) {\n if (!inited) {\n init();\n }\n var i, j, l, tmp, placeHolders, arr\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // the number of equal signs (place holders)\n // if there are two placeholders, than the two characters before it\n // represent one byte\n // if there is only one, then the three characters before it represent 2 bytes\n // this is just a cheap hack to not do indexOf twice\n placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0\n\n // base64 is 4/3 + up to two characters of the original data\n arr = new Arr(len * 3 / 4 - placeHolders)\n\n // if there are placeholders, only get up to the last complete 4 chars\n l = placeHolders > 0 ? len - 4 : len\n\n var L = 0\n\n for (i = 0, j = 0; i < l; i += 4, j += 3) {\n tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]\n arr[L++] = (tmp >> 16) & 0xFF\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n if (placeHolders === 2) {\n tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[L++] = tmp & 0xFF\n } else if (placeHolders === 1) {\n tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[L++] = (tmp >> 8) & 0xFF\n arr[L++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nexport function fromByteArray (uint8) {\n if (!inited) {\n init();\n }\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var output = ''\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n output += lookup[tmp >> 2]\n output += lookup[(tmp << 4) & 0x3F]\n output += '=='\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + (uint8[len - 1])\n output += lookup[tmp >> 10]\n output += lookup[(tmp >> 4) & 0x3F]\n output += lookup[(tmp << 2) & 0x3F]\n output += '='\n }\n\n parts.push(output)\n\n return parts.join('')\n}\n","\nexport function read (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexport function write (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = nBytes * 8 - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = (value * c - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","var toString = {}.toString;\n\nexport default Array.isArray || function (arr) {\n return toString.call(arr) == '[object Array]';\n};\n","/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh \n * @license MIT\n */\n/* eslint-disable no-proto */\n\n\nimport * as base64 from './base64'\nimport * as ieee754 from './ieee754'\nimport isArray from './isArray'\n\nexport var INSPECT_MAX_BYTES = 50\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Use Object implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * Due to various browser bugs, sometimes the Object implementation will be used even\n * when the browser supports typed arrays.\n *\n * Note:\n *\n * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,\n * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.\n *\n * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.\n *\n * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of\n * incorrect length in some situations.\n\n * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they\n * get the Object implementation, which is slower but behaves correctly.\n */\nBuffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined\n ? global.TYPED_ARRAY_SUPPORT\n : true\n\n/*\n * Export kMaxLength after typed array support is determined.\n */\nvar _kMaxLength = kMaxLength()\nexport {_kMaxLength as kMaxLength};\nfunction typedArraySupport () {\n return true;\n // rollup issues\n // try {\n // var arr = new Uint8Array(1)\n // arr.__proto__ = {\n // __proto__: Uint8Array.prototype,\n // foo: function () { return 42 }\n // }\n // return arr.foo() === 42 && // typed array instances can be augmented\n // typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`\n // arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`\n // } catch (e) {\n // return false\n // }\n}\n\nfunction kMaxLength () {\n return Buffer.TYPED_ARRAY_SUPPORT\n ? 0x7fffffff\n : 0x3fffffff\n}\n\nfunction createBuffer (that, length) {\n if (kMaxLength() < length) {\n throw new RangeError('Invalid typed array length')\n }\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = new Uint8Array(length)\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n if (that === null) {\n that = new Buffer(length)\n }\n that.length = length\n }\n\n return that\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nexport function Buffer (arg, encodingOrOffset, length) {\n if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {\n return new Buffer(arg, encodingOrOffset, length)\n }\n\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new Error(\n 'If encoding is specified then the first argument must be a string'\n )\n }\n return allocUnsafe(this, arg)\n }\n return from(this, arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\n// TODO: Legacy, not needed anymore. Remove in next major version.\nBuffer._augment = function (arr) {\n arr.__proto__ = Buffer.prototype\n return arr\n}\n\nfunction from (that, value, encodingOrOffset, length) {\n if (typeof value === 'number') {\n throw new TypeError('\"value\" argument must not be a number')\n }\n\n if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {\n return fromArrayBuffer(that, value, encodingOrOffset, length)\n }\n\n if (typeof value === 'string') {\n return fromString(that, value, encodingOrOffset)\n }\n\n return fromObject(that, value)\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(null, value, encodingOrOffset, length)\n}\n\nif (Buffer.TYPED_ARRAY_SUPPORT) {\n Buffer.prototype.__proto__ = Uint8Array.prototype\n Buffer.__proto__ = Uint8Array\n if (typeof Symbol !== 'undefined' && Symbol.species &&\n Buffer[Symbol.species] === Buffer) {\n // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97\n // Object.defineProperty(Buffer, Symbol.species, {\n // value: null,\n // configurable: true\n // })\n }\n}\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be a number')\n } else if (size < 0) {\n throw new RangeError('\"size\" argument must not be negative')\n }\n}\n\nfunction alloc (that, size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(that, size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpretted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(that, size).fill(fill, encoding)\n : createBuffer(that, size).fill(fill)\n }\n return createBuffer(that, size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(null, size, fill, encoding)\n}\n\nfunction allocUnsafe (that, size) {\n assertSize(size)\n that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) {\n for (var i = 0; i < size; ++i) {\n that[i] = 0\n }\n }\n return that\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(null, size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(null, size)\n}\n\nfunction fromString (that, string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('\"encoding\" must be a valid string encoding')\n }\n\n var length = byteLength(string, encoding) | 0\n that = createBuffer(that, length)\n\n var actual = that.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n that = that.slice(0, actual)\n }\n\n return that\n}\n\nfunction fromArrayLike (that, array) {\n var length = array.length < 0 ? 0 : checked(array.length) | 0\n that = createBuffer(that, length)\n for (var i = 0; i < length; i += 1) {\n that[i] = array[i] & 255\n }\n return that\n}\n\nfunction fromArrayBuffer (that, array, byteOffset, length) {\n array.byteLength // this throws if `array` is not a valid ArrayBuffer\n\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\\'offset\\' is out of bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\\'length\\' is out of bounds')\n }\n\n if (byteOffset === undefined && length === undefined) {\n array = new Uint8Array(array)\n } else if (length === undefined) {\n array = new Uint8Array(array, byteOffset)\n } else {\n array = new Uint8Array(array, byteOffset, length)\n }\n\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n // Return an augmented `Uint8Array` instance, for best performance\n that = array\n that.__proto__ = Buffer.prototype\n } else {\n // Fallback: Return an object instance of the Buffer class\n that = fromArrayLike(that, array)\n }\n return that\n}\n\nfunction fromObject (that, obj) {\n if (internalIsBuffer(obj)) {\n var len = checked(obj.length) | 0\n that = createBuffer(that, len)\n\n if (that.length === 0) {\n return that\n }\n\n obj.copy(that, 0, 0, len)\n return that\n }\n\n if (obj) {\n if ((typeof ArrayBuffer !== 'undefined' &&\n obj.buffer instanceof ArrayBuffer) || 'length' in obj) {\n if (typeof obj.length !== 'number' || isnan(obj.length)) {\n return createBuffer(that, 0)\n }\n return fromArrayLike(that, obj)\n }\n\n if (obj.type === 'Buffer' && isArray(obj.data)) {\n return fromArrayLike(that, obj.data)\n }\n }\n\n throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')\n}\n\nfunction checked (length) {\n // Note: cannot use `length < kMaxLength()` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= kMaxLength()) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + kMaxLength().toString(16) + ' bytes')\n }\n return length | 0\n}\n\nexport function SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\nBuffer.isBuffer = isBuffer;\nfunction internalIsBuffer (b) {\n return !!(b != null && b._isBuffer)\n}\n\nBuffer.compare = function compare (a, b) {\n if (!internalIsBuffer(a) || !internalIsBuffer(b)) {\n throw new TypeError('Arguments must be Buffers')\n }\n\n if (a === b) return 0\n\n var x = a.length\n var y = b.length\n\n for (var i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n var i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n var buffer = Buffer.allocUnsafe(length)\n var pos = 0\n for (i = 0; i < list.length; ++i) {\n var buf = list[i]\n if (!internalIsBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n buf.copy(buffer, pos)\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (internalIsBuffer(string)) {\n return string.length\n }\n if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&\n (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n string = '' + string\n }\n\n var len = string.length\n if (len === 0) return 0\n\n // Use a for loop to avoid recursion\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n case undefined:\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) return utf8ToBytes(string).length // assume utf8\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n var loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coersion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect\n// Buffer instances.\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n var i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n var len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (var i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n var len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (var i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n var len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (var i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n var length = this.length | 0\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.equals = function equals (b) {\n if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n var str = ''\n var max = INSPECT_MAX_BYTES\n if (this.length > 0) {\n str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')\n if (this.length > max) str += ' ... '\n }\n return ''\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (!internalIsBuffer(target)) {\n throw new TypeError('Argument must be a Buffer')\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n var x = thisEnd - thisStart\n var y = end - start\n var len = Math.min(x, y)\n\n var thisCopy = this.slice(thisStart, thisEnd)\n var targetCopy = target.slice(start, end)\n\n for (var i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (isNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (internalIsBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (Buffer.TYPED_ARRAY_SUPPORT &&\n typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n var indexSize = 1\n var arrLength = arr.length\n var valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n var i\n if (dir) {\n var foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n var found = true\n for (var j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n var remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n // must be an even number of digits\n var strLen = string.length\n if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n for (var i = 0; i < length; ++i) {\n var parsed = parseInt(string.substr(i * 2, 2), 16)\n if (isNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction latin1Write (buf, string, offset, length) {\n return asciiWrite(buf, string, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset | 0\n if (isFinite(length)) {\n length = length | 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n // legacy write(string, encoding, offset, length) - remove in v0.13\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n var remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n var loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n return asciiWrite(this, string, offset, length)\n\n case 'latin1':\n case 'binary':\n return latin1Write(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n var res = []\n\n var i = start\n while (i < end) {\n var firstByte = buf[i]\n var codePoint = null\n var bytesPerSequence = (firstByte > 0xEF) ? 4\n : (firstByte > 0xDF) ? 3\n : (firstByte > 0xBF) ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n var secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nvar MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n var len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n var res = ''\n var i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n var ret = ''\n end = Math.min(buf.length, end)\n\n for (var i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n var len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n var out = ''\n for (var i = start; i < end; ++i) {\n out += toHex(buf[i])\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n var bytes = buf.slice(start, end)\n var res = ''\n for (var i = 0; i < bytes.length; i += 2) {\n res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n var len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n var newBuf\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n newBuf = this.subarray(start, end)\n newBuf.__proto__ = Buffer.prototype\n } else {\n var sliceLen = end - start\n newBuf = new Buffer(sliceLen, undefined)\n for (var i = 0; i < sliceLen; ++i) {\n newBuf[i] = this[i + start]\n }\n }\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n var val = this[offset + --byteLength]\n var mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var val = this[offset]\n var mul = 1\n var i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n var i = byteLength\n var mul = 1\n var val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 2, this.length)\n var val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!internalIsBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var mul = 1\n var i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n byteLength = byteLength | 0\n if (!noAssert) {\n var maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n var i = byteLength - 1\n var mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nfunction objectWriteUInt16 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {\n buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>\n (littleEndian ? i : 1 - i) * 8\n }\n}\n\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nfunction objectWriteUInt32 (buf, value, offset, littleEndian) {\n if (value < 0) value = 0xffffffff + value + 1\n for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {\n buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff\n }\n}\n\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = 0\n var mul = 1\n var sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) {\n var limit = Math.pow(2, 8 * byteLength - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n var i = byteLength - 1\n var mul = 1\n var sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n } else {\n objectWriteUInt16(this, value, offset, true)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n } else {\n objectWriteUInt16(this, value, offset, false)\n }\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n } else {\n objectWriteUInt32(this, value, offset, true)\n }\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset | 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n if (Buffer.TYPED_ARRAY_SUPPORT) {\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n } else {\n objectWriteUInt32(this, value, offset, false)\n }\n return offset + 4\n}\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n var len = end - start\n var i\n\n if (this === target && start < targetStart && targetStart < end) {\n // descending copy from end\n for (i = len - 1; i >= 0; --i) {\n target[i + targetStart] = this[i + start]\n }\n } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {\n // ascending copy from start\n for (i = 0; i < len; ++i) {\n target[i + targetStart] = this[i + start]\n }\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, start + len),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (val.length === 1) {\n var code = val.charCodeAt(0)\n if (code < 256) {\n val = code\n }\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n } else if (typeof val === 'number') {\n val = val & 255\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n var i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n var bytes = internalIsBuffer(val)\n ? val\n : utf8ToBytes(new Buffer(val, encoding).toString())\n var len = bytes.length\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// HELPER FUNCTIONS\n// ================\n\nvar INVALID_BASE64_RE = /[^+\\/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = stringtrim(str).replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction stringtrim (str) {\n if (str.trim) return str.trim()\n return str.replace(/^\\s+|\\s+$/g, '')\n}\n\nfunction toHex (n) {\n if (n < 16) return '0' + n.toString(16)\n return n.toString(16)\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n var codePoint\n var length = string.length\n var leadSurrogate = null\n var bytes = []\n\n for (var i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n var c, hi, lo\n var byteArray = []\n for (var i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n for (var i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\nfunction isnan (val) {\n return val !== val // eslint-disable-line no-self-compare\n}\n\n\n// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence\n// The _isBuffer check is for Safari 5-7 support, because it's missing\n// Object.prototype.constructor. Remove this eventually\nexport function isBuffer(obj) {\n return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj))\n}\n\nfunction isFastBuffer (obj) {\n return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)\n}\n\n// For Node v0.10 support. Remove this eventually.\nfunction isSlowBuffer (obj) {\n return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0))\n}\n","export var browser = true;\n","/*! https://mths.be/he v1.2.0 by @mathias | MIT license */\n;(function(root) {\n\n\t// Detect free variables `exports`.\n\tvar freeExports = typeof exports == 'object' && exports;\n\n\t// Detect free variable `module`.\n\tvar freeModule = typeof module == 'object' && module &&\n\t\tmodule.exports == freeExports && module;\n\n\t// Detect free variable `global`, from Node.js or Browserified code,\n\t// and use it as `root`.\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {\n\t\troot = freeGlobal;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\t// All astral symbols.\n\tvar regexAstralSymbols = /[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]/g;\n\t// All ASCII symbols (not just printable ASCII) except those listed in the\n\t// first column of the overrides table.\n\t// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides\n\tvar regexAsciiWhitelist = /[\\x01-\\x7F]/g;\n\t// All BMP symbols that are not ASCII newlines, printable ASCII symbols, or\n\t// code points listed in the first column of the overrides table on\n\t// https://html.spec.whatwg.org/multipage/syntax.html#table-charref-overrides.\n\tvar regexBmpWhitelist = /[\\x01-\\t\\x0B\\f\\x0E-\\x1F\\x7F\\x81\\x8D\\x8F\\x90\\x9D\\xA0-\\uFFFF]/g;\n\n\tvar regexEncodeNonAscii = /<\\u20D2|=\\u20E5|>\\u20D2|\\u205F\\u200A|\\u219D\\u0338|\\u2202\\u0338|\\u2220\\u20D2|\\u2229\\uFE00|\\u222A\\uFE00|\\u223C\\u20D2|\\u223D\\u0331|\\u223E\\u0333|\\u2242\\u0338|\\u224B\\u0338|\\u224D\\u20D2|\\u224E\\u0338|\\u224F\\u0338|\\u2250\\u0338|\\u2261\\u20E5|\\u2264\\u20D2|\\u2265\\u20D2|\\u2266\\u0338|\\u2267\\u0338|\\u2268\\uFE00|\\u2269\\uFE00|\\u226A\\u0338|\\u226A\\u20D2|\\u226B\\u0338|\\u226B\\u20D2|\\u227F\\u0338|\\u2282\\u20D2|\\u2283\\u20D2|\\u228A\\uFE00|\\u228B\\uFE00|\\u228F\\u0338|\\u2290\\u0338|\\u2293\\uFE00|\\u2294\\uFE00|\\u22B4\\u20D2|\\u22B5\\u20D2|\\u22D8\\u0338|\\u22D9\\u0338|\\u22DA\\uFE00|\\u22DB\\uFE00|\\u22F5\\u0338|\\u22F9\\u0338|\\u2933\\u0338|\\u29CF\\u0338|\\u29D0\\u0338|\\u2A6D\\u0338|\\u2A70\\u0338|\\u2A7D\\u0338|\\u2A7E\\u0338|\\u2AA1\\u0338|\\u2AA2\\u0338|\\u2AAC\\uFE00|\\u2AAD\\uFE00|\\u2AAF\\u0338|\\u2AB0\\u0338|\\u2AC5\\u0338|\\u2AC6\\u0338|\\u2ACB\\uFE00|\\u2ACC\\uFE00|\\u2AFD\\u20E5|[\\xA0-\\u0113\\u0116-\\u0122\\u0124-\\u012B\\u012E-\\u014D\\u0150-\\u017E\\u0192\\u01B5\\u01F5\\u0237\\u02C6\\u02C7\\u02D8-\\u02DD\\u0311\\u0391-\\u03A1\\u03A3-\\u03A9\\u03B1-\\u03C9\\u03D1\\u03D2\\u03D5\\u03D6\\u03DC\\u03DD\\u03F0\\u03F1\\u03F5\\u03F6\\u0401-\\u040C\\u040E-\\u044F\\u0451-\\u045C\\u045E\\u045F\\u2002-\\u2005\\u2007-\\u2010\\u2013-\\u2016\\u2018-\\u201A\\u201C-\\u201E\\u2020-\\u2022\\u2025\\u2026\\u2030-\\u2035\\u2039\\u203A\\u203E\\u2041\\u2043\\u2044\\u204F\\u2057\\u205F-\\u2063\\u20AC\\u20DB\\u20DC\\u2102\\u2105\\u210A-\\u2113\\u2115-\\u211E\\u2122\\u2124\\u2127-\\u2129\\u212C\\u212D\\u212F-\\u2131\\u2133-\\u2138\\u2145-\\u2148\\u2153-\\u215E\\u2190-\\u219B\\u219D-\\u21A7\\u21A9-\\u21AE\\u21B0-\\u21B3\\u21B5-\\u21B7\\u21BA-\\u21DB\\u21DD\\u21E4\\u21E5\\u21F5\\u21FD-\\u2205\\u2207-\\u2209\\u220B\\u220C\\u220F-\\u2214\\u2216-\\u2218\\u221A\\u221D-\\u2238\\u223A-\\u2257\\u2259\\u225A\\u225C\\u225F-\\u2262\\u2264-\\u228B\\u228D-\\u229B\\u229D-\\u22A5\\u22A7-\\u22B0\\u22B2-\\u22BB\\u22BD-\\u22DB\\u22DE-\\u22E3\\u22E6-\\u22F7\\u22F9-\\u22FE\\u2305\\u2306\\u2308-\\u2310\\u2312\\u2313\\u2315\\u2316\\u231C-\\u231F\\u2322\\u2323\\u232D\\u232E\\u2336\\u233D\\u233F\\u237C\\u23B0\\u23B1\\u23B4-\\u23B6\\u23DC-\\u23DF\\u23E2\\u23E7\\u2423\\u24C8\\u2500\\u2502\\u250C\\u2510\\u2514\\u2518\\u251C\\u2524\\u252C\\u2534\\u253C\\u2550-\\u256C\\u2580\\u2584\\u2588\\u2591-\\u2593\\u25A1\\u25AA\\u25AB\\u25AD\\u25AE\\u25B1\\u25B3-\\u25B5\\u25B8\\u25B9\\u25BD-\\u25BF\\u25C2\\u25C3\\u25CA\\u25CB\\u25EC\\u25EF\\u25F8-\\u25FC\\u2605\\u2606\\u260E\\u2640\\u2642\\u2660\\u2663\\u2665\\u2666\\u266A\\u266D-\\u266F\\u2713\\u2717\\u2720\\u2736\\u2758\\u2772\\u2773\\u27C8\\u27C9\\u27E6-\\u27ED\\u27F5-\\u27FA\\u27FC\\u27FF\\u2902-\\u2905\\u290C-\\u2913\\u2916\\u2919-\\u2920\\u2923-\\u292A\\u2933\\u2935-\\u2939\\u293C\\u293D\\u2945\\u2948-\\u294B\\u294E-\\u2976\\u2978\\u2979\\u297B-\\u297F\\u2985\\u2986\\u298B-\\u2996\\u299A\\u299C\\u299D\\u29A4-\\u29B7\\u29B9\\u29BB\\u29BC\\u29BE-\\u29C5\\u29C9\\u29CD-\\u29D0\\u29DC-\\u29DE\\u29E3-\\u29E5\\u29EB\\u29F4\\u29F6\\u2A00-\\u2A02\\u2A04\\u2A06\\u2A0C\\u2A0D\\u2A10-\\u2A17\\u2A22-\\u2A27\\u2A29\\u2A2A\\u2A2D-\\u2A31\\u2A33-\\u2A3C\\u2A3F\\u2A40\\u2A42-\\u2A4D\\u2A50\\u2A53-\\u2A58\\u2A5A-\\u2A5D\\u2A5F\\u2A66\\u2A6A\\u2A6D-\\u2A75\\u2A77-\\u2A9A\\u2A9D-\\u2AA2\\u2AA4-\\u2AB0\\u2AB3-\\u2AC8\\u2ACB\\u2ACC\\u2ACF-\\u2ADB\\u2AE4\\u2AE6-\\u2AE9\\u2AEB-\\u2AF3\\u2AFD\\uFB00-\\uFB04]|\\uD835[\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDCCF\\uDD04\\uDD05\\uDD07-\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDD6B]/g;\n\tvar encodeMap = {'\\xAD':'shy','\\u200C':'zwnj','\\u200D':'zwj','\\u200E':'lrm','\\u2063':'ic','\\u2062':'it','\\u2061':'af','\\u200F':'rlm','\\u200B':'ZeroWidthSpace','\\u2060':'NoBreak','\\u0311':'DownBreve','\\u20DB':'tdot','\\u20DC':'DotDot','\\t':'Tab','\\n':'NewLine','\\u2008':'puncsp','\\u205F':'MediumSpace','\\u2009':'thinsp','\\u200A':'hairsp','\\u2004':'emsp13','\\u2002':'ensp','\\u2005':'emsp14','\\u2003':'emsp','\\u2007':'numsp','\\xA0':'nbsp','\\u205F\\u200A':'ThickSpace','\\u203E':'oline','_':'lowbar','\\u2010':'dash','\\u2013':'ndash','\\u2014':'mdash','\\u2015':'horbar',',':'comma',';':'semi','\\u204F':'bsemi',':':'colon','\\u2A74':'Colone','!':'excl','\\xA1':'iexcl','?':'quest','\\xBF':'iquest','.':'period','\\u2025':'nldr','\\u2026':'mldr','\\xB7':'middot','\\'':'apos','\\u2018':'lsquo','\\u2019':'rsquo','\\u201A':'sbquo','\\u2039':'lsaquo','\\u203A':'rsaquo','\"':'quot','\\u201C':'ldquo','\\u201D':'rdquo','\\u201E':'bdquo','\\xAB':'laquo','\\xBB':'raquo','(':'lpar',')':'rpar','[':'lsqb',']':'rsqb','{':'lcub','}':'rcub','\\u2308':'lceil','\\u2309':'rceil','\\u230A':'lfloor','\\u230B':'rfloor','\\u2985':'lopar','\\u2986':'ropar','\\u298B':'lbrke','\\u298C':'rbrke','\\u298D':'lbrkslu','\\u298E':'rbrksld','\\u298F':'lbrksld','\\u2990':'rbrkslu','\\u2991':'langd','\\u2992':'rangd','\\u2993':'lparlt','\\u2994':'rpargt','\\u2995':'gtlPar','\\u2996':'ltrPar','\\u27E6':'lobrk','\\u27E7':'robrk','\\u27E8':'lang','\\u27E9':'rang','\\u27EA':'Lang','\\u27EB':'Rang','\\u27EC':'loang','\\u27ED':'roang','\\u2772':'lbbrk','\\u2773':'rbbrk','\\u2016':'Vert','\\xA7':'sect','\\xB6':'para','@':'commat','*':'ast','/':'sol','undefined':null,'&':'amp','#':'num','%':'percnt','\\u2030':'permil','\\u2031':'pertenk','\\u2020':'dagger','\\u2021':'Dagger','\\u2022':'bull','\\u2043':'hybull','\\u2032':'prime','\\u2033':'Prime','\\u2034':'tprime','\\u2057':'qprime','\\u2035':'bprime','\\u2041':'caret','`':'grave','\\xB4':'acute','\\u02DC':'tilde','^':'Hat','\\xAF':'macr','\\u02D8':'breve','\\u02D9':'dot','\\xA8':'die','\\u02DA':'ring','\\u02DD':'dblac','\\xB8':'cedil','\\u02DB':'ogon','\\u02C6':'circ','\\u02C7':'caron','\\xB0':'deg','\\xA9':'copy','\\xAE':'reg','\\u2117':'copysr','\\u2118':'wp','\\u211E':'rx','\\u2127':'mho','\\u2129':'iiota','\\u2190':'larr','\\u219A':'nlarr','\\u2192':'rarr','\\u219B':'nrarr','\\u2191':'uarr','\\u2193':'darr','\\u2194':'harr','\\u21AE':'nharr','\\u2195':'varr','\\u2196':'nwarr','\\u2197':'nearr','\\u2198':'searr','\\u2199':'swarr','\\u219D':'rarrw','\\u219D\\u0338':'nrarrw','\\u219E':'Larr','\\u219F':'Uarr','\\u21A0':'Rarr','\\u21A1':'Darr','\\u21A2':'larrtl','\\u21A3':'rarrtl','\\u21A4':'mapstoleft','\\u21A5':'mapstoup','\\u21A6':'map','\\u21A7':'mapstodown','\\u21A9':'larrhk','\\u21AA':'rarrhk','\\u21AB':'larrlp','\\u21AC':'rarrlp','\\u21AD':'harrw','\\u21B0':'lsh','\\u21B1':'rsh','\\u21B2':'ldsh','\\u21B3':'rdsh','\\u21B5':'crarr','\\u21B6':'cularr','\\u21B7':'curarr','\\u21BA':'olarr','\\u21BB':'orarr','\\u21BC':'lharu','\\u21BD':'lhard','\\u21BE':'uharr','\\u21BF':'uharl','\\u21C0':'rharu','\\u21C1':'rhard','\\u21C2':'dharr','\\u21C3':'dharl','\\u21C4':'rlarr','\\u21C5':'udarr','\\u21C6':'lrarr','\\u21C7':'llarr','\\u21C8':'uuarr','\\u21C9':'rrarr','\\u21CA':'ddarr','\\u21CB':'lrhar','\\u21CC':'rlhar','\\u21D0':'lArr','\\u21CD':'nlArr','\\u21D1':'uArr','\\u21D2':'rArr','\\u21CF':'nrArr','\\u21D3':'dArr','\\u21D4':'iff','\\u21CE':'nhArr','\\u21D5':'vArr','\\u21D6':'nwArr','\\u21D7':'neArr','\\u21D8':'seArr','\\u21D9':'swArr','\\u21DA':'lAarr','\\u21DB':'rAarr','\\u21DD':'zigrarr','\\u21E4':'larrb','\\u21E5':'rarrb','\\u21F5':'duarr','\\u21FD':'loarr','\\u21FE':'roarr','\\u21FF':'hoarr','\\u2200':'forall','\\u2201':'comp','\\u2202':'part','\\u2202\\u0338':'npart','\\u2203':'exist','\\u2204':'nexist','\\u2205':'empty','\\u2207':'Del','\\u2208':'in','\\u2209':'notin','\\u220B':'ni','\\u220C':'notni','\\u03F6':'bepsi','\\u220F':'prod','\\u2210':'coprod','\\u2211':'sum','+':'plus','\\xB1':'pm','\\xF7':'div','\\xD7':'times','<':'lt','\\u226E':'nlt','<\\u20D2':'nvlt','=':'equals','\\u2260':'ne','=\\u20E5':'bne','\\u2A75':'Equal','>':'gt','\\u226F':'ngt','>\\u20D2':'nvgt','\\xAC':'not','|':'vert','\\xA6':'brvbar','\\u2212':'minus','\\u2213':'mp','\\u2214':'plusdo','\\u2044':'frasl','\\u2216':'setmn','\\u2217':'lowast','\\u2218':'compfn','\\u221A':'Sqrt','\\u221D':'prop','\\u221E':'infin','\\u221F':'angrt','\\u2220':'ang','\\u2220\\u20D2':'nang','\\u2221':'angmsd','\\u2222':'angsph','\\u2223':'mid','\\u2224':'nmid','\\u2225':'par','\\u2226':'npar','\\u2227':'and','\\u2228':'or','\\u2229':'cap','\\u2229\\uFE00':'caps','\\u222A':'cup','\\u222A\\uFE00':'cups','\\u222B':'int','\\u222C':'Int','\\u222D':'tint','\\u2A0C':'qint','\\u222E':'oint','\\u222F':'Conint','\\u2230':'Cconint','\\u2231':'cwint','\\u2232':'cwconint','\\u2233':'awconint','\\u2234':'there4','\\u2235':'becaus','\\u2236':'ratio','\\u2237':'Colon','\\u2238':'minusd','\\u223A':'mDDot','\\u223B':'homtht','\\u223C':'sim','\\u2241':'nsim','\\u223C\\u20D2':'nvsim','\\u223D':'bsim','\\u223D\\u0331':'race','\\u223E':'ac','\\u223E\\u0333':'acE','\\u223F':'acd','\\u2240':'wr','\\u2242':'esim','\\u2242\\u0338':'nesim','\\u2243':'sime','\\u2244':'nsime','\\u2245':'cong','\\u2247':'ncong','\\u2246':'simne','\\u2248':'ap','\\u2249':'nap','\\u224A':'ape','\\u224B':'apid','\\u224B\\u0338':'napid','\\u224C':'bcong','\\u224D':'CupCap','\\u226D':'NotCupCap','\\u224D\\u20D2':'nvap','\\u224E':'bump','\\u224E\\u0338':'nbump','\\u224F':'bumpe','\\u224F\\u0338':'nbumpe','\\u2250':'doteq','\\u2250\\u0338':'nedot','\\u2251':'eDot','\\u2252':'efDot','\\u2253':'erDot','\\u2254':'colone','\\u2255':'ecolon','\\u2256':'ecir','\\u2257':'cire','\\u2259':'wedgeq','\\u225A':'veeeq','\\u225C':'trie','\\u225F':'equest','\\u2261':'equiv','\\u2262':'nequiv','\\u2261\\u20E5':'bnequiv','\\u2264':'le','\\u2270':'nle','\\u2264\\u20D2':'nvle','\\u2265':'ge','\\u2271':'nge','\\u2265\\u20D2':'nvge','\\u2266':'lE','\\u2266\\u0338':'nlE','\\u2267':'gE','\\u2267\\u0338':'ngE','\\u2268\\uFE00':'lvnE','\\u2268':'lnE','\\u2269':'gnE','\\u2269\\uFE00':'gvnE','\\u226A':'ll','\\u226A\\u0338':'nLtv','\\u226A\\u20D2':'nLt','\\u226B':'gg','\\u226B\\u0338':'nGtv','\\u226B\\u20D2':'nGt','\\u226C':'twixt','\\u2272':'lsim','\\u2274':'nlsim','\\u2273':'gsim','\\u2275':'ngsim','\\u2276':'lg','\\u2278':'ntlg','\\u2277':'gl','\\u2279':'ntgl','\\u227A':'pr','\\u2280':'npr','\\u227B':'sc','\\u2281':'nsc','\\u227C':'prcue','\\u22E0':'nprcue','\\u227D':'sccue','\\u22E1':'nsccue','\\u227E':'prsim','\\u227F':'scsim','\\u227F\\u0338':'NotSucceedsTilde','\\u2282':'sub','\\u2284':'nsub','\\u2282\\u20D2':'vnsub','\\u2283':'sup','\\u2285':'nsup','\\u2283\\u20D2':'vnsup','\\u2286':'sube','\\u2288':'nsube','\\u2287':'supe','\\u2289':'nsupe','\\u228A\\uFE00':'vsubne','\\u228A':'subne','\\u228B\\uFE00':'vsupne','\\u228B':'supne','\\u228D':'cupdot','\\u228E':'uplus','\\u228F':'sqsub','\\u228F\\u0338':'NotSquareSubset','\\u2290':'sqsup','\\u2290\\u0338':'NotSquareSuperset','\\u2291':'sqsube','\\u22E2':'nsqsube','\\u2292':'sqsupe','\\u22E3':'nsqsupe','\\u2293':'sqcap','\\u2293\\uFE00':'sqcaps','\\u2294':'sqcup','\\u2294\\uFE00':'sqcups','\\u2295':'oplus','\\u2296':'ominus','\\u2297':'otimes','\\u2298':'osol','\\u2299':'odot','\\u229A':'ocir','\\u229B':'oast','\\u229D':'odash','\\u229E':'plusb','\\u229F':'minusb','\\u22A0':'timesb','\\u22A1':'sdotb','\\u22A2':'vdash','\\u22AC':'nvdash','\\u22A3':'dashv','\\u22A4':'top','\\u22A5':'bot','\\u22A7':'models','\\u22A8':'vDash','\\u22AD':'nvDash','\\u22A9':'Vdash','\\u22AE':'nVdash','\\u22AA':'Vvdash','\\u22AB':'VDash','\\u22AF':'nVDash','\\u22B0':'prurel','\\u22B2':'vltri','\\u22EA':'nltri','\\u22B3':'vrtri','\\u22EB':'nrtri','\\u22B4':'ltrie','\\u22EC':'nltrie','\\u22B4\\u20D2':'nvltrie','\\u22B5':'rtrie','\\u22ED':'nrtrie','\\u22B5\\u20D2':'nvrtrie','\\u22B6':'origof','\\u22B7':'imof','\\u22B8':'mumap','\\u22B9':'hercon','\\u22BA':'intcal','\\u22BB':'veebar','\\u22BD':'barvee','\\u22BE':'angrtvb','\\u22BF':'lrtri','\\u22C0':'Wedge','\\u22C1':'Vee','\\u22C2':'xcap','\\u22C3':'xcup','\\u22C4':'diam','\\u22C5':'sdot','\\u22C6':'Star','\\u22C7':'divonx','\\u22C8':'bowtie','\\u22C9':'ltimes','\\u22CA':'rtimes','\\u22CB':'lthree','\\u22CC':'rthree','\\u22CD':'bsime','\\u22CE':'cuvee','\\u22CF':'cuwed','\\u22D0':'Sub','\\u22D1':'Sup','\\u22D2':'Cap','\\u22D3':'Cup','\\u22D4':'fork','\\u22D5':'epar','\\u22D6':'ltdot','\\u22D7':'gtdot','\\u22D8':'Ll','\\u22D8\\u0338':'nLl','\\u22D9':'Gg','\\u22D9\\u0338':'nGg','\\u22DA\\uFE00':'lesg','\\u22DA':'leg','\\u22DB':'gel','\\u22DB\\uFE00':'gesl','\\u22DE':'cuepr','\\u22DF':'cuesc','\\u22E6':'lnsim','\\u22E7':'gnsim','\\u22E8':'prnsim','\\u22E9':'scnsim','\\u22EE':'vellip','\\u22EF':'ctdot','\\u22F0':'utdot','\\u22F1':'dtdot','\\u22F2':'disin','\\u22F3':'isinsv','\\u22F4':'isins','\\u22F5':'isindot','\\u22F5\\u0338':'notindot','\\u22F6':'notinvc','\\u22F7':'notinvb','\\u22F9':'isinE','\\u22F9\\u0338':'notinE','\\u22FA':'nisd','\\u22FB':'xnis','\\u22FC':'nis','\\u22FD':'notnivc','\\u22FE':'notnivb','\\u2305':'barwed','\\u2306':'Barwed','\\u230C':'drcrop','\\u230D':'dlcrop','\\u230E':'urcrop','\\u230F':'ulcrop','\\u2310':'bnot','\\u2312':'profline','\\u2313':'profsurf','\\u2315':'telrec','\\u2316':'target','\\u231C':'ulcorn','\\u231D':'urcorn','\\u231E':'dlcorn','\\u231F':'drcorn','\\u2322':'frown','\\u2323':'smile','\\u232D':'cylcty','\\u232E':'profalar','\\u2336':'topbot','\\u233D':'ovbar','\\u233F':'solbar','\\u237C':'angzarr','\\u23B0':'lmoust','\\u23B1':'rmoust','\\u23B4':'tbrk','\\u23B5':'bbrk','\\u23B6':'bbrktbrk','\\u23DC':'OverParenthesis','\\u23DD':'UnderParenthesis','\\u23DE':'OverBrace','\\u23DF':'UnderBrace','\\u23E2':'trpezium','\\u23E7':'elinters','\\u2423':'blank','\\u2500':'boxh','\\u2502':'boxv','\\u250C':'boxdr','\\u2510':'boxdl','\\u2514':'boxur','\\u2518':'boxul','\\u251C':'boxvr','\\u2524':'boxvl','\\u252C':'boxhd','\\u2534':'boxhu','\\u253C':'boxvh','\\u2550':'boxH','\\u2551':'boxV','\\u2552':'boxdR','\\u2553':'boxDr','\\u2554':'boxDR','\\u2555':'boxdL','\\u2556':'boxDl','\\u2557':'boxDL','\\u2558':'boxuR','\\u2559':'boxUr','\\u255A':'boxUR','\\u255B':'boxuL','\\u255C':'boxUl','\\u255D':'boxUL','\\u255E':'boxvR','\\u255F':'boxVr','\\u2560':'boxVR','\\u2561':'boxvL','\\u2562':'boxVl','\\u2563':'boxVL','\\u2564':'boxHd','\\u2565':'boxhD','\\u2566':'boxHD','\\u2567':'boxHu','\\u2568':'boxhU','\\u2569':'boxHU','\\u256A':'boxvH','\\u256B':'boxVh','\\u256C':'boxVH','\\u2580':'uhblk','\\u2584':'lhblk','\\u2588':'block','\\u2591':'blk14','\\u2592':'blk12','\\u2593':'blk34','\\u25A1':'squ','\\u25AA':'squf','\\u25AB':'EmptyVerySmallSquare','\\u25AD':'rect','\\u25AE':'marker','\\u25B1':'fltns','\\u25B3':'xutri','\\u25B4':'utrif','\\u25B5':'utri','\\u25B8':'rtrif','\\u25B9':'rtri','\\u25BD':'xdtri','\\u25BE':'dtrif','\\u25BF':'dtri','\\u25C2':'ltrif','\\u25C3':'ltri','\\u25CA':'loz','\\u25CB':'cir','\\u25EC':'tridot','\\u25EF':'xcirc','\\u25F8':'ultri','\\u25F9':'urtri','\\u25FA':'lltri','\\u25FB':'EmptySmallSquare','\\u25FC':'FilledSmallSquare','\\u2605':'starf','\\u2606':'star','\\u260E':'phone','\\u2640':'female','\\u2642':'male','\\u2660':'spades','\\u2663':'clubs','\\u2665':'hearts','\\u2666':'diams','\\u266A':'sung','\\u2713':'check','\\u2717':'cross','\\u2720':'malt','\\u2736':'sext','\\u2758':'VerticalSeparator','\\u27C8':'bsolhsub','\\u27C9':'suphsol','\\u27F5':'xlarr','\\u27F6':'xrarr','\\u27F7':'xharr','\\u27F8':'xlArr','\\u27F9':'xrArr','\\u27FA':'xhArr','\\u27FC':'xmap','\\u27FF':'dzigrarr','\\u2902':'nvlArr','\\u2903':'nvrArr','\\u2904':'nvHarr','\\u2905':'Map','\\u290C':'lbarr','\\u290D':'rbarr','\\u290E':'lBarr','\\u290F':'rBarr','\\u2910':'RBarr','\\u2911':'DDotrahd','\\u2912':'UpArrowBar','\\u2913':'DownArrowBar','\\u2916':'Rarrtl','\\u2919':'latail','\\u291A':'ratail','\\u291B':'lAtail','\\u291C':'rAtail','\\u291D':'larrfs','\\u291E':'rarrfs','\\u291F':'larrbfs','\\u2920':'rarrbfs','\\u2923':'nwarhk','\\u2924':'nearhk','\\u2925':'searhk','\\u2926':'swarhk','\\u2927':'nwnear','\\u2928':'toea','\\u2929':'tosa','\\u292A':'swnwar','\\u2933':'rarrc','\\u2933\\u0338':'nrarrc','\\u2935':'cudarrr','\\u2936':'ldca','\\u2937':'rdca','\\u2938':'cudarrl','\\u2939':'larrpl','\\u293C':'curarrm','\\u293D':'cularrp','\\u2945':'rarrpl','\\u2948':'harrcir','\\u2949':'Uarrocir','\\u294A':'lurdshar','\\u294B':'ldrushar','\\u294E':'LeftRightVector','\\u294F':'RightUpDownVector','\\u2950':'DownLeftRightVector','\\u2951':'LeftUpDownVector','\\u2952':'LeftVectorBar','\\u2953':'RightVectorBar','\\u2954':'RightUpVectorBar','\\u2955':'RightDownVectorBar','\\u2956':'DownLeftVectorBar','\\u2957':'DownRightVectorBar','\\u2958':'LeftUpVectorBar','\\u2959':'LeftDownVectorBar','\\u295A':'LeftTeeVector','\\u295B':'RightTeeVector','\\u295C':'RightUpTeeVector','\\u295D':'RightDownTeeVector','\\u295E':'DownLeftTeeVector','\\u295F':'DownRightTeeVector','\\u2960':'LeftUpTeeVector','\\u2961':'LeftDownTeeVector','\\u2962':'lHar','\\u2963':'uHar','\\u2964':'rHar','\\u2965':'dHar','\\u2966':'luruhar','\\u2967':'ldrdhar','\\u2968':'ruluhar','\\u2969':'rdldhar','\\u296A':'lharul','\\u296B':'llhard','\\u296C':'rharul','\\u296D':'lrhard','\\u296E':'udhar','\\u296F':'duhar','\\u2970':'RoundImplies','\\u2971':'erarr','\\u2972':'simrarr','\\u2973':'larrsim','\\u2974':'rarrsim','\\u2975':'rarrap','\\u2976':'ltlarr','\\u2978':'gtrarr','\\u2979':'subrarr','\\u297B':'suplarr','\\u297C':'lfisht','\\u297D':'rfisht','\\u297E':'ufisht','\\u297F':'dfisht','\\u299A':'vzigzag','\\u299C':'vangrt','\\u299D':'angrtvbd','\\u29A4':'ange','\\u29A5':'range','\\u29A6':'dwangle','\\u29A7':'uwangle','\\u29A8':'angmsdaa','\\u29A9':'angmsdab','\\u29AA':'angmsdac','\\u29AB':'angmsdad','\\u29AC':'angmsdae','\\u29AD':'angmsdaf','\\u29AE':'angmsdag','\\u29AF':'angmsdah','\\u29B0':'bemptyv','\\u29B1':'demptyv','\\u29B2':'cemptyv','\\u29B3':'raemptyv','\\u29B4':'laemptyv','\\u29B5':'ohbar','\\u29B6':'omid','\\u29B7':'opar','\\u29B9':'operp','\\u29BB':'olcross','\\u29BC':'odsold','\\u29BE':'olcir','\\u29BF':'ofcir','\\u29C0':'olt','\\u29C1':'ogt','\\u29C2':'cirscir','\\u29C3':'cirE','\\u29C4':'solb','\\u29C5':'bsolb','\\u29C9':'boxbox','\\u29CD':'trisb','\\u29CE':'rtriltri','\\u29CF':'LeftTriangleBar','\\u29CF\\u0338':'NotLeftTriangleBar','\\u29D0':'RightTriangleBar','\\u29D0\\u0338':'NotRightTriangleBar','\\u29DC':'iinfin','\\u29DD':'infintie','\\u29DE':'nvinfin','\\u29E3':'eparsl','\\u29E4':'smeparsl','\\u29E5':'eqvparsl','\\u29EB':'lozf','\\u29F4':'RuleDelayed','\\u29F6':'dsol','\\u2A00':'xodot','\\u2A01':'xoplus','\\u2A02':'xotime','\\u2A04':'xuplus','\\u2A06':'xsqcup','\\u2A0D':'fpartint','\\u2A10':'cirfnint','\\u2A11':'awint','\\u2A12':'rppolint','\\u2A13':'scpolint','\\u2A14':'npolint','\\u2A15':'pointint','\\u2A16':'quatint','\\u2A17':'intlarhk','\\u2A22':'pluscir','\\u2A23':'plusacir','\\u2A24':'simplus','\\u2A25':'plusdu','\\u2A26':'plussim','\\u2A27':'plustwo','\\u2A29':'mcomma','\\u2A2A':'minusdu','\\u2A2D':'loplus','\\u2A2E':'roplus','\\u2A2F':'Cross','\\u2A30':'timesd','\\u2A31':'timesbar','\\u2A33':'smashp','\\u2A34':'lotimes','\\u2A35':'rotimes','\\u2A36':'otimesas','\\u2A37':'Otimes','\\u2A38':'odiv','\\u2A39':'triplus','\\u2A3A':'triminus','\\u2A3B':'tritime','\\u2A3C':'iprod','\\u2A3F':'amalg','\\u2A40':'capdot','\\u2A42':'ncup','\\u2A43':'ncap','\\u2A44':'capand','\\u2A45':'cupor','\\u2A46':'cupcap','\\u2A47':'capcup','\\u2A48':'cupbrcap','\\u2A49':'capbrcup','\\u2A4A':'cupcup','\\u2A4B':'capcap','\\u2A4C':'ccups','\\u2A4D':'ccaps','\\u2A50':'ccupssm','\\u2A53':'And','\\u2A54':'Or','\\u2A55':'andand','\\u2A56':'oror','\\u2A57':'orslope','\\u2A58':'andslope','\\u2A5A':'andv','\\u2A5B':'orv','\\u2A5C':'andd','\\u2A5D':'ord','\\u2A5F':'wedbar','\\u2A66':'sdote','\\u2A6A':'simdot','\\u2A6D':'congdot','\\u2A6D\\u0338':'ncongdot','\\u2A6E':'easter','\\u2A6F':'apacir','\\u2A70':'apE','\\u2A70\\u0338':'napE','\\u2A71':'eplus','\\u2A72':'pluse','\\u2A73':'Esim','\\u2A77':'eDDot','\\u2A78':'equivDD','\\u2A79':'ltcir','\\u2A7A':'gtcir','\\u2A7B':'ltquest','\\u2A7C':'gtquest','\\u2A7D':'les','\\u2A7D\\u0338':'nles','\\u2A7E':'ges','\\u2A7E\\u0338':'nges','\\u2A7F':'lesdot','\\u2A80':'gesdot','\\u2A81':'lesdoto','\\u2A82':'gesdoto','\\u2A83':'lesdotor','\\u2A84':'gesdotol','\\u2A85':'lap','\\u2A86':'gap','\\u2A87':'lne','\\u2A88':'gne','\\u2A89':'lnap','\\u2A8A':'gnap','\\u2A8B':'lEg','\\u2A8C':'gEl','\\u2A8D':'lsime','\\u2A8E':'gsime','\\u2A8F':'lsimg','\\u2A90':'gsiml','\\u2A91':'lgE','\\u2A92':'glE','\\u2A93':'lesges','\\u2A94':'gesles','\\u2A95':'els','\\u2A96':'egs','\\u2A97':'elsdot','\\u2A98':'egsdot','\\u2A99':'el','\\u2A9A':'eg','\\u2A9D':'siml','\\u2A9E':'simg','\\u2A9F':'simlE','\\u2AA0':'simgE','\\u2AA1':'LessLess','\\u2AA1\\u0338':'NotNestedLessLess','\\u2AA2':'GreaterGreater','\\u2AA2\\u0338':'NotNestedGreaterGreater','\\u2AA4':'glj','\\u2AA5':'gla','\\u2AA6':'ltcc','\\u2AA7':'gtcc','\\u2AA8':'lescc','\\u2AA9':'gescc','\\u2AAA':'smt','\\u2AAB':'lat','\\u2AAC':'smte','\\u2AAC\\uFE00':'smtes','\\u2AAD':'late','\\u2AAD\\uFE00':'lates','\\u2AAE':'bumpE','\\u2AAF':'pre','\\u2AAF\\u0338':'npre','\\u2AB0':'sce','\\u2AB0\\u0338':'nsce','\\u2AB3':'prE','\\u2AB4':'scE','\\u2AB5':'prnE','\\u2AB6':'scnE','\\u2AB7':'prap','\\u2AB8':'scap','\\u2AB9':'prnap','\\u2ABA':'scnap','\\u2ABB':'Pr','\\u2ABC':'Sc','\\u2ABD':'subdot','\\u2ABE':'supdot','\\u2ABF':'subplus','\\u2AC0':'supplus','\\u2AC1':'submult','\\u2AC2':'supmult','\\u2AC3':'subedot','\\u2AC4':'supedot','\\u2AC5':'subE','\\u2AC5\\u0338':'nsubE','\\u2AC6':'supE','\\u2AC6\\u0338':'nsupE','\\u2AC7':'subsim','\\u2AC8':'supsim','\\u2ACB\\uFE00':'vsubnE','\\u2ACB':'subnE','\\u2ACC\\uFE00':'vsupnE','\\u2ACC':'supnE','\\u2ACF':'csub','\\u2AD0':'csup','\\u2AD1':'csube','\\u2AD2':'csupe','\\u2AD3':'subsup','\\u2AD4':'supsub','\\u2AD5':'subsub','\\u2AD6':'supsup','\\u2AD7':'suphsub','\\u2AD8':'supdsub','\\u2AD9':'forkv','\\u2ADA':'topfork','\\u2ADB':'mlcp','\\u2AE4':'Dashv','\\u2AE6':'Vdashl','\\u2AE7':'Barv','\\u2AE8':'vBar','\\u2AE9':'vBarv','\\u2AEB':'Vbar','\\u2AEC':'Not','\\u2AED':'bNot','\\u2AEE':'rnmid','\\u2AEF':'cirmid','\\u2AF0':'midcir','\\u2AF1':'topcir','\\u2AF2':'nhpar','\\u2AF3':'parsim','\\u2AFD':'parsl','\\u2AFD\\u20E5':'nparsl','\\u266D':'flat','\\u266E':'natur','\\u266F':'sharp','\\xA4':'curren','\\xA2':'cent','$':'dollar','\\xA3':'pound','\\xA5':'yen','\\u20AC':'euro','\\xB9':'sup1','\\xBD':'half','\\u2153':'frac13','\\xBC':'frac14','\\u2155':'frac15','\\u2159':'frac16','\\u215B':'frac18','\\xB2':'sup2','\\u2154':'frac23','\\u2156':'frac25','\\xB3':'sup3','\\xBE':'frac34','\\u2157':'frac35','\\u215C':'frac38','\\u2158':'frac45','\\u215A':'frac56','\\u215D':'frac58','\\u215E':'frac78','\\uD835\\uDCB6':'ascr','\\uD835\\uDD52':'aopf','\\uD835\\uDD1E':'afr','\\uD835\\uDD38':'Aopf','\\uD835\\uDD04':'Afr','\\uD835\\uDC9C':'Ascr','\\xAA':'ordf','\\xE1':'aacute','\\xC1':'Aacute','\\xE0':'agrave','\\xC0':'Agrave','\\u0103':'abreve','\\u0102':'Abreve','\\xE2':'acirc','\\xC2':'Acirc','\\xE5':'aring','\\xC5':'angst','\\xE4':'auml','\\xC4':'Auml','\\xE3':'atilde','\\xC3':'Atilde','\\u0105':'aogon','\\u0104':'Aogon','\\u0101':'amacr','\\u0100':'Amacr','\\xE6':'aelig','\\xC6':'AElig','\\uD835\\uDCB7':'bscr','\\uD835\\uDD53':'bopf','\\uD835\\uDD1F':'bfr','\\uD835\\uDD39':'Bopf','\\u212C':'Bscr','\\uD835\\uDD05':'Bfr','\\uD835\\uDD20':'cfr','\\uD835\\uDCB8':'cscr','\\uD835\\uDD54':'copf','\\u212D':'Cfr','\\uD835\\uDC9E':'Cscr','\\u2102':'Copf','\\u0107':'cacute','\\u0106':'Cacute','\\u0109':'ccirc','\\u0108':'Ccirc','\\u010D':'ccaron','\\u010C':'Ccaron','\\u010B':'cdot','\\u010A':'Cdot','\\xE7':'ccedil','\\xC7':'Ccedil','\\u2105':'incare','\\uD835\\uDD21':'dfr','\\u2146':'dd','\\uD835\\uDD55':'dopf','\\uD835\\uDCB9':'dscr','\\uD835\\uDC9F':'Dscr','\\uD835\\uDD07':'Dfr','\\u2145':'DD','\\uD835\\uDD3B':'Dopf','\\u010F':'dcaron','\\u010E':'Dcaron','\\u0111':'dstrok','\\u0110':'Dstrok','\\xF0':'eth','\\xD0':'ETH','\\u2147':'ee','\\u212F':'escr','\\uD835\\uDD22':'efr','\\uD835\\uDD56':'eopf','\\u2130':'Escr','\\uD835\\uDD08':'Efr','\\uD835\\uDD3C':'Eopf','\\xE9':'eacute','\\xC9':'Eacute','\\xE8':'egrave','\\xC8':'Egrave','\\xEA':'ecirc','\\xCA':'Ecirc','\\u011B':'ecaron','\\u011A':'Ecaron','\\xEB':'euml','\\xCB':'Euml','\\u0117':'edot','\\u0116':'Edot','\\u0119':'eogon','\\u0118':'Eogon','\\u0113':'emacr','\\u0112':'Emacr','\\uD835\\uDD23':'ffr','\\uD835\\uDD57':'fopf','\\uD835\\uDCBB':'fscr','\\uD835\\uDD09':'Ffr','\\uD835\\uDD3D':'Fopf','\\u2131':'Fscr','\\uFB00':'fflig','\\uFB03':'ffilig','\\uFB04':'ffllig','\\uFB01':'filig','fj':'fjlig','\\uFB02':'fllig','\\u0192':'fnof','\\u210A':'gscr','\\uD835\\uDD58':'gopf','\\uD835\\uDD24':'gfr','\\uD835\\uDCA2':'Gscr','\\uD835\\uDD3E':'Gopf','\\uD835\\uDD0A':'Gfr','\\u01F5':'gacute','\\u011F':'gbreve','\\u011E':'Gbreve','\\u011D':'gcirc','\\u011C':'Gcirc','\\u0121':'gdot','\\u0120':'Gdot','\\u0122':'Gcedil','\\uD835\\uDD25':'hfr','\\u210E':'planckh','\\uD835\\uDCBD':'hscr','\\uD835\\uDD59':'hopf','\\u210B':'Hscr','\\u210C':'Hfr','\\u210D':'Hopf','\\u0125':'hcirc','\\u0124':'Hcirc','\\u210F':'hbar','\\u0127':'hstrok','\\u0126':'Hstrok','\\uD835\\uDD5A':'iopf','\\uD835\\uDD26':'ifr','\\uD835\\uDCBE':'iscr','\\u2148':'ii','\\uD835\\uDD40':'Iopf','\\u2110':'Iscr','\\u2111':'Im','\\xED':'iacute','\\xCD':'Iacute','\\xEC':'igrave','\\xCC':'Igrave','\\xEE':'icirc','\\xCE':'Icirc','\\xEF':'iuml','\\xCF':'Iuml','\\u0129':'itilde','\\u0128':'Itilde','\\u0130':'Idot','\\u012F':'iogon','\\u012E':'Iogon','\\u012B':'imacr','\\u012A':'Imacr','\\u0133':'ijlig','\\u0132':'IJlig','\\u0131':'imath','\\uD835\\uDCBF':'jscr','\\uD835\\uDD5B':'jopf','\\uD835\\uDD27':'jfr','\\uD835\\uDCA5':'Jscr','\\uD835\\uDD0D':'Jfr','\\uD835\\uDD41':'Jopf','\\u0135':'jcirc','\\u0134':'Jcirc','\\u0237':'jmath','\\uD835\\uDD5C':'kopf','\\uD835\\uDCC0':'kscr','\\uD835\\uDD28':'kfr','\\uD835\\uDCA6':'Kscr','\\uD835\\uDD42':'Kopf','\\uD835\\uDD0E':'Kfr','\\u0137':'kcedil','\\u0136':'Kcedil','\\uD835\\uDD29':'lfr','\\uD835\\uDCC1':'lscr','\\u2113':'ell','\\uD835\\uDD5D':'lopf','\\u2112':'Lscr','\\uD835\\uDD0F':'Lfr','\\uD835\\uDD43':'Lopf','\\u013A':'lacute','\\u0139':'Lacute','\\u013E':'lcaron','\\u013D':'Lcaron','\\u013C':'lcedil','\\u013B':'Lcedil','\\u0142':'lstrok','\\u0141':'Lstrok','\\u0140':'lmidot','\\u013F':'Lmidot','\\uD835\\uDD2A':'mfr','\\uD835\\uDD5E':'mopf','\\uD835\\uDCC2':'mscr','\\uD835\\uDD10':'Mfr','\\uD835\\uDD44':'Mopf','\\u2133':'Mscr','\\uD835\\uDD2B':'nfr','\\uD835\\uDD5F':'nopf','\\uD835\\uDCC3':'nscr','\\u2115':'Nopf','\\uD835\\uDCA9':'Nscr','\\uD835\\uDD11':'Nfr','\\u0144':'nacute','\\u0143':'Nacute','\\u0148':'ncaron','\\u0147':'Ncaron','\\xF1':'ntilde','\\xD1':'Ntilde','\\u0146':'ncedil','\\u0145':'Ncedil','\\u2116':'numero','\\u014B':'eng','\\u014A':'ENG','\\uD835\\uDD60':'oopf','\\uD835\\uDD2C':'ofr','\\u2134':'oscr','\\uD835\\uDCAA':'Oscr','\\uD835\\uDD12':'Ofr','\\uD835\\uDD46':'Oopf','\\xBA':'ordm','\\xF3':'oacute','\\xD3':'Oacute','\\xF2':'ograve','\\xD2':'Ograve','\\xF4':'ocirc','\\xD4':'Ocirc','\\xF6':'ouml','\\xD6':'Ouml','\\u0151':'odblac','\\u0150':'Odblac','\\xF5':'otilde','\\xD5':'Otilde','\\xF8':'oslash','\\xD8':'Oslash','\\u014D':'omacr','\\u014C':'Omacr','\\u0153':'oelig','\\u0152':'OElig','\\uD835\\uDD2D':'pfr','\\uD835\\uDCC5':'pscr','\\uD835\\uDD61':'popf','\\u2119':'Popf','\\uD835\\uDD13':'Pfr','\\uD835\\uDCAB':'Pscr','\\uD835\\uDD62':'qopf','\\uD835\\uDD2E':'qfr','\\uD835\\uDCC6':'qscr','\\uD835\\uDCAC':'Qscr','\\uD835\\uDD14':'Qfr','\\u211A':'Qopf','\\u0138':'kgreen','\\uD835\\uDD2F':'rfr','\\uD835\\uDD63':'ropf','\\uD835\\uDCC7':'rscr','\\u211B':'Rscr','\\u211C':'Re','\\u211D':'Ropf','\\u0155':'racute','\\u0154':'Racute','\\u0159':'rcaron','\\u0158':'Rcaron','\\u0157':'rcedil','\\u0156':'Rcedil','\\uD835\\uDD64':'sopf','\\uD835\\uDCC8':'sscr','\\uD835\\uDD30':'sfr','\\uD835\\uDD4A':'Sopf','\\uD835\\uDD16':'Sfr','\\uD835\\uDCAE':'Sscr','\\u24C8':'oS','\\u015B':'sacute','\\u015A':'Sacute','\\u015D':'scirc','\\u015C':'Scirc','\\u0161':'scaron','\\u0160':'Scaron','\\u015F':'scedil','\\u015E':'Scedil','\\xDF':'szlig','\\uD835\\uDD31':'tfr','\\uD835\\uDCC9':'tscr','\\uD835\\uDD65':'topf','\\uD835\\uDCAF':'Tscr','\\uD835\\uDD17':'Tfr','\\uD835\\uDD4B':'Topf','\\u0165':'tcaron','\\u0164':'Tcaron','\\u0163':'tcedil','\\u0162':'Tcedil','\\u2122':'trade','\\u0167':'tstrok','\\u0166':'Tstrok','\\uD835\\uDCCA':'uscr','\\uD835\\uDD66':'uopf','\\uD835\\uDD32':'ufr','\\uD835\\uDD4C':'Uopf','\\uD835\\uDD18':'Ufr','\\uD835\\uDCB0':'Uscr','\\xFA':'uacute','\\xDA':'Uacute','\\xF9':'ugrave','\\xD9':'Ugrave','\\u016D':'ubreve','\\u016C':'Ubreve','\\xFB':'ucirc','\\xDB':'Ucirc','\\u016F':'uring','\\u016E':'Uring','\\xFC':'uuml','\\xDC':'Uuml','\\u0171':'udblac','\\u0170':'Udblac','\\u0169':'utilde','\\u0168':'Utilde','\\u0173':'uogon','\\u0172':'Uogon','\\u016B':'umacr','\\u016A':'Umacr','\\uD835\\uDD33':'vfr','\\uD835\\uDD67':'vopf','\\uD835\\uDCCB':'vscr','\\uD835\\uDD19':'Vfr','\\uD835\\uDD4D':'Vopf','\\uD835\\uDCB1':'Vscr','\\uD835\\uDD68':'wopf','\\uD835\\uDCCC':'wscr','\\uD835\\uDD34':'wfr','\\uD835\\uDCB2':'Wscr','\\uD835\\uDD4E':'Wopf','\\uD835\\uDD1A':'Wfr','\\u0175':'wcirc','\\u0174':'Wcirc','\\uD835\\uDD35':'xfr','\\uD835\\uDCCD':'xscr','\\uD835\\uDD69':'xopf','\\uD835\\uDD4F':'Xopf','\\uD835\\uDD1B':'Xfr','\\uD835\\uDCB3':'Xscr','\\uD835\\uDD36':'yfr','\\uD835\\uDCCE':'yscr','\\uD835\\uDD6A':'yopf','\\uD835\\uDCB4':'Yscr','\\uD835\\uDD1C':'Yfr','\\uD835\\uDD50':'Yopf','\\xFD':'yacute','\\xDD':'Yacute','\\u0177':'ycirc','\\u0176':'Ycirc','\\xFF':'yuml','\\u0178':'Yuml','\\uD835\\uDCCF':'zscr','\\uD835\\uDD37':'zfr','\\uD835\\uDD6B':'zopf','\\u2128':'Zfr','\\u2124':'Zopf','\\uD835\\uDCB5':'Zscr','\\u017A':'zacute','\\u0179':'Zacute','\\u017E':'zcaron','\\u017D':'Zcaron','\\u017C':'zdot','\\u017B':'Zdot','\\u01B5':'imped','\\xFE':'thorn','\\xDE':'THORN','\\u0149':'napos','\\u03B1':'alpha','\\u0391':'Alpha','\\u03B2':'beta','\\u0392':'Beta','\\u03B3':'gamma','\\u0393':'Gamma','\\u03B4':'delta','\\u0394':'Delta','\\u03B5':'epsi','\\u03F5':'epsiv','\\u0395':'Epsilon','\\u03DD':'gammad','\\u03DC':'Gammad','\\u03B6':'zeta','\\u0396':'Zeta','\\u03B7':'eta','\\u0397':'Eta','\\u03B8':'theta','\\u03D1':'thetav','\\u0398':'Theta','\\u03B9':'iota','\\u0399':'Iota','\\u03BA':'kappa','\\u03F0':'kappav','\\u039A':'Kappa','\\u03BB':'lambda','\\u039B':'Lambda','\\u03BC':'mu','\\xB5':'micro','\\u039C':'Mu','\\u03BD':'nu','\\u039D':'Nu','\\u03BE':'xi','\\u039E':'Xi','\\u03BF':'omicron','\\u039F':'Omicron','\\u03C0':'pi','\\u03D6':'piv','\\u03A0':'Pi','\\u03C1':'rho','\\u03F1':'rhov','\\u03A1':'Rho','\\u03C3':'sigma','\\u03A3':'Sigma','\\u03C2':'sigmaf','\\u03C4':'tau','\\u03A4':'Tau','\\u03C5':'upsi','\\u03A5':'Upsilon','\\u03D2':'Upsi','\\u03C6':'phi','\\u03D5':'phiv','\\u03A6':'Phi','\\u03C7':'chi','\\u03A7':'Chi','\\u03C8':'psi','\\u03A8':'Psi','\\u03C9':'omega','\\u03A9':'ohm','\\u0430':'acy','\\u0410':'Acy','\\u0431':'bcy','\\u0411':'Bcy','\\u0432':'vcy','\\u0412':'Vcy','\\u0433':'gcy','\\u0413':'Gcy','\\u0453':'gjcy','\\u0403':'GJcy','\\u0434':'dcy','\\u0414':'Dcy','\\u0452':'djcy','\\u0402':'DJcy','\\u0435':'iecy','\\u0415':'IEcy','\\u0451':'iocy','\\u0401':'IOcy','\\u0454':'jukcy','\\u0404':'Jukcy','\\u0436':'zhcy','\\u0416':'ZHcy','\\u0437':'zcy','\\u0417':'Zcy','\\u0455':'dscy','\\u0405':'DScy','\\u0438':'icy','\\u0418':'Icy','\\u0456':'iukcy','\\u0406':'Iukcy','\\u0457':'yicy','\\u0407':'YIcy','\\u0439':'jcy','\\u0419':'Jcy','\\u0458':'jsercy','\\u0408':'Jsercy','\\u043A':'kcy','\\u041A':'Kcy','\\u045C':'kjcy','\\u040C':'KJcy','\\u043B':'lcy','\\u041B':'Lcy','\\u0459':'ljcy','\\u0409':'LJcy','\\u043C':'mcy','\\u041C':'Mcy','\\u043D':'ncy','\\u041D':'Ncy','\\u045A':'njcy','\\u040A':'NJcy','\\u043E':'ocy','\\u041E':'Ocy','\\u043F':'pcy','\\u041F':'Pcy','\\u0440':'rcy','\\u0420':'Rcy','\\u0441':'scy','\\u0421':'Scy','\\u0442':'tcy','\\u0422':'Tcy','\\u045B':'tshcy','\\u040B':'TSHcy','\\u0443':'ucy','\\u0423':'Ucy','\\u045E':'ubrcy','\\u040E':'Ubrcy','\\u0444':'fcy','\\u0424':'Fcy','\\u0445':'khcy','\\u0425':'KHcy','\\u0446':'tscy','\\u0426':'TScy','\\u0447':'chcy','\\u0427':'CHcy','\\u045F':'dzcy','\\u040F':'DZcy','\\u0448':'shcy','\\u0428':'SHcy','\\u0449':'shchcy','\\u0429':'SHCHcy','\\u044A':'hardcy','\\u042A':'HARDcy','\\u044B':'ycy','\\u042B':'Ycy','\\u044C':'softcy','\\u042C':'SOFTcy','\\u044D':'ecy','\\u042D':'Ecy','\\u044E':'yucy','\\u042E':'YUcy','\\u044F':'yacy','\\u042F':'YAcy','\\u2135':'aleph','\\u2136':'beth','\\u2137':'gimel','\\u2138':'daleth'};\n\n\tvar regexEscape = /[\"&'<>`]/g;\n\tvar escapeMap = {\n\t\t'\"': '"',\n\t\t'&': '&',\n\t\t'\\'': ''',\n\t\t'<': '<',\n\t\t// See https://mathiasbynens.be/notes/ambiguous-ampersands: in HTML, the\n\t\t// following is not strictly necessary unless it’s part of a tag or an\n\t\t// unquoted attribute value. We’re only escaping it to support those\n\t\t// situations, and for XML support.\n\t\t'>': '>',\n\t\t// In Internet Explorer ≤ 8, the backtick character can be used\n\t\t// to break out of (un)quoted attribute values or HTML comments.\n\t\t// See http://html5sec.org/#102, http://html5sec.org/#108, and\n\t\t// http://html5sec.org/#133.\n\t\t'`': '`'\n\t};\n\n\tvar regexInvalidEntity = /&#(?:[xX][^a-fA-F0-9]|[^0-9xX])/;\n\tvar regexInvalidRawCodePoint = /[\\0-\\x08\\x0B\\x0E-\\x1F\\x7F-\\x9F\\uFDD0-\\uFDEF\\uFFFE\\uFFFF]|[\\uD83F\\uD87F\\uD8BF\\uD8FF\\uD93F\\uD97F\\uD9BF\\uD9FF\\uDA3F\\uDA7F\\uDABF\\uDAFF\\uDB3F\\uDB7F\\uDBBF\\uDBFF][\\uDFFE\\uDFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/;\n\tvar regexDecode = /&(CounterClockwiseContourIntegral|DoubleLongLeftRightArrow|ClockwiseContourIntegral|NotNestedGreaterGreater|NotSquareSupersetEqual|DiacriticalDoubleAcute|NotRightTriangleEqual|NotSucceedsSlantEqual|NotPrecedesSlantEqual|CloseCurlyDoubleQuote|NegativeVeryThinSpace|DoubleContourIntegral|FilledVerySmallSquare|CapitalDifferentialD|OpenCurlyDoubleQuote|EmptyVerySmallSquare|NestedGreaterGreater|DoubleLongRightArrow|NotLeftTriangleEqual|NotGreaterSlantEqual|ReverseUpEquilibrium|DoubleLeftRightArrow|NotSquareSubsetEqual|NotDoubleVerticalBar|RightArrowLeftArrow|NotGreaterFullEqual|NotRightTriangleBar|SquareSupersetEqual|DownLeftRightVector|DoubleLongLeftArrow|leftrightsquigarrow|LeftArrowRightArrow|NegativeMediumSpace|blacktriangleright|RightDownVectorBar|PrecedesSlantEqual|RightDoubleBracket|SucceedsSlantEqual|NotLeftTriangleBar|RightTriangleEqual|SquareIntersection|RightDownTeeVector|ReverseEquilibrium|NegativeThickSpace|longleftrightarrow|Longleftrightarrow|LongLeftRightArrow|DownRightTeeVector|DownRightVectorBar|GreaterSlantEqual|SquareSubsetEqual|LeftDownVectorBar|LeftDoubleBracket|VerticalSeparator|rightleftharpoons|NotGreaterGreater|NotSquareSuperset|blacktriangleleft|blacktriangledown|NegativeThinSpace|LeftDownTeeVector|NotLessSlantEqual|leftrightharpoons|DoubleUpDownArrow|DoubleVerticalBar|LeftTriangleEqual|FilledSmallSquare|twoheadrightarrow|NotNestedLessLess|DownLeftTeeVector|DownLeftVectorBar|RightAngleBracket|NotTildeFullEqual|NotReverseElement|RightUpDownVector|DiacriticalTilde|NotSucceedsTilde|circlearrowright|NotPrecedesEqual|rightharpoondown|DoubleRightArrow|NotSucceedsEqual|NonBreakingSpace|NotRightTriangle|LessEqualGreater|RightUpTeeVector|LeftAngleBracket|GreaterFullEqual|DownArrowUpArrow|RightUpVectorBar|twoheadleftarrow|GreaterEqualLess|downharpoonright|RightTriangleBar|ntrianglerighteq|NotSupersetEqual|LeftUpDownVector|DiacriticalAcute|rightrightarrows|vartriangleright|UpArrowDownArrow|DiacriticalGrave|UnderParenthesis|EmptySmallSquare|LeftUpVectorBar|leftrightarrows|DownRightVector|downharpoonleft|trianglerighteq|ShortRightArrow|OverParenthesis|DoubleLeftArrow|DoubleDownArrow|NotSquareSubset|bigtriangledown|ntrianglelefteq|UpperRightArrow|curvearrowright|vartriangleleft|NotLeftTriangle|nleftrightarrow|LowerRightArrow|NotHumpDownHump|NotGreaterTilde|rightthreetimes|LeftUpTeeVector|NotGreaterEqual|straightepsilon|LeftTriangleBar|rightsquigarrow|ContourIntegral|rightleftarrows|CloseCurlyQuote|RightDownVector|LeftRightVector|nLeftrightarrow|leftharpoondown|circlearrowleft|SquareSuperset|OpenCurlyQuote|hookrightarrow|HorizontalLine|DiacriticalDot|NotLessGreater|ntriangleright|DoubleRightTee|InvisibleComma|InvisibleTimes|LowerLeftArrow|DownLeftVector|NotSubsetEqual|curvearrowleft|trianglelefteq|NotVerticalBar|TildeFullEqual|downdownarrows|NotGreaterLess|RightTeeVector|ZeroWidthSpace|looparrowright|LongRightArrow|doublebarwedge|ShortLeftArrow|ShortDownArrow|RightVectorBar|GreaterGreater|ReverseElement|rightharpoonup|LessSlantEqual|leftthreetimes|upharpoonright|rightarrowtail|LeftDownVector|Longrightarrow|NestedLessLess|UpperLeftArrow|nshortparallel|leftleftarrows|leftrightarrow|Leftrightarrow|LeftRightArrow|longrightarrow|upharpoonleft|RightArrowBar|ApplyFunction|LeftTeeVector|leftarrowtail|NotEqualTilde|varsubsetneqq|varsupsetneqq|RightTeeArrow|SucceedsEqual|SucceedsTilde|LeftVectorBar|SupersetEqual|hookleftarrow|DifferentialD|VerticalTilde|VeryThinSpace|blacktriangle|bigtriangleup|LessFullEqual|divideontimes|leftharpoonup|UpEquilibrium|ntriangleleft|RightTriangle|measuredangle|shortparallel|longleftarrow|Longleftarrow|LongLeftArrow|DoubleLeftTee|Poincareplane|PrecedesEqual|triangleright|DoubleUpArrow|RightUpVector|fallingdotseq|looparrowleft|PrecedesTilde|NotTildeEqual|NotTildeTilde|smallsetminus|Proportional|triangleleft|triangledown|UnderBracket|NotHumpEqual|exponentiale|ExponentialE|NotLessTilde|HilbertSpace|RightCeiling|blacklozenge|varsupsetneq|HumpDownHump|GreaterEqual|VerticalLine|LeftTeeArrow|NotLessEqual|DownTeeArrow|LeftTriangle|varsubsetneq|Intersection|NotCongruent|DownArrowBar|LeftUpVector|LeftArrowBar|risingdotseq|GreaterTilde|RoundImplies|SquareSubset|ShortUpArrow|NotSuperset|quaternions|precnapprox|backepsilon|preccurlyeq|OverBracket|blacksquare|MediumSpace|VerticalBar|circledcirc|circleddash|CircleMinus|CircleTimes|LessGreater|curlyeqprec|curlyeqsucc|diamondsuit|UpDownArrow|Updownarrow|RuleDelayed|Rrightarrow|updownarrow|RightVector|nRightarrow|nrightarrow|eqslantless|LeftCeiling|Equilibrium|SmallCircle|expectation|NotSucceeds|thickapprox|GreaterLess|SquareUnion|NotPrecedes|NotLessLess|straightphi|succnapprox|succcurlyeq|SubsetEqual|sqsupseteq|Proportion|Laplacetrf|ImaginaryI|supsetneqq|NotGreater|gtreqqless|NotElement|ThickSpace|TildeEqual|TildeTilde|Fouriertrf|rmoustache|EqualTilde|eqslantgtr|UnderBrace|LeftVector|UpArrowBar|nLeftarrow|nsubseteqq|subsetneqq|nsupseteqq|nleftarrow|succapprox|lessapprox|UpTeeArrow|upuparrows|curlywedge|lesseqqgtr|varepsilon|varnothing|RightFloor|complement|CirclePlus|sqsubseteq|Lleftarrow|circledast|RightArrow|Rightarrow|rightarrow|lmoustache|Bernoullis|precapprox|mapstoleft|mapstodown|longmapsto|dotsquare|downarrow|DoubleDot|nsubseteq|supsetneq|leftarrow|nsupseteq|subsetneq|ThinSpace|ngeqslant|subseteqq|HumpEqual|NotSubset|triangleq|NotCupCap|lesseqgtr|heartsuit|TripleDot|Leftarrow|Coproduct|Congruent|varpropto|complexes|gvertneqq|LeftArrow|LessTilde|supseteqq|MinusPlus|CircleDot|nleqslant|NotExists|gtreqless|nparallel|UnionPlus|LeftFloor|checkmark|CenterDot|centerdot|Mellintrf|gtrapprox|bigotimes|OverBrace|spadesuit|therefore|pitchfork|rationals|PlusMinus|Backslash|Therefore|DownBreve|backsimeq|backprime|DownArrow|nshortmid|Downarrow|lvertneqq|eqvparsl|imagline|imagpart|infintie|integers|Integral|intercal|LessLess|Uarrocir|intlarhk|sqsupset|angmsdaf|sqsubset|llcorner|vartheta|cupbrcap|lnapprox|Superset|SuchThat|succnsim|succneqq|angmsdag|biguplus|curlyvee|trpezium|Succeeds|NotTilde|bigwedge|angmsdah|angrtvbd|triminus|cwconint|fpartint|lrcorner|smeparsl|subseteq|urcorner|lurdshar|laemptyv|DDotrahd|approxeq|ldrushar|awconint|mapstoup|backcong|shortmid|triangle|geqslant|gesdotol|timesbar|circledR|circledS|setminus|multimap|naturals|scpolint|ncongdot|RightTee|boxminus|gnapprox|boxtimes|andslope|thicksim|angmsdaa|varsigma|cirfnint|rtriltri|angmsdab|rppolint|angmsdac|barwedge|drbkarow|clubsuit|thetasym|bsolhsub|capbrcup|dzigrarr|doteqdot|DotEqual|dotminus|UnderBar|NotEqual|realpart|otimesas|ulcorner|hksearow|hkswarow|parallel|PartialD|elinters|emptyset|plusacir|bbrktbrk|angmsdad|pointint|bigoplus|angmsdae|Precedes|bigsqcup|varkappa|notindot|supseteq|precneqq|precnsim|profalar|profline|profsurf|leqslant|lesdotor|raemptyv|subplus|notnivb|notnivc|subrarr|zigrarr|vzigzag|submult|subedot|Element|between|cirscir|larrbfs|larrsim|lotimes|lbrksld|lbrkslu|lozenge|ldrdhar|dbkarow|bigcirc|epsilon|simrarr|simplus|ltquest|Epsilon|luruhar|gtquest|maltese|npolint|eqcolon|npreceq|bigodot|ddagger|gtrless|bnequiv|harrcir|ddotseq|equivDD|backsim|demptyv|nsqsube|nsqsupe|Upsilon|nsubset|upsilon|minusdu|nsucceq|swarrow|nsupset|coloneq|searrow|boxplus|napprox|natural|asympeq|alefsym|congdot|nearrow|bigstar|diamond|supplus|tritime|LeftTee|nvinfin|triplus|NewLine|nvltrie|nvrtrie|nwarrow|nexists|Diamond|ruluhar|Implies|supmult|angzarr|suplarr|suphsub|questeq|because|digamma|Because|olcross|bemptyv|omicron|Omicron|rotimes|NoBreak|intprod|angrtvb|orderof|uwangle|suphsol|lesdoto|orslope|DownTee|realine|cudarrl|rdldhar|OverBar|supedot|lessdot|supdsub|topfork|succsim|rbrkslu|rbrksld|pertenk|cudarrr|isindot|planckh|lessgtr|pluscir|gesdoto|plussim|plustwo|lesssim|cularrp|rarrsim|Cayleys|notinva|notinvb|notinvc|UpArrow|Uparrow|uparrow|NotLess|dwangle|precsim|Product|curarrm|Cconint|dotplus|rarrbfs|ccupssm|Cedilla|cemptyv|notniva|quatint|frac35|frac38|frac45|frac56|frac58|frac78|tridot|xoplus|gacute|gammad|Gammad|lfisht|lfloor|bigcup|sqsupe|gbreve|Gbreve|lharul|sqsube|sqcups|Gcedil|apacir|llhard|lmidot|Lmidot|lmoust|andand|sqcaps|approx|Abreve|spades|circeq|tprime|divide|topcir|Assign|topbot|gesdot|divonx|xuplus|timesd|gesles|atilde|solbar|SOFTcy|loplus|timesb|lowast|lowbar|dlcorn|dlcrop|softcy|dollar|lparlt|thksim|lrhard|Atilde|lsaquo|smashp|bigvee|thinsp|wreath|bkarow|lsquor|lstrok|Lstrok|lthree|ltimes|ltlarr|DotDot|simdot|ltrPar|weierp|xsqcup|angmsd|sigmav|sigmaf|zeetrf|Zcaron|zcaron|mapsto|vsupne|thetav|cirmid|marker|mcomma|Zacute|vsubnE|there4|gtlPar|vsubne|bottom|gtrarr|SHCHcy|shchcy|midast|midcir|middot|minusb|minusd|gtrdot|bowtie|sfrown|mnplus|models|colone|seswar|Colone|mstpos|searhk|gtrsim|nacute|Nacute|boxbox|telrec|hairsp|Tcedil|nbumpe|scnsim|ncaron|Ncaron|ncedil|Ncedil|hamilt|Scedil|nearhk|hardcy|HARDcy|tcedil|Tcaron|commat|nequiv|nesear|tcaron|target|hearts|nexist|varrho|scedil|Scaron|scaron|hellip|Sacute|sacute|hercon|swnwar|compfn|rtimes|rthree|rsquor|rsaquo|zacute|wedgeq|homtht|barvee|barwed|Barwed|rpargt|horbar|conint|swarhk|roplus|nltrie|hslash|hstrok|Hstrok|rmoust|Conint|bprime|hybull|hyphen|iacute|Iacute|supsup|supsub|supsim|varphi|coprod|brvbar|agrave|Supset|supset|igrave|Igrave|notinE|Agrave|iiiint|iinfin|copysr|wedbar|Verbar|vangrt|becaus|incare|verbar|inodot|bullet|drcorn|intcal|drcrop|cularr|vellip|Utilde|bumpeq|cupcap|dstrok|Dstrok|CupCap|cupcup|cupdot|eacute|Eacute|supdot|iquest|easter|ecaron|Ecaron|ecolon|isinsv|utilde|itilde|Itilde|curarr|succeq|Bumpeq|cacute|ulcrop|nparsl|Cacute|nprcue|egrave|Egrave|nrarrc|nrarrw|subsup|subsub|nrtrie|jsercy|nsccue|Jsercy|kappav|kcedil|Kcedil|subsim|ulcorn|nsimeq|egsdot|veebar|kgreen|capand|elsdot|Subset|subset|curren|aacute|lacute|Lacute|emptyv|ntilde|Ntilde|lagran|lambda|Lambda|capcap|Ugrave|langle|subdot|emsp13|numero|emsp14|nvdash|nvDash|nVdash|nVDash|ugrave|ufisht|nvHarr|larrfs|nvlArr|larrhk|larrlp|larrpl|nvrArr|Udblac|nwarhk|larrtl|nwnear|oacute|Oacute|latail|lAtail|sstarf|lbrace|odblac|Odblac|lbrack|udblac|odsold|eparsl|lcaron|Lcaron|ograve|Ograve|lcedil|Lcedil|Aacute|ssmile|ssetmn|squarf|ldquor|capcup|ominus|cylcty|rharul|eqcirc|dagger|rfloor|rfisht|Dagger|daleth|equals|origof|capdot|equest|dcaron|Dcaron|rdquor|oslash|Oslash|otilde|Otilde|otimes|Otimes|urcrop|Ubreve|ubreve|Yacute|Uacute|uacute|Rcedil|rcedil|urcorn|parsim|Rcaron|Vdashl|rcaron|Tstrok|percnt|period|permil|Exists|yacute|rbrack|rbrace|phmmat|ccaron|Ccaron|planck|ccedil|plankv|tstrok|female|plusdo|plusdu|ffilig|plusmn|ffllig|Ccedil|rAtail|dfisht|bernou|ratail|Rarrtl|rarrtl|angsph|rarrpl|rarrlp|rarrhk|xwedge|xotime|forall|ForAll|Vvdash|vsupnE|preceq|bigcap|frac12|frac13|frac14|primes|rarrfs|prnsim|frac15|Square|frac16|square|lesdot|frac18|frac23|propto|prurel|rarrap|rangle|puncsp|frac25|Racute|qprime|racute|lesges|frac34|abreve|AElig|eqsim|utdot|setmn|urtri|Equal|Uring|seArr|uring|searr|dashv|Dashv|mumap|nabla|iogon|Iogon|sdote|sdotb|scsim|napid|napos|equiv|natur|Acirc|dblac|erarr|nbump|iprod|erDot|ucirc|awint|esdot|angrt|ncong|isinE|scnap|Scirc|scirc|ndash|isins|Ubrcy|nearr|neArr|isinv|nedot|ubrcy|acute|Ycirc|iukcy|Iukcy|xutri|nesim|caret|jcirc|Jcirc|caron|twixt|ddarr|sccue|exist|jmath|sbquo|ngeqq|angst|ccaps|lceil|ngsim|UpTee|delta|Delta|rtrif|nharr|nhArr|nhpar|rtrie|jukcy|Jukcy|kappa|rsquo|Kappa|nlarr|nlArr|TSHcy|rrarr|aogon|Aogon|fflig|xrarr|tshcy|ccirc|nleqq|filig|upsih|nless|dharl|nlsim|fjlig|ropar|nltri|dharr|robrk|roarr|fllig|fltns|roang|rnmid|subnE|subne|lAarr|trisb|Ccirc|acirc|ccups|blank|VDash|forkv|Vdash|langd|cedil|blk12|blk14|laquo|strns|diams|notin|vDash|larrb|blk34|block|disin|uplus|vdash|vBarv|aelig|starf|Wedge|check|xrArr|lates|lbarr|lBarr|notni|lbbrk|bcong|frasl|lbrke|frown|vrtri|vprop|vnsup|gamma|Gamma|wedge|xodot|bdquo|srarr|doteq|ldquo|boxdl|boxdL|gcirc|Gcirc|boxDl|boxDL|boxdr|boxdR|boxDr|TRADE|trade|rlhar|boxDR|vnsub|npart|vltri|rlarr|boxhd|boxhD|nprec|gescc|nrarr|nrArr|boxHd|boxHD|boxhu|boxhU|nrtri|boxHu|clubs|boxHU|times|colon|Colon|gimel|xlArr|Tilde|nsime|tilde|nsmid|nspar|THORN|thorn|xlarr|nsube|nsubE|thkap|xhArr|comma|nsucc|boxul|boxuL|nsupe|nsupE|gneqq|gnsim|boxUl|boxUL|grave|boxur|boxuR|boxUr|boxUR|lescc|angle|bepsi|boxvh|varpi|boxvH|numsp|Theta|gsime|gsiml|theta|boxVh|boxVH|boxvl|gtcir|gtdot|boxvL|boxVl|boxVL|crarr|cross|Cross|nvsim|boxvr|nwarr|nwArr|sqsup|dtdot|Uogon|lhard|lharu|dtrif|ocirc|Ocirc|lhblk|duarr|odash|sqsub|Hacek|sqcup|llarr|duhar|oelig|OElig|ofcir|boxvR|uogon|lltri|boxVr|csube|uuarr|ohbar|csupe|ctdot|olarr|olcir|harrw|oline|sqcap|omacr|Omacr|omega|Omega|boxVR|aleph|lneqq|lnsim|loang|loarr|rharu|lobrk|hcirc|operp|oplus|rhard|Hcirc|orarr|Union|order|ecirc|Ecirc|cuepr|szlig|cuesc|breve|reals|eDDot|Breve|hoarr|lopar|utrif|rdquo|Umacr|umacr|efDot|swArr|ultri|alpha|rceil|ovbar|swarr|Wcirc|wcirc|smtes|smile|bsemi|lrarr|aring|parsl|lrhar|bsime|uhblk|lrtri|cupor|Aring|uharr|uharl|slarr|rbrke|bsolb|lsime|rbbrk|RBarr|lsimg|phone|rBarr|rbarr|icirc|lsquo|Icirc|emacr|Emacr|ratio|simne|plusb|simlE|simgE|simeq|pluse|ltcir|ltdot|empty|xharr|xdtri|iexcl|Alpha|ltrie|rarrw|pound|ltrif|xcirc|bumpe|prcue|bumpE|asymp|amacr|cuvee|Sigma|sigma|iiint|udhar|iiota|ijlig|IJlig|supnE|imacr|Imacr|prime|Prime|image|prnap|eogon|Eogon|rarrc|mdash|mDDot|cuwed|imath|supne|imped|Amacr|udarr|prsim|micro|rarrb|cwint|raquo|infin|eplus|range|rangd|Ucirc|radic|minus|amalg|veeeq|rAarr|epsiv|ycirc|quest|sharp|quot|zwnj|Qscr|race|qscr|Qopf|qopf|qint|rang|Rang|Zscr|zscr|Zopf|zopf|rarr|rArr|Rarr|Pscr|pscr|prop|prod|prnE|prec|ZHcy|zhcy|prap|Zeta|zeta|Popf|popf|Zdot|plus|zdot|Yuml|yuml|phiv|YUcy|yucy|Yscr|yscr|perp|Yopf|yopf|part|para|YIcy|Ouml|rcub|yicy|YAcy|rdca|ouml|osol|Oscr|rdsh|yacy|real|oscr|xvee|andd|rect|andv|Xscr|oror|ordm|ordf|xscr|ange|aopf|Aopf|rHar|Xopf|opar|Oopf|xopf|xnis|rhov|oopf|omid|xmap|oint|apid|apos|ogon|ascr|Ascr|odot|odiv|xcup|xcap|ocir|oast|nvlt|nvle|nvgt|nvge|nvap|Wscr|wscr|auml|ntlg|ntgl|nsup|nsub|nsim|Nscr|nscr|nsce|Wopf|ring|npre|wopf|npar|Auml|Barv|bbrk|Nopf|nopf|nmid|nLtv|beta|ropf|Ropf|Beta|beth|nles|rpar|nleq|bnot|bNot|nldr|NJcy|rscr|Rscr|Vscr|vscr|rsqb|njcy|bopf|nisd|Bopf|rtri|Vopf|nGtv|ngtr|vopf|boxh|boxH|boxv|nges|ngeq|boxV|bscr|scap|Bscr|bsim|Vert|vert|bsol|bull|bump|caps|cdot|ncup|scnE|ncap|nbsp|napE|Cdot|cent|sdot|Vbar|nang|vBar|chcy|Mscr|mscr|sect|semi|CHcy|Mopf|mopf|sext|circ|cire|mldr|mlcp|cirE|comp|shcy|SHcy|vArr|varr|cong|copf|Copf|copy|COPY|malt|male|macr|lvnE|cscr|ltri|sime|ltcc|simg|Cscr|siml|csub|Uuml|lsqb|lsim|uuml|csup|Lscr|lscr|utri|smid|lpar|cups|smte|lozf|darr|Lopf|Uscr|solb|lopf|sopf|Sopf|lneq|uscr|spar|dArr|lnap|Darr|dash|Sqrt|LJcy|ljcy|lHar|dHar|Upsi|upsi|diam|lesg|djcy|DJcy|leqq|dopf|Dopf|dscr|Dscr|dscy|ldsh|ldca|squf|DScy|sscr|Sscr|dsol|lcub|late|star|Star|Uopf|Larr|lArr|larr|uopf|dtri|dzcy|sube|subE|Lang|lang|Kscr|kscr|Kopf|kopf|KJcy|kjcy|KHcy|khcy|DZcy|ecir|edot|eDot|Jscr|jscr|succ|Jopf|jopf|Edot|uHar|emsp|ensp|Iuml|iuml|eopf|isin|Iscr|iscr|Eopf|epar|sung|epsi|escr|sup1|sup2|sup3|Iota|iota|supe|supE|Iopf|iopf|IOcy|iocy|Escr|esim|Esim|imof|Uarr|QUOT|uArr|uarr|euml|IEcy|iecy|Idot|Euml|euro|excl|Hscr|hscr|Hopf|hopf|TScy|tscy|Tscr|hbar|tscr|flat|tbrk|fnof|hArr|harr|half|fopf|Fopf|tdot|gvnE|fork|trie|gtcc|fscr|Fscr|gdot|gsim|Gscr|gscr|Gopf|gopf|gneq|Gdot|tosa|gnap|Topf|topf|geqq|toea|GJcy|gj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rave|Iacute|Igrave|Ntilde|Oacute|Ograve|Oslash|Otilde|Uacute|Ugrave|Yacute|aacute|agrave|atilde|brvbar|ccedil|curren|divide|eacute|egrave|frac12|frac14|frac34|iacute|igrave|iquest|middot|ntilde|oacute|ograve|oslash|otilde|plusmn|uacute|ugrave|yacute|AElig|Acirc|Aring|Ecirc|Icirc|Ocirc|THORN|Ucirc|acirc|acute|aelig|aring|cedil|ecirc|icirc|iexcl|laquo|micro|ocirc|pound|raquo|szlig|thorn|times|ucirc|Auml|COPY|Euml|Iuml|Ouml|QUOT|Uuml|auml|cent|copy|euml|iuml|macr|nbsp|ordf|ordm|ouml|para|quot|sect|sup1|sup2|sup3|uuml|yuml|AMP|ETH|REG|amp|deg|eth|not|reg|shy|uml|yen|GT|LT|gt|lt)(?!;)([=a-zA-Z0-9]?)|&#([0-9]+)(;?)|&#[xX]([a-fA-F0-9]+)(;?)|&([0-9a-zA-Z]+)/g;\n\tvar decodeMap = {'aacute':'\\xE1','Aacute':'\\xC1','abreve':'\\u0103','Abreve':'\\u0102','ac':'\\u223E','acd':'\\u223F','acE':'\\u223E\\u0333','acirc':'\\xE2','Acirc':'\\xC2','acute':'\\xB4','acy':'\\u0430','Acy':'\\u0410','aelig':'\\xE6','AElig':'\\xC6','af':'\\u2061','afr':'\\uD835\\uDD1E','Afr':'\\uD835\\uDD04','agrave':'\\xE0','Agrave':'\\xC0','alefsym':'\\u2135','aleph':'\\u2135','alpha':'\\u03B1','Alpha':'\\u0391','amacr':'\\u0101','Amacr':'\\u0100','amalg':'\\u2A3F','amp':'&','AMP':'&','and':'\\u2227','And':'\\u2A53','andand':'\\u2A55','andd':'\\u2A5C','andslope':'\\u2A58','andv':'\\u2A5A','ang':'\\u2220','ange':'\\u29A4','angle':'\\u2220','angmsd':'\\u2221','angmsdaa':'\\u29A8','angmsdab':'\\u29A9','angmsdac':'\\u29AA','angmsdad':'\\u29AB','angmsdae':'\\u29AC','angmsdaf':'\\u29AD','angmsdag':'\\u29AE','angmsdah':'\\u29AF','angrt':'\\u221F','angrtvb':'\\u22BE','angrtvbd':'\\u299D','angsph':'\\u2222','angst':'\\xC5','angzarr':'\\u237C','aogon':'\\u0105','Aogon':'\\u0104','aopf':'\\uD835\\uDD52','Aopf':'\\uD835\\uDD38','ap':'\\u2248','apacir':'\\u2A6F','ape':'\\u224A','apE':'\\u2A70','apid':'\\u224B','apos':'\\'','ApplyFunction':'\\u2061','approx':'\\u2248','approxeq':'\\u224A','aring':'\\xE5','Aring':'\\xC5','ascr':'\\uD835\\uDCB6','Ascr':'\\uD835\\uDC9C','Assign':'\\u2254','ast':'*','asymp':'\\u2248','asympeq':'\\u224D','atilde':'\\xE3','Atilde':'\\xC3','auml':'\\xE4','Auml':'\\xC4','awconint':'\\u2233','awint':'\\u2A11','backcong':'\\u224C','backepsilon':'\\u03F6','backprime':'\\u2035','backsim':'\\u223D','backsimeq':'\\u22CD','Backslash':'\\u2216','Barv':'\\u2AE7','barvee':'\\u22BD','barwed':'\\u2305','Barwed':'\\u2306','barwedge':'\\u2305','bbrk':'\\u23B5','bbrktbrk':'\\u23B6','bcong':'\\u224C','bcy':'\\u0431','Bcy':'\\u0411','bdquo':'\\u201E','becaus':'\\u2235','because':'\\u2235','Because':'\\u2235','bemptyv':'\\u29B0','bepsi':'\\u03F6','bernou':'\\u212C','Bernoullis':'\\u212C','beta':'\\u03B2','Beta':'\\u0392','beth':'\\u2136','between':'\\u226C','bfr':'\\uD835\\uDD1F','Bfr':'\\uD835\\uDD05','bigcap':'\\u22C2','bigcirc':'\\u25EF','bigcup':'\\u22C3','bigodot':'\\u2A00','bigoplus':'\\u2A01','bigotimes':'\\u2A02','bigsqcup':'\\u2A06','bigstar':'\\u2605','bigtriangledown':'\\u25BD','bigtriangleup':'\\u25B3','biguplus':'\\u2A04','bigvee':'\\u22C1','bigwedge':'\\u22C0','bkarow':'\\u290D','blacklozenge':'\\u29EB','blacksquare':'\\u25AA','blacktriangle':'\\u25B4','blacktriangledown':'\\u25BE','blacktriangleleft':'\\u25C2','blacktriangleright':'\\u25B8','blank':'\\u2423','blk12':'\\u2592','blk14':'\\u2591','blk34':'\\u2593','block':'\\u2588','bne':'=\\u20E5','bnequiv':'\\u2261\\u20E5','bnot':'\\u2310','bNot':'\\u2AED','bopf':'\\uD835\\uDD53','Bopf':'\\uD835\\uDD39','bot':'\\u22A5','bottom':'\\u22A5','bowtie':'\\u22C8','boxbox':'\\u29C9','boxdl':'\\u2510','boxdL':'\\u2555','boxDl':'\\u2556','boxDL':'\\u2557','boxdr':'\\u250C','boxdR':'\\u2552','boxDr':'\\u2553','boxDR':'\\u2554','boxh':'\\u2500','boxH':'\\u2550','boxhd':'\\u252C','boxhD':'\\u2565','boxHd':'\\u2564','boxHD':'\\u2566','boxhu':'\\u2534','boxhU':'\\u2568','boxHu':'\\u2567','boxHU':'\\u2569','boxminus':'\\u229F','boxplus':'\\u229E','boxtimes':'\\u22A0','boxul':'\\u2518','boxuL':'\\u255B','boxUl':'\\u255C','boxUL':'\\u255D','boxur':'\\u2514','boxuR':'\\u2558','boxUr':'\\u2559','boxUR':'\\u255A','boxv':'\\u2502','boxV':'\\u2551','boxvh':'\\u253C','boxvH':'\\u256A','boxVh':'\\u256B','boxVH':'\\u256C','boxvl':'\\u2524','boxvL':'\\u2561','boxVl':'\\u2562','boxVL':'\\u2563','boxvr':'\\u251C','boxvR':'\\u255E','boxVr':'\\u255F','boxVR':'\\u2560','bprime':'\\u2035','breve':'\\u02D8','Breve':'\\u02D8','brvbar':'\\xA6','bscr':'\\uD835\\uDCB7','Bscr':'\\u212C','bsemi':'\\u204F','bsim':'\\u223D','bsime':'\\u22CD','bsol':'\\\\','bsolb':'\\u29C5','bsolhsub':'\\u27C8','bull':'\\u2022','bullet':'\\u2022','bump':'\\u224E','bumpe':'\\u224F','bumpE':'\\u2AAE','bumpeq':'\\u224F','Bumpeq':'\\u224E','cacute':'\\u0107','Cacute':'\\u0106','cap':'\\u2229','Cap':'\\u22D2','capand':'\\u2A44','capbrcup':'\\u2A49','capcap':'\\u2A4B','capcup':'\\u2A47','capdot':'\\u2A40','CapitalDifferentialD':'\\u2145','caps':'\\u2229\\uFE00','caret':'\\u2041','caron':'\\u02C7','Cayleys':'\\u212D','ccaps':'\\u2A4D','ccaron':'\\u010D','Ccaron':'\\u010C','ccedil':'\\xE7','Ccedil':'\\xC7','ccirc':'\\u0109','Ccirc':'\\u0108','Cconint':'\\u2230','ccups':'\\u2A4C','ccupssm':'\\u2A50','cdot':'\\u010B','Cdot':'\\u010A','cedil':'\\xB8','Cedilla':'\\xB8','cemptyv':'\\u29B2','cent':'\\xA2','centerdot':'\\xB7','CenterDot':'\\xB7','cfr':'\\uD835\\uDD20','Cfr':'\\u212D','chcy':'\\u0447','CHcy':'\\u0427','check':'\\u2713','checkmark':'\\u2713','chi':'\\u03C7','Chi':'\\u03A7','cir':'\\u25CB','circ':'\\u02C6','circeq':'\\u2257','circlearrowleft':'\\u21BA','circlearrowright':'\\u21BB','circledast':'\\u229B','circledcirc':'\\u229A','circleddash':'\\u229D','CircleDot':'\\u2299','circledR':'\\xAE','circledS':'\\u24C8','CircleMinus':'\\u2296','CirclePlus':'\\u2295','CircleTimes':'\\u2297','cire':'\\u2257','cirE':'\\u29C3','cirfnint':'\\u2A10','cirmid':'\\u2AEF','cirscir':'\\u29C2','ClockwiseContourIntegral':'\\u2232','CloseCurlyDoubleQuote':'\\u201D','CloseCurlyQuote':'\\u2019','clubs':'\\u2663','clubsuit':'\\u2663','colon':':','Colon':'\\u2237','colone':'\\u2254','Colone':'\\u2A74','coloneq':'\\u2254','comma':',','commat':'@','comp':'\\u2201','compfn':'\\u2218','complement':'\\u2201','complexes':'\\u2102','cong':'\\u2245','congdot':'\\u2A6D','Congruent':'\\u2261','conint':'\\u222E','Conint':'\\u222F','ContourIntegral':'\\u222E','copf':'\\uD835\\uDD54','Copf':'\\u2102','coprod':'\\u2210','Coproduct':'\\u2210','copy':'\\xA9','COPY':'\\xA9','copysr':'\\u2117','CounterClockwiseContourIntegral':'\\u2233','crarr':'\\u21B5','cross':'\\u2717','Cross':'\\u2A2F','cscr':'\\uD835\\uDCB8','Cscr':'\\uD835\\uDC9E','csub':'\\u2ACF','csube':'\\u2AD1','csup':'\\u2AD0','csupe':'\\u2AD2','ctdot':'\\u22EF','cudarrl':'\\u2938','cudarrr':'\\u2935','cuepr':'\\u22DE','cuesc':'\\u22DF','cularr':'\\u21B6','cularrp':'\\u293D','cup':'\\u222A','Cup':'\\u22D3','cupbrcap':'\\u2A48','cupcap':'\\u2A46','CupCap':'\\u224D','cupcup':'\\u2A4A','cupdot':'\\u228D','cupor':'\\u2A45','cups':'\\u222A\\uFE00','curarr':'\\u21B7','curarrm':'\\u293C','curlyeqprec':'\\u22DE','curlyeqsucc':'\\u22DF','curlyvee':'\\u22CE','curlywedge':'\\u22CF','curren':'\\xA4','curvearrowleft':'\\u21B6','curvearrowright':'\\u21B7','cuvee':'\\u22CE','cuwed':'\\u22CF','cwconint':'\\u2232','cwint':'\\u2231','cylcty':'\\u232D','dagger':'\\u2020','Dagger':'\\u2021','daleth':'\\u2138','darr':'\\u2193','dArr':'\\u21D3','Darr':'\\u21A1','dash':'\\u2010','dashv':'\\u22A3','Dashv':'\\u2AE4','dbkarow':'\\u290F','dblac':'\\u02DD','dcaron':'\\u010F','Dcaron':'\\u010E','dcy':'\\u0434','Dcy':'\\u0414','dd':'\\u2146','DD':'\\u2145','ddagger':'\\u2021','ddarr':'\\u21CA','DDotrahd':'\\u2911','ddotseq':'\\u2A77','deg':'\\xB0','Del':'\\u2207','delta':'\\u03B4','Delta':'\\u0394','demptyv':'\\u29B1','dfisht':'\\u297F','dfr':'\\uD835\\uDD21','Dfr':'\\uD835\\uDD07','dHar':'\\u2965','dharl':'\\u21C3','dharr':'\\u21C2','DiacriticalAcute':'\\xB4','DiacriticalDot':'\\u02D9','DiacriticalDoubleAcute':'\\u02DD','DiacriticalGrave':'`','DiacriticalTilde':'\\u02DC','diam':'\\u22C4','diamond':'\\u22C4','Diamond':'\\u22C4','diamondsuit':'\\u2666','diams':'\\u2666','die':'\\xA8','DifferentialD':'\\u2146','digamma':'\\u03DD','disin':'\\u22F2','div':'\\xF7','divide':'\\xF7','divideontimes':'\\u22C7','divonx':'\\u22C7','djcy':'\\u0452','DJcy':'\\u0402','dlcorn':'\\u231E','dlcrop':'\\u230D','dollar':'$','dopf':'\\uD835\\uDD55','Dopf':'\\uD835\\uDD3B','dot':'\\u02D9','Dot':'\\xA8','DotDot':'\\u20DC','doteq':'\\u2250','doteqdot':'\\u2251','DotEqual':'\\u2250','dotminus':'\\u2238','dotplus':'\\u2214','dotsquare':'\\u22A1','doublebarwedge':'\\u2306','DoubleContourIntegral':'\\u222F','DoubleDot':'\\xA8','DoubleDownArrow':'\\u21D3','DoubleLeftArrow':'\\u21D0','DoubleLeftRightArrow':'\\u21D4','DoubleLeftTee':'\\u2AE4','DoubleLongLeftArrow':'\\u27F8','DoubleLongLeftRightArrow':'\\u27FA','DoubleLongRightArrow':'\\u27F9','DoubleRightArrow':'\\u21D2','DoubleRightTee':'\\u22A8','DoubleUpArrow':'\\u21D1','DoubleUpDownArrow':'\\u21D5','DoubleVerticalBar':'\\u2225','downarrow':'\\u2193','Downarrow':'\\u21D3','DownArrow':'\\u2193','DownArrowBar':'\\u2913','DownArrowUpArrow':'\\u21F5','DownBreve':'\\u0311','downdownarrows':'\\u21CA','downharpoonleft':'\\u21C3','downharpoonright':'\\u21C2','DownLeftRightVector':'\\u2950','DownLeftTeeVector':'\\u295E','DownLeftVector':'\\u21BD','DownLeftVectorBar':'\\u2956','DownRightTeeVector':'\\u295F','DownRightVector':'\\u21C1','DownRightVectorBar':'\\u2957','DownTee':'\\u22A4','DownTeeArrow':'\\u21A7','drbkarow':'\\u2910','drcorn':'\\u231F','drcrop':'\\u230C','dscr':'\\uD835\\uDCB9','Dscr':'\\uD835\\uDC9F','dscy':'\\u0455','DScy':'\\u0405','dsol':'\\u29F6','dstrok':'\\u0111','Dstrok':'\\u0110','dtdot':'\\u22F1','dtri':'\\u25BF','dtrif':'\\u25BE','duarr':'\\u21F5','duhar':'\\u296F','dwangle':'\\u29A6','dzcy':'\\u045F','DZcy':'\\u040F','dzigrarr':'\\u27FF','eacute':'\\xE9','Eacute':'\\xC9','easter':'\\u2A6E','ecaron':'\\u011B','Ecaron':'\\u011A','ecir':'\\u2256','ecirc':'\\xEA','Ecirc':'\\xCA','ecolon':'\\u2255','ecy':'\\u044D','Ecy':'\\u042D','eDDot':'\\u2A77','edot':'\\u0117','eDot':'\\u2251','Edot':'\\u0116','ee':'\\u2147','efDot':'\\u2252','efr':'\\uD835\\uDD22','Efr':'\\uD835\\uDD08','eg':'\\u2A9A','egrave':'\\xE8','Egrave':'\\xC8','egs':'\\u2A96','egsdot':'\\u2A98','el':'\\u2A99','Element':'\\u2208','elinters':'\\u23E7','ell':'\\u2113','els':'\\u2A95','elsdot':'\\u2A97','emacr':'\\u0113','Emacr':'\\u0112','empty':'\\u2205','emptyset':'\\u2205','EmptySmallSquare':'\\u25FB','emptyv':'\\u2205','EmptyVerySmallSquare':'\\u25AB','emsp':'\\u2003','emsp13':'\\u2004','emsp14':'\\u2005','eng':'\\u014B','ENG':'\\u014A','ensp':'\\u2002','eogon':'\\u0119','Eogon':'\\u0118','eopf':'\\uD835\\uDD56','Eopf':'\\uD835\\uDD3C','epar':'\\u22D5','eparsl':'\\u29E3','eplus':'\\u2A71','epsi':'\\u03B5','epsilon':'\\u03B5','Epsilon':'\\u0395','epsiv':'\\u03F5','eqcirc':'\\u2256','eqcolon':'\\u2255','eqsim':'\\u2242','eqslantgtr':'\\u2A96','eqslantless':'\\u2A95','Equal':'\\u2A75','equals':'=','EqualTilde':'\\u2242','equest':'\\u225F','Equilibrium':'\\u21CC','equiv':'\\u2261','equivDD':'\\u2A78','eqvparsl':'\\u29E5','erarr':'\\u2971','erDot':'\\u2253','escr':'\\u212F','Escr':'\\u2130','esdot':'\\u2250','esim':'\\u2242','Esim':'\\u2A73','eta':'\\u03B7','Eta':'\\u0397','eth':'\\xF0','ETH':'\\xD0','euml':'\\xEB','Euml':'\\xCB','euro':'\\u20AC','excl':'!','exist':'\\u2203','Exists':'\\u2203','expectation':'\\u2130','exponentiale':'\\u2147','ExponentialE':'\\u2147','fallingdotseq':'\\u2252','fcy':'\\u0444','Fcy':'\\u0424','female':'\\u2640','ffilig':'\\uFB03','fflig':'\\uFB00','ffllig':'\\uFB04','ffr':'\\uD835\\uDD23','Ffr':'\\uD835\\uDD09','filig':'\\uFB01','FilledSmallSquare':'\\u25FC','FilledVerySmallSquare':'\\u25AA','fjlig':'fj','flat':'\\u266D','fllig':'\\uFB02','fltns':'\\u25B1','fnof':'\\u0192','fopf':'\\uD835\\uDD57','Fopf':'\\uD835\\uDD3D','forall':'\\u2200','ForAll':'\\u2200','fork':'\\u22D4','forkv':'\\u2AD9','Fouriertrf':'\\u2131','fpartint':'\\u2A0D','frac12':'\\xBD','frac13':'\\u2153','frac14':'\\xBC','frac15':'\\u2155','frac16':'\\u2159','frac18':'\\u215B','frac23':'\\u2154','frac25':'\\u2156','frac34':'\\xBE','frac35':'\\u2157','frac38':'\\u215C','frac45':'\\u2158','frac56':'\\u215A','frac58':'\\u215D','frac78':'\\u215E','frasl':'\\u2044','frown':'\\u2322','fscr':'\\uD835\\uDCBB','Fscr':'\\u2131','gacute':'\\u01F5','gamma':'\\u03B3','Gamma':'\\u0393','gammad':'\\u03DD','Gammad':'\\u03DC','gap':'\\u2A86','gbreve':'\\u011F','Gbreve':'\\u011E','Gcedil':'\\u0122','gcirc':'\\u011D','Gcirc':'\\u011C','gcy':'\\u0433','Gcy':'\\u0413','gdot':'\\u0121','Gdot':'\\u0120','ge':'\\u2265','gE':'\\u2267','gel':'\\u22DB','gEl':'\\u2A8C','geq':'\\u2265','geqq':'\\u2267','geqslant':'\\u2A7E','ges':'\\u2A7E','gescc':'\\u2AA9','gesdot':'\\u2A80','gesdoto':'\\u2A82','gesdotol':'\\u2A84','gesl':'\\u22DB\\uFE00','gesles':'\\u2A94','gfr':'\\uD835\\uDD24','Gfr':'\\uD835\\uDD0A','gg':'\\u226B','Gg':'\\u22D9','ggg':'\\u22D9','gimel':'\\u2137','gjcy':'\\u0453','GJcy':'\\u0403','gl':'\\u2277','gla':'\\u2AA5','glE':'\\u2A92','glj':'\\u2AA4','gnap':'\\u2A8A','gnapprox':'\\u2A8A','gne':'\\u2A88','gnE':'\\u2269','gneq':'\\u2A88','gneqq':'\\u2269','gnsim':'\\u22E7','gopf':'\\uD835\\uDD58','Gopf':'\\uD835\\uDD3E','grave':'`','GreaterEqual':'\\u2265','GreaterEqualLess':'\\u22DB','GreaterFullEqual':'\\u2267','GreaterGreater':'\\u2AA2','GreaterLess':'\\u2277','GreaterSlantEqual':'\\u2A7E','GreaterTilde':'\\u2273','gscr':'\\u210A','Gscr':'\\uD835\\uDCA2','gsim':'\\u2273','gsime':'\\u2A8E','gsiml':'\\u2A90','gt':'>','Gt':'\\u226B','GT':'>','gtcc':'\\u2AA7','gtcir':'\\u2A7A','gtdot':'\\u22D7','gtlPar':'\\u2995','gtquest':'\\u2A7C','gtrapprox':'\\u2A86','gtrarr':'\\u2978','gtrdot':'\\u22D7','gtreqless':'\\u22DB','gtreqqless':'\\u2A8C','gtrless':'\\u2277','gtrsim':'\\u2273','gvertneqq':'\\u2269\\uFE00','gvnE':'\\u2269\\uFE00','Hacek':'\\u02C7','hairsp':'\\u200A','half':'\\xBD','hamilt':'\\u210B','hardcy':'\\u044A','HARDcy':'\\u042A','harr':'\\u2194','hArr':'\\u21D4','harrcir':'\\u2948','harrw':'\\u21AD','Hat':'^','hbar':'\\u210F','hcirc':'\\u0125','Hcirc':'\\u0124','hearts':'\\u2665','heartsuit':'\\u2665','hellip':'\\u2026','hercon':'\\u22B9','hfr':'\\uD835\\uDD25','Hfr':'\\u210C','HilbertSpace':'\\u210B','hksearow':'\\u2925','hkswarow':'\\u2926','hoarr':'\\u21FF','homtht':'\\u223B','hookleftarrow':'\\u21A9','hookrightarrow':'\\u21AA','hopf':'\\uD835\\uDD59','Hopf':'\\u210D','horbar':'\\u2015','HorizontalLine':'\\u2500','hscr':'\\uD835\\uDCBD','Hscr':'\\u210B','hslash':'\\u210F','hstrok':'\\u0127','Hstrok':'\\u0126','HumpDownHump':'\\u224E','HumpEqual':'\\u224F','hybull':'\\u2043','hyphen':'\\u2010','iacute':'\\xED','Iacute':'\\xCD','ic':'\\u2063','icirc':'\\xEE','Icirc':'\\xCE','icy':'\\u0438','Icy':'\\u0418','Idot':'\\u0130','iecy':'\\u0435','IEcy':'\\u0415','iexcl':'\\xA1','iff':'\\u21D4','ifr':'\\uD835\\uDD26','Ifr':'\\u2111','igrave':'\\xEC','Igrave':'\\xCC','ii':'\\u2148','iiiint':'\\u2A0C','iiint':'\\u222D','iinfin':'\\u29DC','iiota':'\\u2129','ijlig':'\\u0133','IJlig':'\\u0132','Im':'\\u2111','imacr':'\\u012B','Imacr':'\\u012A','image':'\\u2111','ImaginaryI':'\\u2148','imagline':'\\u2110','imagpart':'\\u2111','imath':'\\u0131','imof':'\\u22B7','imped':'\\u01B5','Implies':'\\u21D2','in':'\\u2208','incare':'\\u2105','infin':'\\u221E','infintie':'\\u29DD','inodot':'\\u0131','int':'\\u222B','Int':'\\u222C','intcal':'\\u22BA','integers':'\\u2124','Integral':'\\u222B','intercal':'\\u22BA','Intersection':'\\u22C2','intlarhk':'\\u2A17','intprod':'\\u2A3C','InvisibleComma':'\\u2063','InvisibleTimes':'\\u2062','iocy':'\\u0451','IOcy':'\\u0401','iogon':'\\u012F','Iogon':'\\u012E','iopf':'\\uD835\\uDD5A','Iopf':'\\uD835\\uDD40','iota':'\\u03B9','Iota':'\\u0399','iprod':'\\u2A3C','iquest':'\\xBF','iscr':'\\uD835\\uDCBE','Iscr':'\\u2110','isin':'\\u2208','isindot':'\\u22F5','isinE':'\\u22F9','isins':'\\u22F4','isinsv':'\\u22F3','isinv':'\\u2208','it':'\\u2062','itilde':'\\u0129','Itilde':'\\u0128','iukcy':'\\u0456','Iukcy':'\\u0406','iuml':'\\xEF','Iuml':'\\xCF','jcirc':'\\u0135','Jcirc':'\\u0134','jcy':'\\u0439','Jcy':'\\u0419','jfr':'\\uD835\\uDD27','Jfr':'\\uD835\\uDD0D','jmath':'\\u0237','jopf':'\\uD835\\uDD5B','Jopf':'\\uD835\\uDD41','jscr':'\\uD835\\uDCBF','Jscr':'\\uD835\\uDCA5','jsercy':'\\u0458','Jsercy':'\\u0408','jukcy':'\\u0454','Jukcy':'\\u0404','kappa':'\\u03BA','Kappa':'\\u039A','kappav':'\\u03F0','kcedil':'\\u0137','Kcedil':'\\u0136','kcy':'\\u043A','Kcy':'\\u041A','kfr':'\\uD835\\uDD28','Kfr':'\\uD835\\uDD0E','kgreen':'\\u0138','khcy':'\\u0445','KHcy':'\\u0425','kjcy':'\\u045C','KJcy':'\\u040C','kopf':'\\uD835\\uDD5C','Kopf':'\\uD835\\uDD42','kscr':'\\uD835\\uDCC0','Kscr':'\\uD835\\uDCA6','lAarr':'\\u21DA','lacute':'\\u013A','Lacute':'\\u0139','laemptyv':'\\u29B4','lagran':'\\u2112','lambda':'\\u03BB','Lambda':'\\u039B','lang':'\\u27E8','Lang':'\\u27EA','langd':'\\u2991','langle':'\\u27E8','lap':'\\u2A85','Laplacetrf':'\\u2112','laquo':'\\xAB','larr':'\\u2190','lArr':'\\u21D0','Larr':'\\u219E','larrb':'\\u21E4','larrbfs':'\\u291F','larrfs':'\\u291D','larrhk':'\\u21A9','larrlp':'\\u21AB','larrpl':'\\u2939','larrsim':'\\u2973','larrtl':'\\u21A2','lat':'\\u2AAB','latail':'\\u2919','lAtail':'\\u291B','late':'\\u2AAD','lates':'\\u2AAD\\uFE00','lbarr':'\\u290C','lBarr':'\\u290E','lbbrk':'\\u2772','lbrace':'{','lbrack':'[','lbrke':'\\u298B','lbrksld':'\\u298F','lbrkslu':'\\u298D','lcaron':'\\u013E','Lcaron':'\\u013D','lcedil':'\\u013C','Lcedil':'\\u013B','lceil':'\\u2308','lcub':'{','lcy':'\\u043B','Lcy':'\\u041B','ldca':'\\u2936','ldquo':'\\u201C','ldquor':'\\u201E','ldrdhar':'\\u2967','ldrushar':'\\u294B','ldsh':'\\u21B2','le':'\\u2264','lE':'\\u2266','LeftAngleBracket':'\\u27E8','leftarrow':'\\u2190','Leftarrow':'\\u21D0','LeftArrow':'\\u2190','LeftArrowBar':'\\u21E4','LeftArrowRightArrow':'\\u21C6','leftarrowtail':'\\u21A2','LeftCeiling':'\\u2308','LeftDoubleBracket':'\\u27E6','LeftDownTeeVector':'\\u2961','LeftDownVector':'\\u21C3','LeftDownVectorBar':'\\u2959','LeftFloor':'\\u230A','leftharpoondown':'\\u21BD','leftharpoonup':'\\u21BC','leftleftarrows':'\\u21C7','leftrightarrow':'\\u2194','Leftrightarrow':'\\u21D4','LeftRightArrow':'\\u2194','leftrightarrows':'\\u21C6','leftrightharpoons':'\\u21CB','leftrightsquigarrow':'\\u21AD','LeftRightVector':'\\u294E','LeftTee':'\\u22A3','LeftTeeArrow':'\\u21A4','LeftTeeVector':'\\u295A','leftthreetimes':'\\u22CB','LeftTriangle':'\\u22B2','LeftTriangleBar':'\\u29CF','LeftTriangleEqual':'\\u22B4','LeftUpDownVector':'\\u2951','LeftUpTeeVector':'\\u2960','LeftUpVector':'\\u21BF','LeftUpVectorBar':'\\u2958','LeftVector':'\\u21BC','LeftVectorBar':'\\u2952','leg':'\\u22DA','lEg':'\\u2A8B','leq':'\\u2264','leqq':'\\u2266','leqslant':'\\u2A7D','les':'\\u2A7D','lescc':'\\u2AA8','lesdot':'\\u2A7F','lesdoto':'\\u2A81','lesdotor':'\\u2A83','lesg':'\\u22DA\\uFE00','lesges':'\\u2A93','lessapprox':'\\u2A85','lessdot':'\\u22D6','lesseqgtr':'\\u22DA','lesseqqgtr':'\\u2A8B','LessEqualGreater':'\\u22DA','LessFullEqual':'\\u2266','LessGreater':'\\u2276','lessgtr':'\\u2276','LessLess':'\\u2AA1','lesssim':'\\u2272','LessSlantEqual':'\\u2A7D','LessTilde':'\\u2272','lfisht':'\\u297C','lfloor':'\\u230A','lfr':'\\uD835\\uDD29','Lfr':'\\uD835\\uDD0F','lg':'\\u2276','lgE':'\\u2A91','lHar':'\\u2962','lhard':'\\u21BD','lharu':'\\u21BC','lharul':'\\u296A','lhblk':'\\u2584','ljcy':'\\u0459','LJcy':'\\u0409','ll':'\\u226A','Ll':'\\u22D8','llarr':'\\u21C7','llcorner':'\\u231E','Lleftarrow':'\\u21DA','llhard':'\\u296B','lltri':'\\u25FA','lmidot':'\\u0140','Lmidot':'\\u013F','lmoust':'\\u23B0','lmoustache':'\\u23B0','lnap':'\\u2A89','lnapprox':'\\u2A89','lne':'\\u2A87','lnE':'\\u2268','lneq':'\\u2A87','lneqq':'\\u2268','lnsim':'\\u22E6','loang':'\\u27EC','loarr':'\\u21FD','lobrk':'\\u27E6','longleftarrow':'\\u27F5','Longleftarrow':'\\u27F8','LongLeftArrow':'\\u27F5','longleftrightarrow':'\\u27F7','Longleftrightarrow':'\\u27FA','LongLeftRightArrow':'\\u27F7','longmapsto':'\\u27FC','longrightarrow':'\\u27F6','Longrightarrow':'\\u27F9','LongRightArrow':'\\u27F6','looparrowleft':'\\u21AB','looparrowright':'\\u21AC','lopar':'\\u2985','lopf':'\\uD835\\uDD5D','Lopf':'\\uD835\\uDD43','loplus':'\\u2A2D','lotimes':'\\u2A34','lowast':'\\u2217','lowbar':'_','LowerLeftArrow':'\\u2199','LowerRightArrow':'\\u2198','loz':'\\u25CA','lozenge':'\\u25CA','lozf':'\\u29EB','lpar':'(','lparlt':'\\u2993','lrarr':'\\u21C6','lrcorner':'\\u231F','lrhar':'\\u21CB','lrhard':'\\u296D','lrm':'\\u200E','lrtri':'\\u22BF','lsaquo':'\\u2039','lscr':'\\uD835\\uDCC1','Lscr':'\\u2112','lsh':'\\u21B0','Lsh':'\\u21B0','lsim':'\\u2272','lsime':'\\u2A8D','lsimg':'\\u2A8F','lsqb':'[','lsquo':'\\u2018','lsquor':'\\u201A','lstrok':'\\u0142','Lstrok':'\\u0141','lt':'<','Lt':'\\u226A','LT':'<','ltcc':'\\u2AA6','ltcir':'\\u2A79','ltdot':'\\u22D6','lthree':'\\u22CB','ltimes':'\\u22C9','ltlarr':'\\u2976','ltquest':'\\u2A7B','ltri':'\\u25C3','ltrie':'\\u22B4','ltrif':'\\u25C2','ltrPar':'\\u2996','lurdshar':'\\u294A','luruhar':'\\u2966','lvertneqq':'\\u2268\\uFE00','lvnE':'\\u2268\\uFE00','macr':'\\xAF','male':'\\u2642','malt':'\\u2720','maltese':'\\u2720','map':'\\u21A6','Map':'\\u2905','mapsto':'\\u21A6','mapstodown':'\\u21A7','mapstoleft':'\\u21A4','mapstoup':'\\u21A5','marker':'\\u25AE','mcomma':'\\u2A29','mcy':'\\u043C','Mcy':'\\u041C','mdash':'\\u2014','mDDot':'\\u223A','measuredangle':'\\u2221','MediumSpace':'\\u205F','Mellintrf':'\\u2133','mfr':'\\uD835\\uDD2A','Mfr':'\\uD835\\uDD10','mho':'\\u2127','micro':'\\xB5','mid':'\\u2223','midast':'*','midcir':'\\u2AF0','middot':'\\xB7','minus':'\\u2212','minusb':'\\u229F','minusd':'\\u2238','minusdu':'\\u2A2A','MinusPlus':'\\u2213','mlcp':'\\u2ADB','mldr':'\\u2026','mnplus':'\\u2213','models':'\\u22A7','mopf':'\\uD835\\uDD5E','Mopf':'\\uD835\\uDD44','mp':'\\u2213','mscr':'\\uD835\\uDCC2','Mscr':'\\u2133','mstpos':'\\u223E','mu':'\\u03BC','Mu':'\\u039C','multimap':'\\u22B8','mumap':'\\u22B8','nabla':'\\u2207','nacute':'\\u0144','Nacute':'\\u0143','nang':'\\u2220\\u20D2','nap':'\\u2249','napE':'\\u2A70\\u0338','napid':'\\u224B\\u0338','napos':'\\u0149','napprox':'\\u2249','natur':'\\u266E','natural':'\\u266E','naturals':'\\u2115','nbsp':'\\xA0','nbump':'\\u224E\\u0338','nbumpe':'\\u224F\\u0338','ncap':'\\u2A43','ncaron':'\\u0148','Ncaron':'\\u0147','ncedil':'\\u0146','Ncedil':'\\u0145','ncong':'\\u2247','ncongdot':'\\u2A6D\\u0338','ncup':'\\u2A42','ncy':'\\u043D','Ncy':'\\u041D','ndash':'\\u2013','ne':'\\u2260','nearhk':'\\u2924','nearr':'\\u2197','neArr':'\\u21D7','nearrow':'\\u2197','nedot':'\\u2250\\u0338','NegativeMediumSpace':'\\u200B','NegativeThickSpace':'\\u200B','NegativeThinSpace':'\\u200B','NegativeVeryThinSpace':'\\u200B','nequiv':'\\u2262','nesear':'\\u2928','nesim':'\\u2242\\u0338','NestedGreaterGreater':'\\u226B','NestedLessLess':'\\u226A','NewLine':'\\n','nexist':'\\u2204','nexists':'\\u2204','nfr':'\\uD835\\uDD2B','Nfr':'\\uD835\\uDD11','nge':'\\u2271','ngE':'\\u2267\\u0338','ngeq':'\\u2271','ngeqq':'\\u2267\\u0338','ngeqslant':'\\u2A7E\\u0338','nges':'\\u2A7E\\u0338','nGg':'\\u22D9\\u0338','ngsim':'\\u2275','ngt':'\\u226F','nGt':'\\u226B\\u20D2','ngtr':'\\u226F','nGtv':'\\u226B\\u0338','nharr':'\\u21AE','nhArr':'\\u21CE','nhpar':'\\u2AF2','ni':'\\u220B','nis':'\\u22FC','nisd':'\\u22FA','niv':'\\u220B','njcy':'\\u045A','NJcy':'\\u040A','nlarr':'\\u219A','nlArr':'\\u21CD','nldr':'\\u2025','nle':'\\u2270','nlE':'\\u2266\\u0338','nleftarrow':'\\u219A','nLeftarrow':'\\u21CD','nleftrightarrow':'\\u21AE','nLeftrightarrow':'\\u21CE','nleq':'\\u2270','nleqq':'\\u2266\\u0338','nleqslant':'\\u2A7D\\u0338','nles':'\\u2A7D\\u0338','nless':'\\u226E','nLl':'\\u22D8\\u0338','nlsim':'\\u2274','nlt':'\\u226E','nLt':'\\u226A\\u20D2','nltri':'\\u22EA','nltrie':'\\u22EC','nLtv':'\\u226A\\u0338','nmid':'\\u2224','NoBreak':'\\u2060','NonBreakingSpace':'\\xA0','nopf':'\\uD835\\uDD5F','Nopf':'\\u2115','not':'\\xAC','Not':'\\u2AEC','NotCongruent':'\\u2262','NotCupCap':'\\u226D','NotDoubleVerticalBar':'\\u2226','NotElement':'\\u2209','NotEqual':'\\u2260','NotEqualTilde':'\\u2242\\u0338','NotExists':'\\u2204','NotGreater':'\\u226F','NotGreaterEqual':'\\u2271','NotGreaterFullEqual':'\\u2267\\u0338','NotGreaterGreater':'\\u226B\\u0338','NotGreaterLess':'\\u2279','NotGreaterSlantEqual':'\\u2A7E\\u0338','NotGreaterTilde':'\\u2275','NotHumpDownHump':'\\u224E\\u0338','NotHumpEqual':'\\u224F\\u0338','notin':'\\u2209','notindot':'\\u22F5\\u0338','notinE':'\\u22F9\\u0338','notinva':'\\u2209','notinvb':'\\u22F7','notinvc':'\\u22F6','NotLeftTriangle':'\\u22EA','NotLeftTriangleBar':'\\u29CF\\u0338','NotLeftTriangleEqual':'\\u22EC','NotLess':'\\u226E','NotLessEqual':'\\u2270','NotLessGreater':'\\u2278','NotLessLess':'\\u226A\\u0338','NotLessSlantEqual':'\\u2A7D\\u0338','NotLessTilde':'\\u2274','NotNestedGreaterGreater':'\\u2AA2\\u0338','NotNestedLessLess':'\\u2AA1\\u0338','notni':'\\u220C','notniva':'\\u220C','notnivb':'\\u22FE','notnivc':'\\u22FD','NotPrecedes':'\\u2280','NotPrecedesEqual':'\\u2AAF\\u0338','NotPrecedesSlantEqual':'\\u22E0','NotReverseElement':'\\u220C','NotRightTriangle':'\\u22EB','NotRightTriangleBar':'\\u29D0\\u0338','NotRightTriangleEqual':'\\u22ED','NotSquareSubset':'\\u228F\\u0338','NotSquareSubsetEqual':'\\u22E2','NotSquareSuperset':'\\u2290\\u0338','NotSquareSupersetEqual':'\\u22E3','NotSubset':'\\u2282\\u20D2','NotSubsetEqual':'\\u2288','NotSucceeds':'\\u2281','NotSucceedsEqual':'\\u2AB0\\u0338','NotSucceedsSlantEqual':'\\u22E1','NotSucceedsTilde':'\\u227F\\u0338','NotSuperset':'\\u2283\\u20D2','NotSupersetEqual':'\\u2289','NotTilde':'\\u2241','NotTildeEqual':'\\u2244','NotTildeFullEqual':'\\u2247','NotTildeTilde':'\\u2249','NotVerticalBar':'\\u2224','npar':'\\u2226','nparallel':'\\u2226','nparsl':'\\u2AFD\\u20E5','npart':'\\u2202\\u0338','npolint':'\\u2A14','npr':'\\u2280','nprcue':'\\u22E0','npre':'\\u2AAF\\u0338','nprec':'\\u2280','npreceq':'\\u2AAF\\u0338','nrarr':'\\u219B','nrArr':'\\u21CF','nrarrc':'\\u2933\\u0338','nrarrw':'\\u219D\\u0338','nrightarrow':'\\u219B','nRightarrow':'\\u21CF','nrtri':'\\u22EB','nrtrie':'\\u22ED','nsc':'\\u2281','nsccue':'\\u22E1','nsce':'\\u2AB0\\u0338','nscr':'\\uD835\\uDCC3','Nscr':'\\uD835\\uDCA9','nshortmid':'\\u2224','nshortparallel':'\\u2226','nsim':'\\u2241','nsime':'\\u2244','nsimeq':'\\u2244','nsmid':'\\u2224','nspar':'\\u2226','nsqsube':'\\u22E2','nsqsupe':'\\u22E3','nsub':'\\u2284','nsube':'\\u2288','nsubE':'\\u2AC5\\u0338','nsubset':'\\u2282\\u20D2','nsubseteq':'\\u2288','nsubseteqq':'\\u2AC5\\u0338','nsucc':'\\u2281','nsucceq':'\\u2AB0\\u0338','nsup':'\\u2285','nsupe':'\\u2289','nsupE':'\\u2AC6\\u0338','nsupset':'\\u2283\\u20D2','nsupseteq':'\\u2289','nsupseteqq':'\\u2AC6\\u0338','ntgl':'\\u2279','ntilde':'\\xF1','Ntilde':'\\xD1','ntlg':'\\u2278','ntriangleleft':'\\u22EA','ntrianglelefteq':'\\u22EC','ntriangleright':'\\u22EB','ntrianglerighteq':'\\u22ED','nu':'\\u03BD','Nu':'\\u039D','num':'#','numero':'\\u2116','numsp':'\\u2007','nvap':'\\u224D\\u20D2','nvdash':'\\u22AC','nvDash':'\\u22AD','nVdash':'\\u22AE','nVDash':'\\u22AF','nvge':'\\u2265\\u20D2','nvgt':'>\\u20D2','nvHarr':'\\u2904','nvinfin':'\\u29DE','nvlArr':'\\u2902','nvle':'\\u2264\\u20D2','nvlt':'<\\u20D2','nvltrie':'\\u22B4\\u20D2','nvrArr':'\\u2903','nvrtrie':'\\u22B5\\u20D2','nvsim':'\\u223C\\u20D2','nwarhk':'\\u2923','nwarr':'\\u2196','nwArr':'\\u21D6','nwarrow':'\\u2196','nwnear':'\\u2927','oacute':'\\xF3','Oacute':'\\xD3','oast':'\\u229B','ocir':'\\u229A','ocirc':'\\xF4','Ocirc':'\\xD4','ocy':'\\u043E','Ocy':'\\u041E','odash':'\\u229D','odblac':'\\u0151','Odblac':'\\u0150','odiv':'\\u2A38','odot':'\\u2299','odsold':'\\u29BC','oelig':'\\u0153','OElig':'\\u0152','ofcir':'\\u29BF','ofr':'\\uD835\\uDD2C','Ofr':'\\uD835\\uDD12','ogon':'\\u02DB','ograve':'\\xF2','Ograve':'\\xD2','ogt':'\\u29C1','ohbar':'\\u29B5','ohm':'\\u03A9','oint':'\\u222E','olarr':'\\u21BA','olcir':'\\u29BE','olcross':'\\u29BB','oline':'\\u203E','olt':'\\u29C0','omacr':'\\u014D','Omacr':'\\u014C','omega':'\\u03C9','Omega':'\\u03A9','omicron':'\\u03BF','Omicron':'\\u039F','omid':'\\u29B6','ominus':'\\u2296','oopf':'\\uD835\\uDD60','Oopf':'\\uD835\\uDD46','opar':'\\u29B7','OpenCurlyDoubleQuote':'\\u201C','OpenCurlyQuote':'\\u2018','operp':'\\u29B9','oplus':'\\u2295','or':'\\u2228','Or':'\\u2A54','orarr':'\\u21BB','ord':'\\u2A5D','order':'\\u2134','orderof':'\\u2134','ordf':'\\xAA','ordm':'\\xBA','origof':'\\u22B6','oror':'\\u2A56','orslope':'\\u2A57','orv':'\\u2A5B','oS':'\\u24C8','oscr':'\\u2134','Oscr':'\\uD835\\uDCAA','oslash':'\\xF8','Oslash':'\\xD8','osol':'\\u2298','otilde':'\\xF5','Otilde':'\\xD5','otimes':'\\u2297','Otimes':'\\u2A37','otimesas':'\\u2A36','ouml':'\\xF6','Ouml':'\\xD6','ovbar':'\\u233D','OverBar':'\\u203E','OverBrace':'\\u23DE','OverBracket':'\\u23B4','OverParenthesis':'\\u23DC','par':'\\u2225','para':'\\xB6','parallel':'\\u2225','parsim':'\\u2AF3','parsl':'\\u2AFD','part':'\\u2202','PartialD':'\\u2202','pcy':'\\u043F','Pcy':'\\u041F','percnt':'%','period':'.','permil':'\\u2030','perp':'\\u22A5','pertenk':'\\u2031','pfr':'\\uD835\\uDD2D','Pfr':'\\uD835\\uDD13','phi':'\\u03C6','Phi':'\\u03A6','phiv':'\\u03D5','phmmat':'\\u2133','phone':'\\u260E','pi':'\\u03C0','Pi':'\\u03A0','pitchfork':'\\u22D4','piv':'\\u03D6','planck':'\\u210F','planckh':'\\u210E','plankv':'\\u210F','plus':'+','plusacir':'\\u2A23','plusb':'\\u229E','pluscir':'\\u2A22','plusdo':'\\u2214','plusdu':'\\u2A25','pluse':'\\u2A72','PlusMinus':'\\xB1','plusmn':'\\xB1','plussim':'\\u2A26','plustwo':'\\u2A27','pm':'\\xB1','Poincareplane':'\\u210C','pointint':'\\u2A15','popf':'\\uD835\\uDD61','Popf':'\\u2119','pound':'\\xA3','pr':'\\u227A','Pr':'\\u2ABB','prap':'\\u2AB7','prcue':'\\u227C','pre':'\\u2AAF','prE':'\\u2AB3','prec':'\\u227A','precapprox':'\\u2AB7','preccurlyeq':'\\u227C','Precedes':'\\u227A','PrecedesEqual':'\\u2AAF','PrecedesSlantEqual':'\\u227C','PrecedesTilde':'\\u227E','preceq':'\\u2AAF','precnapprox':'\\u2AB9','precneqq':'\\u2AB5','precnsim':'\\u22E8','precsim':'\\u227E','prime':'\\u2032','Prime':'\\u2033','primes':'\\u2119','prnap':'\\u2AB9','prnE':'\\u2AB5','prnsim':'\\u22E8','prod':'\\u220F','Product':'\\u220F','profalar':'\\u232E','profline':'\\u2312','profsurf':'\\u2313','prop':'\\u221D','Proportion':'\\u2237','Proportional':'\\u221D','propto':'\\u221D','prsim':'\\u227E','prurel':'\\u22B0','pscr':'\\uD835\\uDCC5','Pscr':'\\uD835\\uDCAB','psi':'\\u03C8','Psi':'\\u03A8','puncsp':'\\u2008','qfr':'\\uD835\\uDD2E','Qfr':'\\uD835\\uDD14','qint':'\\u2A0C','qopf':'\\uD835\\uDD62','Qopf':'\\u211A','qprime':'\\u2057','qscr':'\\uD835\\uDCC6','Qscr':'\\uD835\\uDCAC','quaternions':'\\u210D','quatint':'\\u2A16','quest':'?','questeq':'\\u225F','quot':'\"','QUOT':'\"','rAarr':'\\u21DB','race':'\\u223D\\u0331','racute':'\\u0155','Racute':'\\u0154','radic':'\\u221A','raemptyv':'\\u29B3','rang':'\\u27E9','Rang':'\\u27EB','rangd':'\\u2992','range':'\\u29A5','rangle':'\\u27E9','raquo':'\\xBB','rarr':'\\u2192','rArr':'\\u21D2','Rarr':'\\u21A0','rarrap':'\\u2975','rarrb':'\\u21E5','rarrbfs':'\\u2920','rarrc':'\\u2933','rarrfs':'\\u291E','rarrhk':'\\u21AA','rarrlp':'\\u21AC','rarrpl':'\\u2945','rarrsim':'\\u2974','rarrtl':'\\u21A3','Rarrtl':'\\u2916','rarrw':'\\u219D','ratail':'\\u291A','rAtail':'\\u291C','ratio':'\\u2236','rationals':'\\u211A','rbarr':'\\u290D','rBarr':'\\u290F','RBarr':'\\u2910','rbbrk':'\\u2773','rbrace':'}','rbrack':']','rbrke':'\\u298C','rbrksld':'\\u298E','rbrkslu':'\\u2990','rcaron':'\\u0159','Rcaron':'\\u0158','rcedil':'\\u0157','Rcedil':'\\u0156','rceil':'\\u2309','rcub':'}','rcy':'\\u0440','Rcy':'\\u0420','rdca':'\\u2937','rdldhar':'\\u2969','rdquo':'\\u201D','rdquor':'\\u201D','rdsh':'\\u21B3','Re':'\\u211C','real':'\\u211C','realine':'\\u211B','realpart':'\\u211C','reals':'\\u211D','rect':'\\u25AD','reg':'\\xAE','REG':'\\xAE','ReverseElement':'\\u220B','ReverseEquilibrium':'\\u21CB','ReverseUpEquilibrium':'\\u296F','rfisht':'\\u297D','rfloor':'\\u230B','rfr':'\\uD835\\uDD2F','Rfr':'\\u211C','rHar':'\\u2964','rhard':'\\u21C1','rharu':'\\u21C0','rharul':'\\u296C','rho':'\\u03C1','Rho':'\\u03A1','rhov':'\\u03F1','RightAngleBracket':'\\u27E9','rightarrow':'\\u2192','Rightarrow':'\\u21D2','RightArrow':'\\u2192','RightArrowBar':'\\u21E5','RightArrowLeftArrow':'\\u21C4','rightarrowtail':'\\u21A3','RightCeiling':'\\u2309','RightDoubleBracket':'\\u27E7','RightDownTeeVector':'\\u295D','RightDownVector':'\\u21C2','RightDownVectorBar':'\\u2955','RightFloor':'\\u230B','rightharpoondown':'\\u21C1','rightharpoonup':'\\u21C0','rightleftarrows':'\\u21C4','rightleftharpoons':'\\u21CC','rightrightarrows':'\\u21C9','rightsquigarrow':'\\u219D','RightTee':'\\u22A2','RightTeeArrow':'\\u21A6','RightTeeVector':'\\u295B','rightthreetimes':'\\u22CC','RightTriangle':'\\u22B3','RightTriangleBar':'\\u29D0','RightTriangleEqual':'\\u22B5','RightUpDownVector':'\\u294F','RightUpTeeVector':'\\u295C','RightUpVector':'\\u21BE','RightUpVectorBar':'\\u2954','RightVector':'\\u21C0','RightVectorBar':'\\u2953','ring':'\\u02DA','risingdotseq':'\\u2253','rlarr':'\\u21C4','rlhar':'\\u21CC','rlm':'\\u200F','rmoust':'\\u23B1','rmoustache':'\\u23B1','rnmid':'\\u2AEE','roang':'\\u27ED','roarr':'\\u21FE','robrk':'\\u27E7','ropar':'\\u2986','ropf':'\\uD835\\uDD63','Ropf':'\\u211D','roplus':'\\u2A2E','rotimes':'\\u2A35','RoundImplies':'\\u2970','rpar':')','rpargt':'\\u2994','rppolint':'\\u2A12','rrarr':'\\u21C9','Rrightarrow':'\\u21DB','rsaquo':'\\u203A','rscr':'\\uD835\\uDCC7','Rscr':'\\u211B','rsh':'\\u21B1','Rsh':'\\u21B1','rsqb':']','rsquo':'\\u2019','rsquor':'\\u2019','rthree':'\\u22CC','rtimes':'\\u22CA','rtri':'\\u25B9','rtrie':'\\u22B5','rtrif':'\\u25B8','rtriltri':'\\u29CE','RuleDelayed':'\\u29F4','ruluhar':'\\u2968','rx':'\\u211E','sacute':'\\u015B','Sacute':'\\u015A','sbquo':'\\u201A','sc':'\\u227B','Sc':'\\u2ABC','scap':'\\u2AB8','scaron':'\\u0161','Scaron':'\\u0160','sccue':'\\u227D','sce':'\\u2AB0','scE':'\\u2AB4','scedil':'\\u015F','Scedil':'\\u015E','scirc':'\\u015D','Scirc':'\\u015C','scnap':'\\u2ABA','scnE':'\\u2AB6','scnsim':'\\u22E9','scpolint':'\\u2A13','scsim':'\\u227F','scy':'\\u0441','Scy':'\\u0421','sdot':'\\u22C5','sdotb':'\\u22A1','sdote':'\\u2A66','searhk':'\\u2925','searr':'\\u2198','seArr':'\\u21D8','searrow':'\\u2198','sect':'\\xA7','semi':';','seswar':'\\u2929','setminus':'\\u2216','setmn':'\\u2216','sext':'\\u2736','sfr':'\\uD835\\uDD30','Sfr':'\\uD835\\uDD16','sfrown':'\\u2322','sharp':'\\u266F','shchcy':'\\u0449','SHCHcy':'\\u0429','shcy':'\\u0448','SHcy':'\\u0428','ShortDownArrow':'\\u2193','ShortLeftArrow':'\\u2190','shortmid':'\\u2223','shortparallel':'\\u2225','ShortRightArrow':'\\u2192','ShortUpArrow':'\\u2191','shy':'\\xAD','sigma':'\\u03C3','Sigma':'\\u03A3','sigmaf':'\\u03C2','sigmav':'\\u03C2','sim':'\\u223C','simdot':'\\u2A6A','sime':'\\u2243','simeq':'\\u2243','simg':'\\u2A9E','simgE':'\\u2AA0','siml':'\\u2A9D','simlE':'\\u2A9F','simne':'\\u2246','simplus':'\\u2A24','simrarr':'\\u2972','slarr':'\\u2190','SmallCircle':'\\u2218','smallsetminus':'\\u2216','smashp':'\\u2A33','smeparsl':'\\u29E4','smid':'\\u2223','smile':'\\u2323','smt':'\\u2AAA','smte':'\\u2AAC','smtes':'\\u2AAC\\uFE00','softcy':'\\u044C','SOFTcy':'\\u042C','sol':'/','solb':'\\u29C4','solbar':'\\u233F','sopf':'\\uD835\\uDD64','Sopf':'\\uD835\\uDD4A','spades':'\\u2660','spadesuit':'\\u2660','spar':'\\u2225','sqcap':'\\u2293','sqcaps':'\\u2293\\uFE00','sqcup':'\\u2294','sqcups':'\\u2294\\uFE00','Sqrt':'\\u221A','sqsub':'\\u228F','sqsube':'\\u2291','sqsubset':'\\u228F','sqsubseteq':'\\u2291','sqsup':'\\u2290','sqsupe':'\\u2292','sqsupset':'\\u2290','sqsupseteq':'\\u2292','squ':'\\u25A1','square':'\\u25A1','Square':'\\u25A1','SquareIntersection':'\\u2293','SquareSubset':'\\u228F','SquareSubsetEqual':'\\u2291','SquareSuperset':'\\u2290','SquareSupersetEqual':'\\u2292','SquareUnion':'\\u2294','squarf':'\\u25AA','squf':'\\u25AA','srarr':'\\u2192','sscr':'\\uD835\\uDCC8','Sscr':'\\uD835\\uDCAE','ssetmn':'\\u2216','ssmile':'\\u2323','sstarf':'\\u22C6','star':'\\u2606','Star':'\\u22C6','starf':'\\u2605','straightepsilon':'\\u03F5','straightphi':'\\u03D5','strns':'\\xAF','sub':'\\u2282','Sub':'\\u22D0','subdot':'\\u2ABD','sube':'\\u2286','subE':'\\u2AC5','subedot':'\\u2AC3','submult':'\\u2AC1','subne':'\\u228A','subnE':'\\u2ACB','subplus':'\\u2ABF','subrarr':'\\u2979','subset':'\\u2282','Subset':'\\u22D0','subseteq':'\\u2286','subseteqq':'\\u2AC5','SubsetEqual':'\\u2286','subsetneq':'\\u228A','subsetneqq':'\\u2ACB','subsim':'\\u2AC7','subsub':'\\u2AD5','subsup':'\\u2AD3','succ':'\\u227B','succapprox':'\\u2AB8','succcurlyeq':'\\u227D','Succeeds':'\\u227B','SucceedsEqual':'\\u2AB0','SucceedsSlantEqual':'\\u227D','SucceedsTilde':'\\u227F','succeq':'\\u2AB0','succnapprox':'\\u2ABA','succneqq':'\\u2AB6','succnsim':'\\u22E9','succsim':'\\u227F','SuchThat':'\\u220B','sum':'\\u2211','Sum':'\\u2211','sung':'\\u266A','sup':'\\u2283','Sup':'\\u22D1','sup1':'\\xB9','sup2':'\\xB2','sup3':'\\xB3','supdot':'\\u2ABE','supdsub':'\\u2AD8','supe':'\\u2287','supE':'\\u2AC6','supedot':'\\u2AC4','Superset':'\\u2283','SupersetEqual':'\\u2287','suphsol':'\\u27C9','suphsub':'\\u2AD7','suplarr':'\\u297B','supmult':'\\u2AC2','supne':'\\u228B','supnE':'\\u2ACC','supplus':'\\u2AC0','supset':'\\u2283','Supset':'\\u22D1','supseteq':'\\u2287','supseteqq':'\\u2AC6','supsetneq':'\\u228B','supsetneqq':'\\u2ACC','supsim':'\\u2AC8','supsub':'\\u2AD4','supsup':'\\u2AD6','swarhk':'\\u2926','swarr':'\\u2199','swArr':'\\u21D9','swarrow':'\\u2199','swnwar':'\\u292A','szlig':'\\xDF','Tab':'\\t','target':'\\u2316','tau':'\\u03C4','Tau':'\\u03A4','tbrk':'\\u23B4','tcaron':'\\u0165','Tcaron':'\\u0164','tcedil':'\\u0163','Tcedil':'\\u0162','tcy':'\\u0442','Tcy':'\\u0422','tdot':'\\u20DB','telrec':'\\u2315','tfr':'\\uD835\\uDD31','Tfr':'\\uD835\\uDD17','there4':'\\u2234','therefore':'\\u2234','Therefore':'\\u2234','theta':'\\u03B8','Theta':'\\u0398','thetasym':'\\u03D1','thetav':'\\u03D1','thickapprox':'\\u2248','thicksim':'\\u223C','ThickSpace':'\\u205F\\u200A','thinsp':'\\u2009','ThinSpace':'\\u2009','thkap':'\\u2248','thksim':'\\u223C','thorn':'\\xFE','THORN':'\\xDE','tilde':'\\u02DC','Tilde':'\\u223C','TildeEqual':'\\u2243','TildeFullEqual':'\\u2245','TildeTilde':'\\u2248','times':'\\xD7','timesb':'\\u22A0','timesbar':'\\u2A31','timesd':'\\u2A30','tint':'\\u222D','toea':'\\u2928','top':'\\u22A4','topbot':'\\u2336','topcir':'\\u2AF1','topf':'\\uD835\\uDD65','Topf':'\\uD835\\uDD4B','topfork':'\\u2ADA','tosa':'\\u2929','tprime':'\\u2034','trade':'\\u2122','TRADE':'\\u2122','triangle':'\\u25B5','triangledown':'\\u25BF','triangleleft':'\\u25C3','trianglelefteq':'\\u22B4','triangleq':'\\u225C','triangleright':'\\u25B9','trianglerighteq':'\\u22B5','tridot':'\\u25EC','trie':'\\u225C','triminus':'\\u2A3A','TripleDot':'\\u20DB','triplus':'\\u2A39','trisb':'\\u29CD','tritime':'\\u2A3B','trpezium':'\\u23E2','tscr':'\\uD835\\uDCC9','Tscr':'\\uD835\\uDCAF','tscy':'\\u0446','TScy':'\\u0426','tshcy':'\\u045B','TSHcy':'\\u040B','tstrok':'\\u0167','Tstrok':'\\u0166','twixt':'\\u226C','twoheadleftarrow':'\\u219E','twoheadrightarrow':'\\u21A0','uacute':'\\xFA','Uacute':'\\xDA','uarr':'\\u2191','uArr':'\\u21D1','Uarr':'\\u219F','Uarrocir':'\\u2949','ubrcy':'\\u045E','Ubrcy':'\\u040E','ubreve':'\\u016D','Ubreve':'\\u016C','ucirc':'\\xFB','Ucirc':'\\xDB','ucy':'\\u0443','Ucy':'\\u0423','udarr':'\\u21C5','udblac':'\\u0171','Udblac':'\\u0170','udhar':'\\u296E','ufisht':'\\u297E','ufr':'\\uD835\\uDD32','Ufr':'\\uD835\\uDD18','ugrave':'\\xF9','Ugrave':'\\xD9','uHar':'\\u2963','uharl':'\\u21BF','uharr':'\\u21BE','uhblk':'\\u2580','ulcorn':'\\u231C','ulcorner':'\\u231C','ulcrop':'\\u230F','ultri':'\\u25F8','umacr':'\\u016B','Umacr':'\\u016A','uml':'\\xA8','UnderBar':'_','UnderBrace':'\\u23DF','UnderBracket':'\\u23B5','UnderParenthesis':'\\u23DD','Union':'\\u22C3','UnionPlus':'\\u228E','uogon':'\\u0173','Uogon':'\\u0172','uopf':'\\uD835\\uDD66','Uopf':'\\uD835\\uDD4C','uparrow':'\\u2191','Uparrow':'\\u21D1','UpArrow':'\\u2191','UpArrowBar':'\\u2912','UpArrowDownArrow':'\\u21C5','updownarrow':'\\u2195','Updownarrow':'\\u21D5','UpDownArrow':'\\u2195','UpEquilibrium':'\\u296E','upharpoonleft':'\\u21BF','upharpoonright':'\\u21BE','uplus':'\\u228E','UpperLeftArrow':'\\u2196','UpperRightArrow':'\\u2197','upsi':'\\u03C5','Upsi':'\\u03D2','upsih':'\\u03D2','upsilon':'\\u03C5','Upsilon':'\\u03A5','UpTee':'\\u22A5','UpTeeArrow':'\\u21A5','upuparrows':'\\u21C8','urcorn':'\\u231D','urcorner':'\\u231D','urcrop':'\\u230E','uring':'\\u016F','Uring':'\\u016E','urtri':'\\u25F9','uscr':'\\uD835\\uDCCA','Uscr':'\\uD835\\uDCB0','utdot':'\\u22F0','utilde':'\\u0169','Utilde':'\\u0168','utri':'\\u25B5','utrif':'\\u25B4','uuarr':'\\u21C8','uuml':'\\xFC','Uuml':'\\xDC','uwangle':'\\u29A7','vangrt':'\\u299C','varepsilon':'\\u03F5','varkappa':'\\u03F0','varnothing':'\\u2205','varphi':'\\u03D5','varpi':'\\u03D6','varpropto':'\\u221D','varr':'\\u2195','vArr':'\\u21D5','varrho':'\\u03F1','varsigma':'\\u03C2','varsubsetneq':'\\u228A\\uFE00','varsubsetneqq':'\\u2ACB\\uFE00','varsupsetneq':'\\u228B\\uFE00','varsupsetneqq':'\\u2ACC\\uFE00','vartheta':'\\u03D1','vartriangleleft':'\\u22B2','vartriangleright':'\\u22B3','vBar':'\\u2AE8','Vbar':'\\u2AEB','vBarv':'\\u2AE9','vcy':'\\u0432','Vcy':'\\u0412','vdash':'\\u22A2','vDash':'\\u22A8','Vdash':'\\u22A9','VDash':'\\u22AB','Vdashl':'\\u2AE6','vee':'\\u2228','Vee':'\\u22C1','veebar':'\\u22BB','veeeq':'\\u225A','vellip':'\\u22EE','verbar':'|','Verbar':'\\u2016','vert':'|','Vert':'\\u2016','VerticalBar':'\\u2223','VerticalLine':'|','VerticalSeparator':'\\u2758','VerticalTilde':'\\u2240','VeryThinSpace':'\\u200A','vfr':'\\uD835\\uDD33','Vfr':'\\uD835\\uDD19','vltri':'\\u22B2','vnsub':'\\u2282\\u20D2','vnsup':'\\u2283\\u20D2','vopf':'\\uD835\\uDD67','Vopf':'\\uD835\\uDD4D','vprop':'\\u221D','vrtri':'\\u22B3','vscr':'\\uD835\\uDCCB','Vscr':'\\uD835\\uDCB1','vsubne':'\\u228A\\uFE00','vsubnE':'\\u2ACB\\uFE00','vsupne':'\\u228B\\uFE00','vsupnE':'\\u2ACC\\uFE00','Vvdash':'\\u22AA','vzigzag':'\\u299A','wcirc':'\\u0175','Wcirc':'\\u0174','wedbar':'\\u2A5F','wedge':'\\u2227','Wedge':'\\u22C0','wedgeq':'\\u2259','weierp':'\\u2118','wfr':'\\uD835\\uDD34','Wfr':'\\uD835\\uDD1A','wopf':'\\uD835\\uDD68','Wopf':'\\uD835\\uDD4E','wp':'\\u2118','wr':'\\u2240','wreath':'\\u2240','wscr':'\\uD835\\uDCCC','Wscr':'\\uD835\\uDCB2','xcap':'\\u22C2','xcirc':'\\u25EF','xcup':'\\u22C3','xdtri':'\\u25BD','xfr':'\\uD835\\uDD35','Xfr':'\\uD835\\uDD1B','xharr':'\\u27F7','xhArr':'\\u27FA','xi':'\\u03BE','Xi':'\\u039E','xlarr':'\\u27F5','xlArr':'\\u27F8','xmap':'\\u27FC','xnis':'\\u22FB','xodot':'\\u2A00','xopf':'\\uD835\\uDD69','Xopf':'\\uD835\\uDD4F','xoplus':'\\u2A01','xotime':'\\u2A02','xrarr':'\\u27F6','xrArr':'\\u27F9','xscr':'\\uD835\\uDCCD','Xscr':'\\uD835\\uDCB3','xsqcup':'\\u2A06','xuplus':'\\u2A04','xutri':'\\u25B3','xvee':'\\u22C1','xwedge':'\\u22C0','yacute':'\\xFD','Yacute':'\\xDD','yacy':'\\u044F','YAcy':'\\u042F','ycirc':'\\u0177','Ycirc':'\\u0176','ycy':'\\u044B','Ycy':'\\u042B','yen':'\\xA5','yfr':'\\uD835\\uDD36','Yfr':'\\uD835\\uDD1C','yicy':'\\u0457','YIcy':'\\u0407','yopf':'\\uD835\\uDD6A','Yopf':'\\uD835\\uDD50','yscr':'\\uD835\\uDCCE','Yscr':'\\uD835\\uDCB4','yucy':'\\u044E','YUcy':'\\u042E','yuml':'\\xFF','Yuml':'\\u0178','zacute':'\\u017A','Zacute':'\\u0179','zcaron':'\\u017E','Zcaron':'\\u017D','zcy':'\\u0437','Zcy':'\\u0417','zdot':'\\u017C','Zdot':'\\u017B','zeetrf':'\\u2128','ZeroWidthSpace':'\\u200B','zeta':'\\u03B6','Zeta':'\\u0396','zfr':'\\uD835\\uDD37','Zfr':'\\u2128','zhcy':'\\u0436','ZHcy':'\\u0416','zigrarr':'\\u21DD','zopf':'\\uD835\\uDD6B','Zopf':'\\u2124','zscr':'\\uD835\\uDCCF','Zscr':'\\uD835\\uDCB5','zwj':'\\u200D','zwnj':'\\u200C'};\n\tvar decodeMapLegacy = {'aacute':'\\xE1','Aacute':'\\xC1','acirc':'\\xE2','Acirc':'\\xC2','acute':'\\xB4','aelig':'\\xE6','AElig':'\\xC6','agrave':'\\xE0','Agrave':'\\xC0','amp':'&','AMP':'&','aring':'\\xE5','Aring':'\\xC5','atilde':'\\xE3','Atilde':'\\xC3','auml':'\\xE4','Auml':'\\xC4','brvbar':'\\xA6','ccedil':'\\xE7','Ccedil':'\\xC7','cedil':'\\xB8','cent':'\\xA2','copy':'\\xA9','COPY':'\\xA9','curren':'\\xA4','deg':'\\xB0','divide':'\\xF7','eacute':'\\xE9','Eacute':'\\xC9','ecirc':'\\xEA','Ecirc':'\\xCA','egrave':'\\xE8','Egrave':'\\xC8','eth':'\\xF0','ETH':'\\xD0','euml':'\\xEB','Euml':'\\xCB','frac12':'\\xBD','frac14':'\\xBC','frac34':'\\xBE','gt':'>','GT':'>','iacute':'\\xED','Iacute':'\\xCD','icirc':'\\xEE','Icirc':'\\xCE','iexcl':'\\xA1','igrave':'\\xEC','Igrave':'\\xCC','iquest':'\\xBF','iuml':'\\xEF','Iuml':'\\xCF','laquo':'\\xAB','lt':'<','LT':'<','macr':'\\xAF','micro':'\\xB5','middot':'\\xB7','nbsp':'\\xA0','not':'\\xAC','ntilde':'\\xF1','Ntilde':'\\xD1','oacute':'\\xF3','Oacute':'\\xD3','ocirc':'\\xF4','Ocirc':'\\xD4','ograve':'\\xF2','Ograve':'\\xD2','ordf':'\\xAA','ordm':'\\xBA','oslash':'\\xF8','Oslash':'\\xD8','otilde':'\\xF5','Otilde':'\\xD5','ouml':'\\xF6','Ouml':'\\xD6','para':'\\xB6','plusmn':'\\xB1','pound':'\\xA3','quot':'\"','QUOT':'\"','raquo':'\\xBB','reg':'\\xAE','REG':'\\xAE','sect':'\\xA7','shy':'\\xAD','sup1':'\\xB9','sup2':'\\xB2','sup3':'\\xB3','szlig':'\\xDF','thorn':'\\xFE','THORN':'\\xDE','times':'\\xD7','uacute':'\\xFA','Uacute':'\\xDA','ucirc':'\\xFB','Ucirc':'\\xDB','ugrave':'\\xF9','Ugrave':'\\xD9','uml':'\\xA8','uuml':'\\xFC','Uuml':'\\xDC','yacute':'\\xFD','Yacute':'\\xDD','yen':'\\xA5','yuml':'\\xFF'};\n\tvar decodeMapNumeric = {'0':'\\uFFFD','128':'\\u20AC','130':'\\u201A','131':'\\u0192','132':'\\u201E','133':'\\u2026','134':'\\u2020','135':'\\u2021','136':'\\u02C6','137':'\\u2030','138':'\\u0160','139':'\\u2039','140':'\\u0152','142':'\\u017D','145':'\\u2018','146':'\\u2019','147':'\\u201C','148':'\\u201D','149':'\\u2022','150':'\\u2013','151':'\\u2014','152':'\\u02DC','153':'\\u2122','154':'\\u0161','155':'\\u203A','156':'\\u0153','158':'\\u017E','159':'\\u0178'};\n\tvar invalidReferenceCodePoints = [1,2,3,4,5,6,7,8,11,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,64976,64977,64978,64979,64980,64981,64982,64983,64984,64985,64986,64987,64988,64989,64990,64991,64992,64993,64994,64995,64996,64997,64998,64999,65000,65001,65002,65003,65004,65005,65006,65007,65534,65535,131070,131071,196606,196607,262142,262143,327678,327679,393214,393215,458750,458751,524286,524287,589822,589823,655358,655359,720894,720895,786430,786431,851966,851967,917502,917503,983038,983039,1048574,1048575,1114110,1114111];\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar stringFromCharCode = String.fromCharCode;\n\n\tvar object = {};\n\tvar hasOwnProperty = object.hasOwnProperty;\n\tvar has = function(object, propertyName) {\n\t\treturn hasOwnProperty.call(object, propertyName);\n\t};\n\n\tvar contains = function(array, value) {\n\t\tvar index = -1;\n\t\tvar length = array.length;\n\t\twhile (++index < length) {\n\t\t\tif (array[index] == value) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t};\n\n\tvar merge = function(options, defaults) {\n\t\tif (!options) {\n\t\t\treturn defaults;\n\t\t}\n\t\tvar result = {};\n\t\tvar key;\n\t\tfor (key in defaults) {\n\t\t\t// A `hasOwnProperty` check is not needed here, since only recognized\n\t\t\t// option names are used anyway. Any others are ignored.\n\t\t\tresult[key] = has(options, key) ? options[key] : defaults[key];\n\t\t}\n\t\treturn result;\n\t};\n\n\t// Modified version of `ucs2encode`; see https://mths.be/punycode.\n\tvar codePointToSymbol = function(codePoint, strict) {\n\t\tvar output = '';\n\t\tif ((codePoint >= 0xD800 && codePoint <= 0xDFFF) || codePoint > 0x10FFFF) {\n\t\t\t// See issue #4:\n\t\t\t// “Otherwise, if the number is in the range 0xD800 to 0xDFFF or is\n\t\t\t// greater than 0x10FFFF, then this is a parse error. Return a U+FFFD\n\t\t\t// REPLACEMENT CHARACTER.”\n\t\t\tif (strict) {\n\t\t\t\tparseError('character reference outside the permissible Unicode range');\n\t\t\t}\n\t\t\treturn '\\uFFFD';\n\t\t}\n\t\tif (has(decodeMapNumeric, codePoint)) {\n\t\t\tif (strict) {\n\t\t\t\tparseError('disallowed character reference');\n\t\t\t}\n\t\t\treturn decodeMapNumeric[codePoint];\n\t\t}\n\t\tif (strict && contains(invalidReferenceCodePoints, codePoint)) {\n\t\t\tparseError('disallowed character reference');\n\t\t}\n\t\tif (codePoint > 0xFFFF) {\n\t\t\tcodePoint -= 0x10000;\n\t\t\toutput += stringFromCharCode(codePoint >>> 10 & 0x3FF | 0xD800);\n\t\t\tcodePoint = 0xDC00 | codePoint & 0x3FF;\n\t\t}\n\t\toutput += stringFromCharCode(codePoint);\n\t\treturn output;\n\t};\n\n\tvar hexEscape = function(codePoint) {\n\t\treturn '&#x' + codePoint.toString(16).toUpperCase() + ';';\n\t};\n\n\tvar decEscape = function(codePoint) {\n\t\treturn '&#' + codePoint + ';';\n\t};\n\n\tvar parseError = function(message) {\n\t\tthrow Error('Parse error: ' + message);\n\t};\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar encode = function(string, options) {\n\t\toptions = merge(options, encode.options);\n\t\tvar strict = options.strict;\n\t\tif (strict && regexInvalidRawCodePoint.test(string)) {\n\t\t\tparseError('forbidden code point');\n\t\t}\n\t\tvar encodeEverything = options.encodeEverything;\n\t\tvar useNamedReferences = options.useNamedReferences;\n\t\tvar allowUnsafeSymbols = options.allowUnsafeSymbols;\n\t\tvar escapeCodePoint = options.decimal ? decEscape : hexEscape;\n\n\t\tvar escapeBmpSymbol = function(symbol) {\n\t\t\treturn escapeCodePoint(symbol.charCodeAt(0));\n\t\t};\n\n\t\tif (encodeEverything) {\n\t\t\t// Encode ASCII symbols.\n\t\t\tstring = string.replace(regexAsciiWhitelist, function(symbol) {\n\t\t\t\t// Use named references if requested & possible.\n\t\t\t\tif (useNamedReferences && has(encodeMap, symbol)) {\n\t\t\t\t\treturn '&' + encodeMap[symbol] + ';';\n\t\t\t\t}\n\t\t\t\treturn escapeBmpSymbol(symbol);\n\t\t\t});\n\t\t\t// Shorten a few escapes that represent two symbols, of which at least one\n\t\t\t// is within the ASCII range.\n\t\t\tif (useNamedReferences) {\n\t\t\t\tstring = string\n\t\t\t\t\t.replace(/>\\u20D2/g, '>⃒')\n\t\t\t\t\t.replace(/<\\u20D2/g, '<⃒')\n\t\t\t\t\t.replace(/fj/g, 'fj');\n\t\t\t}\n\t\t\t// Encode non-ASCII symbols.\n\t\t\tif (useNamedReferences) {\n\t\t\t\t// Encode non-ASCII symbols that can be replaced with a named reference.\n\t\t\t\tstring = string.replace(regexEncodeNonAscii, function(string) {\n\t\t\t\t\t// Note: there is no need to check `has(encodeMap, string)` here.\n\t\t\t\t\treturn '&' + encodeMap[string] + ';';\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Note: any remaining non-ASCII symbols are handled outside of the `if`.\n\t\t} else if (useNamedReferences) {\n\t\t\t// Apply named character references.\n\t\t\t// Encode `<>\"'&` using named character references.\n\t\t\tif (!allowUnsafeSymbols) {\n\t\t\t\tstring = string.replace(regexEscape, function(string) {\n\t\t\t\t\treturn '&' + encodeMap[string] + ';'; // no need to check `has()` here\n\t\t\t\t});\n\t\t\t}\n\t\t\t// Shorten escapes that represent two symbols, of which at least one is\n\t\t\t// `<>\"'&`.\n\t\t\tstring = string\n\t\t\t\t.replace(/>\\u20D2/g, '>⃒')\n\t\t\t\t.replace(/<\\u20D2/g, '<⃒');\n\t\t\t// Encode non-ASCII symbols that can be replaced with a named reference.\n\t\t\tstring = string.replace(regexEncodeNonAscii, function(string) {\n\t\t\t\t// Note: there is no need to check `has(encodeMap, string)` here.\n\t\t\t\treturn '&' + encodeMap[string] + ';';\n\t\t\t});\n\t\t} else if (!allowUnsafeSymbols) {\n\t\t\t// Encode `<>\"'&` using hexadecimal escapes, now that they’re not handled\n\t\t\t// using named character references.\n\t\t\tstring = string.replace(regexEscape, escapeBmpSymbol);\n\t\t}\n\t\treturn string\n\t\t\t// Encode astral symbols.\n\t\t\t.replace(regexAstralSymbols, function($0) {\n\t\t\t\t// https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae\n\t\t\t\tvar high = $0.charCodeAt(0);\n\t\t\t\tvar low = $0.charCodeAt(1);\n\t\t\t\tvar codePoint = (high - 0xD800) * 0x400 + low - 0xDC00 + 0x10000;\n\t\t\t\treturn escapeCodePoint(codePoint);\n\t\t\t})\n\t\t\t// Encode any remaining BMP symbols that are not printable ASCII symbols\n\t\t\t// using a hexadecimal escape.\n\t\t\t.replace(regexBmpWhitelist, escapeBmpSymbol);\n\t};\n\t// Expose default options (so they can be overridden globally).\n\tencode.options = {\n\t\t'allowUnsafeSymbols': false,\n\t\t'encodeEverything': false,\n\t\t'strict': false,\n\t\t'useNamedReferences': false,\n\t\t'decimal' : false\n\t};\n\n\tvar decode = function(html, options) {\n\t\toptions = merge(options, decode.options);\n\t\tvar strict = options.strict;\n\t\tif (strict && regexInvalidEntity.test(html)) {\n\t\t\tparseError('malformed character reference');\n\t\t}\n\t\treturn html.replace(regexDecode, function($0, $1, $2, $3, $4, $5, $6, $7, $8) {\n\t\t\tvar codePoint;\n\t\t\tvar semicolon;\n\t\t\tvar decDigits;\n\t\t\tvar hexDigits;\n\t\t\tvar reference;\n\t\t\tvar next;\n\n\t\t\tif ($1) {\n\t\t\t\treference = $1;\n\t\t\t\t// Note: there is no need to check `has(decodeMap, reference)`.\n\t\t\t\treturn decodeMap[reference];\n\t\t\t}\n\n\t\t\tif ($2) {\n\t\t\t\t// Decode named character references without trailing `;`, e.g. `&`.\n\t\t\t\t// This is only a parse error if it gets converted to `&`, or if it is\n\t\t\t\t// followed by `=` in an attribute context.\n\t\t\t\treference = $2;\n\t\t\t\tnext = $3;\n\t\t\t\tif (next && options.isAttributeValue) {\n\t\t\t\t\tif (strict && next == '=') {\n\t\t\t\t\t\tparseError('`&` did not start a character reference');\n\t\t\t\t\t}\n\t\t\t\t\treturn $0;\n\t\t\t\t} else {\n\t\t\t\t\tif (strict) {\n\t\t\t\t\t\tparseError(\n\t\t\t\t\t\t\t'named character reference was not terminated by a semicolon'\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\t// Note: there is no need to check `has(decodeMapLegacy, reference)`.\n\t\t\t\t\treturn decodeMapLegacy[reference] + (next || '');\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ($4) {\n\t\t\t\t// Decode decimal escapes, e.g. `𝌆`.\n\t\t\t\tdecDigits = $4;\n\t\t\t\tsemicolon = $5;\n\t\t\t\tif (strict && !semicolon) {\n\t\t\t\t\tparseError('character reference was not terminated by a semicolon');\n\t\t\t\t}\n\t\t\t\tcodePoint = parseInt(decDigits, 10);\n\t\t\t\treturn codePointToSymbol(codePoint, strict);\n\t\t\t}\n\n\t\t\tif ($6) {\n\t\t\t\t// Decode hexadecimal escapes, e.g. `𝌆`.\n\t\t\t\thexDigits = $6;\n\t\t\t\tsemicolon = $7;\n\t\t\t\tif (strict && !semicolon) {\n\t\t\t\t\tparseError('character reference was not terminated by a semicolon');\n\t\t\t\t}\n\t\t\t\tcodePoint = parseInt(hexDigits, 16);\n\t\t\t\treturn codePointToSymbol(codePoint, strict);\n\t\t\t}\n\n\t\t\t// If we’re still here, `if ($7)` is implied; it’s an ambiguous\n\t\t\t// ampersand for sure. https://mths.be/notes/ambiguous-ampersands\n\t\t\tif (strict) {\n\t\t\t\tparseError(\n\t\t\t\t\t'named character reference was not terminated by a semicolon'\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn $0;\n\t\t});\n\t};\n\t// Expose default options (so they can be overridden globally).\n\tdecode.options = {\n\t\t'isAttributeValue': false,\n\t\t'strict': false\n\t};\n\n\tvar escape = function(string) {\n\t\treturn string.replace(regexEscape, function($0) {\n\t\t\t// Note: there is no need to check `has(escapeMap, $0)` here.\n\t\t\treturn escapeMap[$0];\n\t\t});\n\t};\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar he = {\n\t\t'version': '1.2.0',\n\t\t'encode': encode,\n\t\t'decode': decode,\n\t\t'escape': escape,\n\t\t'unescape': decode\n\t};\n\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine(function() {\n\t\t\treturn he;\n\t\t});\n\t}\telse if (freeExports && !freeExports.nodeType) {\n\t\tif (freeModule) { // in Node.js, io.js, or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = he;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tfor (var key in he) {\n\t\t\t\thas(he, key) && (freeExports[key] = he[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.he = he;\n\t}\n\n}(this));\n","'use strict';\n\n/**\n * Various utility functions used throughout Mocha's codebase.\n * @module utils\n */\n\n/**\n * Module dependencies.\n */\nvar path = require('path');\nvar util = require('util');\nvar he = require('he');\n\nconst MOCHA_ID_PROP_NAME = '__mocha_id__';\n\n/**\n * Inherit the prototype methods from one constructor into another.\n *\n * @param {function} ctor - Constructor function which needs to inherit the\n * prototype.\n * @param {function} superCtor - Constructor function to inherit prototype from.\n * @throws {TypeError} if either constructor is null, or if super constructor\n * lacks a prototype.\n */\nexports.inherits = util.inherits;\n\n/**\n * Escape special characters in the given string of html.\n *\n * @private\n * @param {string} html\n * @return {string}\n */\nexports.escape = function (html) {\n return he.encode(String(html), {useNamedReferences: false});\n};\n\n/**\n * Test if the given obj is type of string.\n *\n * @private\n * @param {Object} obj\n * @return {boolean}\n */\nexports.isString = function (obj) {\n return typeof obj === 'string';\n};\n\n/**\n * Compute a slug from the given `str`.\n *\n * @private\n * @param {string} str\n * @return {string}\n */\nexports.slug = function (str) {\n return str\n .toLowerCase()\n .replace(/\\s+/g, '-')\n .replace(/[^-\\w]/g, '')\n .replace(/-{2,}/g, '-');\n};\n\n/**\n * Strip the function definition from `str`, and re-indent for pre whitespace.\n *\n * @param {string} str\n * @return {string}\n */\nexports.clean = function (str) {\n str = str\n .replace(/\\r\\n?|[\\n\\u2028\\u2029]/g, '\\n')\n .replace(/^\\uFEFF/, '')\n // (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content\n .replace(\n /^function(?:\\s*|\\s[^(]*)\\([^)]*\\)\\s*\\{((?:.|\\n)*?)\\}$|^\\([^)]*\\)\\s*=>\\s*(?:\\{((?:.|\\n)*?)\\}|((?:.|\\n)*))$/,\n '$1$2$3'\n );\n\n var spaces = str.match(/^\\n?( *)/)[1].length;\n var tabs = str.match(/^\\n?(\\t*)/)[1].length;\n var re = new RegExp(\n '^\\n?' + (tabs ? '\\t' : ' ') + '{' + (tabs || spaces) + '}',\n 'gm'\n );\n\n str = str.replace(re, '');\n\n return str.trim();\n};\n\n/**\n * If a value could have properties, and has none, this function is called,\n * which returns a string representation of the empty value.\n *\n * Functions w/ no properties return `'[Function]'`\n * Arrays w/ length === 0 return `'[]'`\n * Objects w/ no properties return `'{}'`\n * All else: return result of `value.toString()`\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} typeHint The type of the value\n * @returns {string}\n */\nfunction emptyRepresentation(value, typeHint) {\n switch (typeHint) {\n case 'function':\n return '[Function]';\n case 'object':\n return '{}';\n case 'array':\n return '[]';\n default:\n return value.toString();\n }\n}\n\n/**\n * Takes some variable and asks `Object.prototype.toString()` what it thinks it\n * is.\n *\n * @private\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString\n * @param {*} value The value to test.\n * @returns {string} Computed type\n * @example\n * canonicalType({}) // 'object'\n * canonicalType([]) // 'array'\n * canonicalType(1) // 'number'\n * canonicalType(false) // 'boolean'\n * canonicalType(Infinity) // 'number'\n * canonicalType(null) // 'null'\n * canonicalType(new Date()) // 'date'\n * canonicalType(/foo/) // 'regexp'\n * canonicalType('type') // 'string'\n * canonicalType(global) // 'global'\n * canonicalType(new String('foo') // 'object'\n * canonicalType(async function() {}) // 'asyncfunction'\n * canonicalType(await import(name)) // 'module'\n */\nvar canonicalType = (exports.canonicalType = function canonicalType(value) {\n if (value === undefined) {\n return 'undefined';\n } else if (value === null) {\n return 'null';\n } else if (Buffer.isBuffer(value)) {\n return 'buffer';\n }\n return Object.prototype.toString\n .call(value)\n .replace(/^\\[.+\\s(.+?)]$/, '$1')\n .toLowerCase();\n});\n\n/**\n *\n * Returns a general type or data structure of a variable\n * @private\n * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures\n * @param {*} value The value to test.\n * @returns {string} One of undefined, boolean, number, string, bigint, symbol, object\n * @example\n * type({}) // 'object'\n * type([]) // 'array'\n * type(1) // 'number'\n * type(false) // 'boolean'\n * type(Infinity) // 'number'\n * type(null) // 'null'\n * type(new Date()) // 'object'\n * type(/foo/) // 'object'\n * type('type') // 'string'\n * type(global) // 'object'\n * type(new String('foo') // 'string'\n */\nexports.type = function type(value) {\n // Null is special\n if (value === null) return 'null';\n const primitives = new Set([\n 'undefined',\n 'boolean',\n 'number',\n 'string',\n 'bigint',\n 'symbol'\n ]);\n const _type = typeof value;\n if (_type === 'function') return _type;\n if (primitives.has(_type)) return _type;\n if (value instanceof String) return 'string';\n if (value instanceof Error) return 'error';\n if (Array.isArray(value)) return 'array';\n\n return _type;\n};\n\n/**\n * Stringify `value`. Different behavior depending on type of value:\n *\n * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.\n * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.\n * - If `value` is an *empty* object, function, or array, return result of function\n * {@link emptyRepresentation}.\n * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of\n * JSON.stringify().\n *\n * @private\n * @see exports.type\n * @param {*} value\n * @return {string}\n */\nexports.stringify = function (value) {\n var typeHint = canonicalType(value);\n\n if (!~['object', 'array', 'function'].indexOf(typeHint)) {\n if (typeHint === 'buffer') {\n var json = Buffer.prototype.toJSON.call(value);\n // Based on the toJSON result\n return jsonStringify(\n json.data && json.type ? json.data : json,\n 2\n ).replace(/,(\\n|$)/g, '$1');\n }\n\n // IE7/IE8 has a bizarre String constructor; needs to be coerced\n // into an array and back to obj.\n if (typeHint === 'string' && typeof value === 'object') {\n value = value.split('').reduce(function (acc, char, idx) {\n acc[idx] = char;\n return acc;\n }, {});\n typeHint = 'object';\n } else {\n return jsonStringify(value);\n }\n }\n\n for (var prop in value) {\n if (Object.prototype.hasOwnProperty.call(value, prop)) {\n return jsonStringify(\n exports.canonicalize(value, null, typeHint),\n 2\n ).replace(/,(\\n|$)/g, '$1');\n }\n }\n\n return emptyRepresentation(value, typeHint);\n};\n\n/**\n * like JSON.stringify but more sense.\n *\n * @private\n * @param {Object} object\n * @param {number=} spaces\n * @param {number=} depth\n * @returns {*}\n */\nfunction jsonStringify(object, spaces, depth) {\n if (typeof spaces === 'undefined') {\n // primitive types\n return _stringify(object);\n }\n\n depth = depth || 1;\n var space = spaces * depth;\n var str = Array.isArray(object) ? '[' : '{';\n var end = Array.isArray(object) ? ']' : '}';\n var length =\n typeof object.length === 'number'\n ? object.length\n : Object.keys(object).length;\n // `.repeat()` polyfill\n function repeat(s, n) {\n return new Array(n).join(s);\n }\n\n function _stringify(val) {\n switch (canonicalType(val)) {\n case 'null':\n case 'undefined':\n val = '[' + val + ']';\n break;\n case 'array':\n case 'object':\n val = jsonStringify(val, spaces, depth + 1);\n break;\n case 'boolean':\n case 'regexp':\n case 'symbol':\n case 'number':\n val =\n val === 0 && 1 / val === -Infinity // `-0`\n ? '-0'\n : val.toString();\n break;\n case 'bigint':\n val = val.toString() + 'n';\n break;\n case 'date':\n var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();\n val = '[Date: ' + sDate + ']';\n break;\n case 'buffer':\n var json = val.toJSON();\n // Based on the toJSON result\n json = json.data && json.type ? json.data : json;\n val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';\n break;\n default:\n val =\n val === '[Function]' || val === '[Circular]'\n ? val\n : JSON.stringify(val); // string\n }\n return val;\n }\n\n for (var i in object) {\n if (!Object.prototype.hasOwnProperty.call(object, i)) {\n continue; // not my business\n }\n --length;\n str +=\n '\\n ' +\n repeat(' ', space) +\n (Array.isArray(object) ? '' : '\"' + i + '\": ') + // key\n _stringify(object[i]) + // value\n (length ? ',' : ''); // comma\n }\n\n return (\n str +\n // [], {}\n (str.length !== 1 ? '\\n' + repeat(' ', --space) + end : end)\n );\n}\n\n/**\n * Return a new Thing that has the keys in sorted order. Recursive.\n *\n * If the Thing...\n * - has already been seen, return string `'[Circular]'`\n * - is `undefined`, return string `'[undefined]'`\n * - is `null`, return value `null`\n * - is some other primitive, return the value\n * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method\n * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.\n * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`\n *\n * @private\n * @see {@link exports.stringify}\n * @param {*} value Thing to inspect. May or may not have properties.\n * @param {Array} [stack=[]] Stack of seen values\n * @param {string} [typeHint] Type hint\n * @return {(Object|Array|Function|string|undefined)}\n */\nexports.canonicalize = function canonicalize(value, stack, typeHint) {\n var canonicalizedObj;\n /* eslint-disable no-unused-vars */\n var prop;\n /* eslint-enable no-unused-vars */\n typeHint = typeHint || canonicalType(value);\n function withStack(value, fn) {\n stack.push(value);\n fn();\n stack.pop();\n }\n\n stack = stack || [];\n\n if (stack.indexOf(value) !== -1) {\n return '[Circular]';\n }\n\n switch (typeHint) {\n case 'undefined':\n case 'buffer':\n case 'null':\n canonicalizedObj = value;\n break;\n case 'array':\n withStack(value, function () {\n canonicalizedObj = value.map(function (item) {\n return exports.canonicalize(item, stack);\n });\n });\n break;\n case 'function':\n /* eslint-disable-next-line no-unused-vars, no-unreachable-loop */\n for (prop in value) {\n canonicalizedObj = {};\n break;\n }\n /* eslint-enable guard-for-in */\n if (!canonicalizedObj) {\n canonicalizedObj = emptyRepresentation(value, typeHint);\n break;\n }\n /* falls through */\n case 'object':\n canonicalizedObj = canonicalizedObj || {};\n withStack(value, function () {\n Object.keys(value)\n .sort()\n .forEach(function (key) {\n canonicalizedObj[key] = exports.canonicalize(value[key], stack);\n });\n });\n break;\n case 'date':\n case 'number':\n case 'regexp':\n case 'boolean':\n case 'symbol':\n canonicalizedObj = value;\n break;\n default:\n canonicalizedObj = value + '';\n }\n\n return canonicalizedObj;\n};\n\n/**\n * @summary\n * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)\n * @description\n * When invoking this function you get a filter function that get the Error.stack as an input,\n * and return a prettify output.\n * (i.e: strip Mocha and internal node functions from stack trace).\n * @returns {Function}\n */\nexports.stackTraceFilter = function () {\n // TODO: Replace with `process.browser`\n var is = typeof document === 'undefined' ? {node: true} : {browser: true};\n var slash = path.sep;\n var cwd;\n if (is.node) {\n cwd = exports.cwd() + slash;\n } else {\n cwd = (\n typeof location === 'undefined' ? window.location : location\n ).href.replace(/\\/[^/]*$/, '/');\n slash = '/';\n }\n\n function isMochaInternal(line) {\n return (\n ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||\n ~line.indexOf(slash + 'mocha.js') ||\n ~line.indexOf(slash + 'mocha.min.js')\n );\n }\n\n function isNodeInternal(line) {\n return (\n ~line.indexOf('(timers.js:') ||\n ~line.indexOf('(events.js:') ||\n ~line.indexOf('(node.js:') ||\n ~line.indexOf('(module.js:') ||\n ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||\n false\n );\n }\n\n return function (stack) {\n stack = stack.split('\\n');\n\n stack = stack.reduce(function (list, line) {\n if (isMochaInternal(line)) {\n return list;\n }\n\n if (is.node && isNodeInternal(line)) {\n return list;\n }\n\n // Clean up cwd(absolute)\n if (/:\\d+:\\d+\\)?$/.test(line)) {\n line = line.replace('(' + cwd, '(');\n }\n\n list.push(line);\n return list;\n }, []);\n\n return stack.join('\\n');\n };\n};\n\n/**\n * Crude, but effective.\n * @public\n * @param {*} value\n * @returns {boolean} Whether or not `value` is a Promise\n */\nexports.isPromise = function isPromise(value) {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof value.then === 'function'\n );\n};\n\n/**\n * Clamps a numeric value to an inclusive range.\n *\n * @param {number} value - Value to be clamped.\n * @param {number[]} range - Two element array specifying [min, max] range.\n * @returns {number} clamped value\n */\nexports.clamp = function clamp(value, range) {\n return Math.min(Math.max(value, range[0]), range[1]);\n};\n\n/**\n * It's a noop.\n * @public\n */\nexports.noop = function () {};\n\n/**\n * Creates a map-like object.\n *\n * @description\n * A \"map\" is an object with no prototype, for our purposes. In some cases\n * this would be more appropriate than a `Map`, especially if your environment\n * doesn't support it. Recommended for use in Mocha's public APIs.\n *\n * @public\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Custom_and_Null_objects|MDN:Map}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Custom_and_Null_objects|MDN:Object.create - Custom objects}\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Custom_and_Null_objects|MDN:Object.assign}\n * @param {...*} [obj] - Arguments to `Object.assign()`.\n * @returns {Object} An object with no prototype, having `...obj` properties\n */\nexports.createMap = function (obj) {\n return Object.assign.apply(\n null,\n [Object.create(null)].concat(Array.prototype.slice.call(arguments))\n );\n};\n\n/**\n * Creates a read-only map-like object.\n *\n * @description\n * This differs from {@link module:utils.createMap createMap} only in that\n * the argument must be non-empty, because the result is frozen.\n *\n * @see {@link module:utils.createMap createMap}\n * @param {...*} [obj] - Arguments to `Object.assign()`.\n * @returns {Object} A frozen object with no prototype, having `...obj` properties\n * @throws {TypeError} if argument is not a non-empty object.\n */\nexports.defineConstants = function (obj) {\n if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) {\n throw new TypeError('Invalid argument; expected a non-empty object');\n }\n return Object.freeze(exports.createMap(obj));\n};\n\n/**\n * Returns current working directory\n *\n * Wrapper around `process.cwd()` for isolation\n * @private\n */\nexports.cwd = function cwd() {\n return process.cwd();\n};\n\n/**\n * Returns `true` if Mocha is running in a browser.\n * Checks for `process.browser`.\n * @returns {boolean}\n * @private\n */\nexports.isBrowser = function isBrowser() {\n return Boolean(process.browser);\n};\n\n/*\n * Casts `value` to an array; useful for optionally accepting array parameters\n *\n * It follows these rules, depending on `value`. If `value` is...\n * 1. `undefined`: return an empty Array\n * 2. `null`: return an array with a single `null` element\n * 3. Any other object: return the value of `Array.from()` _if_ the object is iterable\n * 4. otherwise: return an array with a single element, `value`\n * @param {*} value - Something to cast to an Array\n * @returns {Array<*>}\n */\nexports.castArray = function castArray(value) {\n if (value === undefined) {\n return [];\n }\n if (value === null) {\n return [null];\n }\n if (\n typeof value === 'object' &&\n (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)\n ) {\n return Array.from(value);\n }\n return [value];\n};\n\nexports.constants = exports.defineConstants({\n MOCHA_ID_PROP_NAME\n});\n\nconst uniqueIDBase =\n 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';\n\n/**\n * Creates a new unique identifier\n * Does not create cryptographically safe ids.\n * Trivial copy of nanoid/non-secure\n * @returns {string} Unique identifier\n */\nexports.uniqueID = () => {\n let id = '';\n for (let i = 0; i < 21; i++) {\n id += uniqueIDBase[(Math.random() * 64) | 0];\n }\n return id;\n};\n\nexports.assignNewMochaID = obj => {\n const id = exports.uniqueID();\n Object.defineProperty(obj, MOCHA_ID_PROP_NAME, {\n get() {\n return id;\n }\n });\n return obj;\n};\n\n/**\n * Retrieves a Mocha ID from an object, if present.\n * @param {*} [obj] - Object\n * @returns {string|void}\n */\nexports.getMochaID = obj =>\n obj && typeof obj === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined;\n","'use strict';\n\nmodule.exports = {\n\tinfo: 'ℹ️',\n\tsuccess: '✅',\n\twarning: '⚠️',\n\terror: '❌️'\n};\n","'use strict';\n\n/**\n @module Pending\n*/\n\nmodule.exports = Pending;\n\n/**\n * Initialize a new `Pending` error with the given message.\n *\n * @param {string} message\n */\nfunction Pending(message) {\n this.message = message;\n}\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function(val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tlet i;\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '').split(/[\\s,]+/);\n\t\tconst len = split.length;\n\n\t\tfor (i = 0; i < len; i++) {\n\t\t\tif (!split[i]) {\n\t\t\t\t// ignore empty strings\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tnamespaces = split[i].replace(/\\*/g, '.*?');\n\n\t\t\tif (namespaces[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(new RegExp('^' + namespaces.slice(1) + '$'));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(new RegExp('^' + namespaces + '$'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names.map(toNamespace),\n\t\t\t...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tif (name[name.length - 1] === '*') {\n\t\t\treturn true;\n\t\t}\n\n\t\tlet i;\n\t\tlet len;\n\n\t\tfor (i = 0, len = createDebug.skips.length; i < len; i++) {\n\t\t\tif (createDebug.skips[i].test(name)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0, len = createDebug.names.length; i < len; i++) {\n\t\t\tif (createDebug.names[i].test(name)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Convert regexp to namespace\n\t*\n\t* @param {RegExp} regxep\n\t* @return {String} namespace\n\t* @api private\n\t*/\n\tfunction toNamespace(regexp) {\n\t\treturn regexp.toString()\n\t\t\t.substring(2, regexp.toString().length - 2)\n\t\t\t.replace(/\\.\\*\\?$/, '*');\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug');\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","'use strict';\n\nconst {format} = require('util');\n\n/**\n * Contains error codes, factory functions to create throwable error objects,\n * and warning/deprecation functions.\n * @module\n */\n\n/**\n * process.emitWarning or a polyfill\n * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options\n * @ignore\n */\nconst emitWarning = (msg, type) => {\n if (process.emitWarning) {\n process.emitWarning(msg, type);\n } else {\n /* istanbul ignore next */\n process.nextTick(function () {\n console.warn(type + ': ' + msg);\n });\n }\n};\n\n/**\n * Show a deprecation warning. Each distinct message is only displayed once.\n * Ignores empty messages.\n *\n * @param {string} [msg] - Warning to print\n * @private\n */\nconst deprecate = msg => {\n msg = String(msg);\n if (msg && !deprecate.cache[msg]) {\n deprecate.cache[msg] = true;\n emitWarning(msg, 'DeprecationWarning');\n }\n};\ndeprecate.cache = {};\n\n/**\n * Show a generic warning.\n * Ignores empty messages.\n *\n * @param {string} [msg] - Warning to print\n * @private\n */\nconst warn = msg => {\n if (msg) {\n emitWarning(msg);\n }\n};\n\n/**\n * When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`.\n * @public\n * @namespace\n * @memberof module:lib/errors\n */\nvar constants = {\n /**\n * An unrecoverable error.\n * @constant\n * @default\n */\n FATAL: 'ERR_MOCHA_FATAL',\n\n /**\n * The type of an argument to a function call is invalid\n * @constant\n * @default\n */\n INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE',\n\n /**\n * The value of an argument to a function call is invalid\n * @constant\n * @default\n */\n INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE',\n\n /**\n * Something was thrown, but it wasn't an `Error`\n * @constant\n * @default\n */\n INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION',\n\n /**\n * An interface (e.g., `Mocha.interfaces`) is unknown or invalid\n * @constant\n * @default\n */\n INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE',\n\n /**\n * A reporter (.e.g, `Mocha.reporters`) is unknown or invalid\n * @constant\n * @default\n */\n INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER',\n\n /**\n * `done()` was called twice in a `Test` or `Hook` callback\n * @constant\n * @default\n */\n MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE',\n\n /**\n * No files matched the pattern provided by the user\n * @constant\n * @default\n */\n NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN',\n\n /**\n * Known, but unsupported behavior of some kind\n * @constant\n * @default\n */\n UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED',\n\n /**\n * Invalid state transition occurring in `Mocha` instance\n * @constant\n * @default\n */\n INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',\n\n /**\n * Invalid state transition occurring in `Mocha` instance\n * @constant\n * @default\n */\n INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',\n\n /**\n * Use of `only()` w/ `--forbid-only` results in this error.\n * @constant\n * @default\n */\n FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY',\n\n /**\n * To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid\n * @constant\n * @default\n */\n INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION',\n\n /**\n * To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid\n * @constant\n * @default\n */\n INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION',\n\n /**\n * When a runnable exceeds its allowed run time.\n * @constant\n * @default\n */\n TIMEOUT: 'ERR_MOCHA_TIMEOUT',\n\n /**\n * Input file is not able to be parsed\n * @constant\n * @default\n */\n UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE'\n};\n\n/**\n * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}.\n * @private\n */\nconst MOCHA_ERRORS = new Set(Object.values(constants));\n\n/**\n * Creates an error object to be thrown when no files to be tested could be found using specified pattern.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} pattern - User-specified argument value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createNoFilesMatchPatternError(message, pattern) {\n var err = new Error(message);\n err.code = constants.NO_FILES_MATCH_PATTERN;\n err.pattern = pattern;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when the reporter specified in the options was not found.\n *\n * @public\n * @param {string} message - Error message to be displayed.\n * @param {string} reporter - User-specified reporter value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidReporterError(message, reporter) {\n var err = new TypeError(message);\n err.code = constants.INVALID_REPORTER;\n err.reporter = reporter;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when the interface specified in the options was not found.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} ui - User-specified interface value.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidInterfaceError(message, ui) {\n var err = new Error(message);\n err.code = constants.INVALID_INTERFACE;\n err.interface = ui;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a behavior, option, or parameter is unsupported.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createUnsupportedError(message) {\n var err = new Error(message);\n err.code = constants.UNSUPPORTED;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an argument is missing.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} expected - Expected argument datatype.\n * @returns {Error} instance detailing the error condition\n */\nfunction createMissingArgumentError(message, argument, expected) {\n return createInvalidArgumentTypeError(message, argument, expected);\n}\n\n/**\n * Creates an error object to be thrown when an argument did not use the supported type\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} expected - Expected argument datatype.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidArgumentTypeError(message, argument, expected) {\n var err = new TypeError(message);\n err.code = constants.INVALID_ARG_TYPE;\n err.argument = argument;\n err.expected = expected;\n err.actual = typeof argument;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an argument did not use the supported value\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} argument - Argument name.\n * @param {string} value - Argument value.\n * @param {string} [reason] - Why value is invalid.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidArgumentValueError(message, argument, value, reason) {\n var err = new TypeError(message);\n err.code = constants.INVALID_ARG_VALUE;\n err.argument = argument;\n err.value = value;\n err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createInvalidExceptionError(message, value) {\n var err = new Error(message);\n err.code = constants.INVALID_EXCEPTION;\n err.valueType = typeof value;\n err.value = value;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when an unrecoverable error occurs.\n *\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @returns {Error} instance detailing the error condition\n */\nfunction createFatalError(message, value) {\n var err = new Error(message);\n err.code = constants.FATAL;\n err.valueType = typeof value;\n err.value = value;\n return err;\n}\n\n/**\n * Dynamically creates a plugin-type-specific error based on plugin type\n * @param {string} message - Error message\n * @param {\"reporter\"|\"ui\"} pluginType - Plugin type. Future: expand as needed\n * @param {string} [pluginId] - Name/path of plugin, if any\n * @throws When `pluginType` is not known\n * @public\n * @static\n * @returns {Error}\n */\nfunction createInvalidLegacyPluginError(message, pluginType, pluginId) {\n switch (pluginType) {\n case 'reporter':\n return createInvalidReporterError(message, pluginId);\n case 'ui':\n return createInvalidInterfaceError(message, pluginId);\n default:\n throw new Error('unknown pluginType \"' + pluginType + '\"');\n }\n}\n\n/**\n * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type\n * @deprecated\n * @param {string} message - Error message\n * @param {\"reporter\"|\"interface\"} pluginType - Plugin type. Future: expand as needed\n * @param {string} [pluginId] - Name/path of plugin, if any\n * @throws When `pluginType` is not known\n * @public\n * @static\n * @returns {Error}\n */\nfunction createInvalidPluginError(...args) {\n deprecate('Use createInvalidLegacyPluginError() instead');\n return createInvalidLegacyPluginError(...args);\n}\n\n/**\n * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed.\n * @param {string} message The error message to be displayed.\n * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun`\n * @param {Mocha} instance the mocha instance that throw this error\n * @static\n */\nfunction createMochaInstanceAlreadyDisposedError(\n message,\n cleanReferencesAfterRun,\n instance\n) {\n var err = new Error(message);\n err.code = constants.INSTANCE_ALREADY_DISPOSED;\n err.cleanReferencesAfterRun = cleanReferencesAfterRun;\n err.instance = instance;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress.\n * @param {string} message The error message to be displayed.\n * @static\n * @public\n */\nfunction createMochaInstanceAlreadyRunningError(message, instance) {\n var err = new Error(message);\n err.code = constants.INSTANCE_ALREADY_RUNNING;\n err.instance = instance;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when done() is called multiple times in a test\n *\n * @public\n * @param {Runnable} runnable - Original runnable\n * @param {Error} [originalErr] - Original error, if any\n * @returns {Error} instance detailing the error condition\n * @static\n */\nfunction createMultipleDoneError(runnable, originalErr) {\n var title;\n try {\n title = format('<%s>', runnable.fullTitle());\n if (runnable.parent.root) {\n title += ' (of root suite)';\n }\n } catch (ignored) {\n title = format('<%s> (of unknown suite)', runnable.title);\n }\n var message = format(\n 'done() called multiple times in %s %s',\n runnable.type ? runnable.type : 'unknown runnable',\n title\n );\n if (runnable.file) {\n message += format(' of file %s', runnable.file);\n }\n if (originalErr) {\n message += format('; in addition, done() received error: %s', originalErr);\n }\n\n var err = new Error(message);\n err.code = constants.MULTIPLE_DONE;\n err.valueType = typeof originalErr;\n err.value = originalErr;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when `.only()` is used with\n * `--forbid-only`.\n * @static\n * @public\n * @param {Mocha} mocha - Mocha instance\n * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY}\n */\nfunction createForbiddenExclusivityError(mocha) {\n var err = new Error(\n mocha.isWorker\n ? '`.only` is not supported in parallel mode'\n : '`.only` forbidden by --forbid-only'\n );\n err.code = constants.FORBIDDEN_EXCLUSIVITY;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a plugin definition is invalid\n * @static\n * @param {string} msg - Error message\n * @param {PluginDefinition} [pluginDef] - Problematic plugin definition\n * @public\n * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}\n */\nfunction createInvalidPluginDefinitionError(msg, pluginDef) {\n const err = new Error(msg);\n err.code = constants.INVALID_PLUGIN_DEFINITION;\n err.pluginDef = pluginDef;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a plugin implementation (user code) is invalid\n * @static\n * @param {string} msg - Error message\n * @param {Object} [opts] - Plugin definition and user-supplied implementation\n * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition\n * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied)\n * @public\n * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}\n */\nfunction createInvalidPluginImplementationError(\n msg,\n {pluginDef, pluginImpl} = {}\n) {\n const err = new Error(msg);\n err.code = constants.INVALID_PLUGIN_IMPLEMENTATION;\n err.pluginDef = pluginDef;\n err.pluginImpl = pluginImpl;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when a runnable exceeds its allowed run time.\n * @static\n * @param {string} msg - Error message\n * @param {number} [timeout] - Timeout in ms\n * @param {string} [file] - File, if given\n * @returns {MochaTimeoutError}\n */\nfunction createTimeoutError(msg, timeout, file) {\n const err = new Error(msg);\n err.code = constants.TIMEOUT;\n err.timeout = timeout;\n err.file = file;\n return err;\n}\n\n/**\n * Creates an error object to be thrown when file is unparsable\n * @public\n * @static\n * @param {string} message - Error message to be displayed.\n * @param {string} filename - File name\n * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE}\n */\nfunction createUnparsableFileError(message, filename) {\n var err = new Error(message);\n err.code = constants.UNPARSABLE_FILE;\n return err;\n}\n\n/**\n * Returns `true` if an error came out of Mocha.\n * _Can suffer from false negatives, but not false positives._\n * @static\n * @public\n * @param {*} err - Error, or anything\n * @returns {boolean}\n */\nconst isMochaError = err =>\n Boolean(err && typeof err === 'object' && MOCHA_ERRORS.has(err.code));\n\nmodule.exports = {\n constants,\n createFatalError,\n createForbiddenExclusivityError,\n createInvalidArgumentTypeError,\n createInvalidArgumentValueError,\n createInvalidExceptionError,\n createInvalidInterfaceError,\n createInvalidLegacyPluginError,\n createInvalidPluginDefinitionError,\n createInvalidPluginError,\n createInvalidPluginImplementationError,\n createInvalidReporterError,\n createMissingArgumentError,\n createMochaInstanceAlreadyDisposedError,\n createMochaInstanceAlreadyRunningError,\n createMultipleDoneError,\n createNoFilesMatchPatternError,\n createTimeoutError,\n createUnparsableFileError,\n createUnsupportedError,\n deprecate,\n isMochaError,\n warn\n};\n\n/**\n * The error thrown when a Runnable times out\n * @memberof module:lib/errors\n * @typedef {Error} MochaTimeoutError\n * @property {constants.TIMEOUT} code - Error code\n * @property {number?} timeout Timeout in ms\n * @property {string?} file Filepath, if given\n */\n","'use strict';\n\nvar EventEmitter = require('events').EventEmitter;\nvar Pending = require('./pending');\nvar debug = require('debug')('mocha:runnable');\nvar milliseconds = require('ms');\nvar utils = require('./utils');\nconst {\n createInvalidExceptionError,\n createMultipleDoneError,\n createTimeoutError\n} = require('./errors');\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n * @private\n */\nvar Date = global.Date;\nvar setTimeout = global.setTimeout;\nvar clearTimeout = global.clearTimeout;\nvar toString = Object.prototype.toString;\n\nmodule.exports = Runnable;\n\n/**\n * Initialize a new `Runnable` with the given `title` and callback `fn`.\n *\n * @class\n * @extends external:EventEmitter\n * @public\n * @param {String} title\n * @param {Function} fn\n */\nfunction Runnable(title, fn) {\n this.title = title;\n this.fn = fn;\n this.body = (fn || '').toString();\n this.async = fn && fn.length;\n this.sync = !this.async;\n this._timeout = 2000;\n this._slow = 75;\n this._retries = -1;\n utils.assignNewMochaID(this);\n Object.defineProperty(this, 'id', {\n get() {\n return utils.getMochaID(this);\n }\n });\n this.reset();\n}\n\n/**\n * Inherit from `EventEmitter.prototype`.\n */\nutils.inherits(Runnable, EventEmitter);\n\n/**\n * Resets the state initially or for a next run.\n */\nRunnable.prototype.reset = function () {\n this.timedOut = false;\n this._currentRetry = 0;\n this.pending = false;\n delete this.state;\n delete this.err;\n};\n\n/**\n * Get current timeout value in msecs.\n *\n * @private\n * @returns {number} current timeout threshold value\n */\n/**\n * @summary\n * Set timeout threshold value (msecs).\n *\n * @description\n * A string argument can use shorthand (e.g., \"2s\") and will be converted.\n * The value will be clamped to range [0, 2^31-1].\n * If clamped value matches either range endpoint, timeouts will be disabled.\n *\n * @private\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value}\n * @param {number|string} ms - Timeout threshold value.\n * @returns {Runnable} this\n * @chainable\n */\nRunnable.prototype.timeout = function (ms) {\n if (!arguments.length) {\n return this._timeout;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n\n // Clamp to range\n var INT_MAX = Math.pow(2, 31) - 1;\n var range = [0, INT_MAX];\n ms = utils.clamp(ms, range);\n\n // see #1652 for reasoning\n if (ms === range[0] || ms === range[1]) {\n this._timeout = 0;\n } else {\n this._timeout = ms;\n }\n debug('timeout %d', this._timeout);\n\n if (this.timer) {\n this.resetTimeout();\n }\n return this;\n};\n\n/**\n * Set or get slow `ms`.\n *\n * @private\n * @param {number|string} ms\n * @return {Runnable|number} ms or Runnable instance.\n */\nRunnable.prototype.slow = function (ms) {\n if (!arguments.length || typeof ms === 'undefined') {\n return this._slow;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n debug('slow %d', ms);\n this._slow = ms;\n return this;\n};\n\n/**\n * Halt and mark as pending.\n *\n * @memberof Mocha.Runnable\n * @public\n */\nRunnable.prototype.skip = function () {\n this.pending = true;\n throw new Pending('sync skip; aborting execution');\n};\n\n/**\n * Check if this runnable or its parent suite is marked as pending.\n *\n * @private\n */\nRunnable.prototype.isPending = function () {\n return this.pending || (this.parent && this.parent.isPending());\n};\n\n/**\n * Return `true` if this Runnable has failed.\n * @return {boolean}\n * @private\n */\nRunnable.prototype.isFailed = function () {\n return !this.isPending() && this.state === constants.STATE_FAILED;\n};\n\n/**\n * Return `true` if this Runnable has passed.\n * @return {boolean}\n * @private\n */\nRunnable.prototype.isPassed = function () {\n return !this.isPending() && this.state === constants.STATE_PASSED;\n};\n\n/**\n * Set or get number of retries.\n *\n * @private\n */\nRunnable.prototype.retries = function (n) {\n if (!arguments.length) {\n return this._retries;\n }\n this._retries = n;\n};\n\n/**\n * Set or get current retry\n *\n * @private\n */\nRunnable.prototype.currentRetry = function (n) {\n if (!arguments.length) {\n return this._currentRetry;\n }\n this._currentRetry = n;\n};\n\n/**\n * Return the full title generated by recursively concatenating the parent's\n * full title.\n *\n * @memberof Mocha.Runnable\n * @public\n * @return {string}\n */\nRunnable.prototype.fullTitle = function () {\n return this.titlePath().join(' ');\n};\n\n/**\n * Return the title path generated by concatenating the parent's title path with the title.\n *\n * @memberof Mocha.Runnable\n * @public\n * @return {string[]}\n */\nRunnable.prototype.titlePath = function () {\n return this.parent.titlePath().concat([this.title]);\n};\n\n/**\n * Clear the timeout.\n *\n * @private\n */\nRunnable.prototype.clearTimeout = function () {\n clearTimeout(this.timer);\n};\n\n/**\n * Reset the timeout.\n *\n * @private\n */\nRunnable.prototype.resetTimeout = function () {\n var self = this;\n var ms = this.timeout();\n\n if (ms === 0) {\n return;\n }\n this.clearTimeout();\n this.timer = setTimeout(function () {\n if (self.timeout() === 0) {\n return;\n }\n self.callback(self._timeoutError(ms));\n self.timedOut = true;\n }, ms);\n};\n\n/**\n * Set or get a list of whitelisted globals for this test run.\n *\n * @private\n * @param {string[]} globals\n */\nRunnable.prototype.globals = function (globals) {\n if (!arguments.length) {\n return this._allowedGlobals;\n }\n this._allowedGlobals = globals;\n};\n\n/**\n * Run the test and invoke `fn(err)`.\n *\n * @param {Function} fn\n * @private\n */\nRunnable.prototype.run = function (fn) {\n var self = this;\n var start = new Date();\n var ctx = this.ctx;\n var finished;\n var errorWasHandled = false;\n\n if (this.isPending()) return fn();\n\n // Sometimes the ctx exists, but it is not runnable\n if (ctx && ctx.runnable) {\n ctx.runnable(this);\n }\n\n // called multiple times\n function multiple(err) {\n if (errorWasHandled) {\n return;\n }\n errorWasHandled = true;\n self.emit('error', createMultipleDoneError(self, err));\n }\n\n // finished\n function done(err) {\n var ms = self.timeout();\n if (self.timedOut) {\n return;\n }\n\n if (finished) {\n return multiple(err);\n }\n\n self.clearTimeout();\n self.duration = new Date() - start;\n finished = true;\n if (!err && self.duration > ms && ms > 0) {\n err = self._timeoutError(ms);\n }\n fn(err);\n }\n\n // for .resetTimeout() and Runner#uncaught()\n this.callback = done;\n\n if (this.fn && typeof this.fn.call !== 'function') {\n done(\n new TypeError(\n 'A runnable must be passed a function as its second argument.'\n )\n );\n return;\n }\n\n // explicit async with `done` argument\n if (this.async) {\n this.resetTimeout();\n\n // allows skip() to be used in an explicit async context\n this.skip = function asyncSkip() {\n this.pending = true;\n done();\n // halt execution, the uncaught handler will ignore the failure.\n throw new Pending('async skip; aborting execution');\n };\n\n try {\n callFnAsync(this.fn);\n } catch (err) {\n // handles async runnables which actually run synchronously\n errorWasHandled = true;\n if (err instanceof Pending) {\n return; // done() is already called in this.skip()\n } else if (this.allowUncaught) {\n throw err;\n }\n done(Runnable.toValueOrError(err));\n }\n return;\n }\n\n // sync or promise-returning\n try {\n callFn(this.fn);\n } catch (err) {\n errorWasHandled = true;\n if (err instanceof Pending) {\n return done();\n } else if (this.allowUncaught) {\n throw err;\n }\n done(Runnable.toValueOrError(err));\n }\n\n function callFn(fn) {\n var result = fn.call(ctx);\n if (result && typeof result.then === 'function') {\n self.resetTimeout();\n result.then(\n function () {\n done();\n // Return null so libraries like bluebird do not warn about\n // subsequently constructed Promises.\n return null;\n },\n function (reason) {\n done(reason || new Error('Promise rejected with no or falsy reason'));\n }\n );\n } else {\n if (self.asyncOnly) {\n return done(\n new Error(\n '--async-only option in use without declaring `done()` or returning a promise'\n )\n );\n }\n\n done();\n }\n }\n\n function callFnAsync(fn) {\n var result = fn.call(ctx, function (err) {\n if (err instanceof Error || toString.call(err) === '[object Error]') {\n return done(err);\n }\n if (err) {\n if (Object.prototype.toString.call(err) === '[object Object]') {\n return done(\n new Error('done() invoked with non-Error: ' + JSON.stringify(err))\n );\n }\n return done(new Error('done() invoked with non-Error: ' + err));\n }\n if (result && utils.isPromise(result)) {\n return done(\n new Error(\n 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'\n )\n );\n }\n\n done();\n });\n }\n};\n\n/**\n * Instantiates a \"timeout\" error\n *\n * @param {number} ms - Timeout (in milliseconds)\n * @returns {Error} a \"timeout\" error\n * @private\n */\nRunnable.prototype._timeoutError = function (ms) {\n let msg = `Timeout of ${ms}ms exceeded. For async tests and hooks, ensure \"done()\" is called; if returning a Promise, ensure it resolves.`;\n if (this.file) {\n msg += ' (' + this.file + ')';\n }\n return createTimeoutError(msg, ms, this.file);\n};\n\nvar constants = utils.defineConstants(\n /**\n * {@link Runnable}-related constants.\n * @public\n * @memberof Runnable\n * @readonly\n * @static\n * @alias constants\n * @enum {string}\n */\n {\n /**\n * Value of `state` prop when a `Runnable` has failed\n */\n STATE_FAILED: 'failed',\n /**\n * Value of `state` prop when a `Runnable` has passed\n */\n STATE_PASSED: 'passed',\n /**\n * Value of `state` prop when a `Runnable` has been skipped by user\n */\n STATE_PENDING: 'pending'\n }\n);\n\n/**\n * Given `value`, return identity if truthy, otherwise create an \"invalid exception\" error and return that.\n * @param {*} [value] - Value to return, if present\n * @returns {*|Error} `value`, otherwise an `Error`\n * @private\n */\nRunnable.toValueOrError = function (value) {\n return (\n value ||\n createInvalidExceptionError(\n 'Runnable failed with falsy or undefined exception. Please throw an Error instead.',\n value\n )\n );\n};\n\nRunnable.constants = constants;\n","'use strict';\n\nvar Runnable = require('./runnable');\nconst {inherits, constants} = require('./utils');\nconst {MOCHA_ID_PROP_NAME} = constants;\n\n/**\n * Expose `Hook`.\n */\n\nmodule.exports = Hook;\n\n/**\n * Initialize a new `Hook` with the given `title` and callback `fn`\n *\n * @class\n * @extends Runnable\n * @param {String} title\n * @param {Function} fn\n */\nfunction Hook(title, fn) {\n Runnable.call(this, title, fn);\n this.type = 'hook';\n}\n\n/**\n * Inherit from `Runnable.prototype`.\n */\ninherits(Hook, Runnable);\n\n/**\n * Resets the state for a next run.\n */\nHook.prototype.reset = function () {\n Runnable.prototype.reset.call(this);\n delete this._error;\n};\n\n/**\n * Get or set the test `err`.\n *\n * @memberof Hook\n * @public\n * @param {Error} err\n * @return {Error}\n */\nHook.prototype.error = function (err) {\n if (!arguments.length) {\n err = this._error;\n this._error = null;\n return err;\n }\n\n this._error = err;\n};\n\n/**\n * Returns an object suitable for IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nHook.prototype.serialize = function serialize() {\n return {\n $$currentRetry: this.currentRetry(),\n $$fullTitle: this.fullTitle(),\n $$isPending: Boolean(this.isPending()),\n $$titlePath: this.titlePath(),\n ctx:\n this.ctx && this.ctx.currentTest\n ? {\n currentTest: {\n title: this.ctx.currentTest.title,\n [MOCHA_ID_PROP_NAME]: this.ctx.currentTest.id\n }\n }\n : {},\n duration: this.duration,\n file: this.file,\n parent: {\n $$fullTitle: this.parent.fullTitle(),\n [MOCHA_ID_PROP_NAME]: this.parent.id\n },\n state: this.state,\n title: this.title,\n type: this.type,\n [MOCHA_ID_PROP_NAME]: this.id\n };\n};\n","'use strict';\n\n/**\n * Module dependencies.\n * @private\n */\nconst {EventEmitter} = require('events');\nconst Hook = require('./hook');\nvar {\n assignNewMochaID,\n clamp,\n constants: utilsConstants,\n defineConstants,\n getMochaID,\n inherits,\n isString\n} = require('./utils');\nconst debug = require('debug')('mocha:suite');\nconst milliseconds = require('ms');\nconst errors = require('./errors');\n\nconst {MOCHA_ID_PROP_NAME} = utilsConstants;\n\n/**\n * Expose `Suite`.\n */\n\nexports = module.exports = Suite;\n\n/**\n * Create a new `Suite` with the given `title` and parent `Suite`.\n *\n * @public\n * @param {Suite} parent - Parent suite (required!)\n * @param {string} title - Title\n * @return {Suite}\n */\nSuite.create = function (parent, title) {\n var suite = new Suite(title, parent.ctx);\n suite.parent = parent;\n title = suite.fullTitle();\n parent.addSuite(suite);\n return suite;\n};\n\n/**\n * Constructs a new `Suite` instance with the given `title`, `ctx`, and `isRoot`.\n *\n * @public\n * @class\n * @extends EventEmitter\n * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter|EventEmitter}\n * @param {string} title - Suite title.\n * @param {Context} parentContext - Parent context instance.\n * @param {boolean} [isRoot=false] - Whether this is the root suite.\n */\nfunction Suite(title, parentContext, isRoot) {\n if (!isString(title)) {\n throw errors.createInvalidArgumentTypeError(\n 'Suite argument \"title\" must be a string. Received type \"' +\n typeof title +\n '\"',\n 'title',\n 'string'\n );\n }\n this.title = title;\n function Context() {}\n Context.prototype = parentContext;\n this.ctx = new Context();\n this.suites = [];\n this.tests = [];\n this.root = isRoot === true;\n this.pending = false;\n this._retries = -1;\n this._beforeEach = [];\n this._beforeAll = [];\n this._afterEach = [];\n this._afterAll = [];\n this._timeout = 2000;\n this._slow = 75;\n this._bail = false;\n this._onlyTests = [];\n this._onlySuites = [];\n assignNewMochaID(this);\n\n Object.defineProperty(this, 'id', {\n get() {\n return getMochaID(this);\n }\n });\n\n this.reset();\n}\n\n/**\n * Inherit from `EventEmitter.prototype`.\n */\ninherits(Suite, EventEmitter);\n\n/**\n * Resets the state initially or for a next run.\n */\nSuite.prototype.reset = function () {\n this.delayed = false;\n function doReset(thingToReset) {\n thingToReset.reset();\n }\n this.suites.forEach(doReset);\n this.tests.forEach(doReset);\n this._beforeEach.forEach(doReset);\n this._afterEach.forEach(doReset);\n this._beforeAll.forEach(doReset);\n this._afterAll.forEach(doReset);\n};\n\n/**\n * Return a clone of this `Suite`.\n *\n * @private\n * @return {Suite}\n */\nSuite.prototype.clone = function () {\n var suite = new Suite(this.title);\n debug('clone');\n suite.ctx = this.ctx;\n suite.root = this.root;\n suite.timeout(this.timeout());\n suite.retries(this.retries());\n suite.slow(this.slow());\n suite.bail(this.bail());\n return suite;\n};\n\n/**\n * Set or get timeout `ms` or short-hand such as \"2s\".\n *\n * @private\n * @todo Do not attempt to set value if `ms` is undefined\n * @param {number|string} ms\n * @return {Suite|number} for chaining\n */\nSuite.prototype.timeout = function (ms) {\n if (!arguments.length) {\n return this._timeout;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n\n // Clamp to range\n var INT_MAX = Math.pow(2, 31) - 1;\n var range = [0, INT_MAX];\n ms = clamp(ms, range);\n\n debug('timeout %d', ms);\n this._timeout = parseInt(ms, 10);\n return this;\n};\n\n/**\n * Set or get number of times to retry a failed test.\n *\n * @private\n * @param {number|string} n\n * @return {Suite|number} for chaining\n */\nSuite.prototype.retries = function (n) {\n if (!arguments.length) {\n return this._retries;\n }\n debug('retries %d', n);\n this._retries = parseInt(n, 10) || 0;\n return this;\n};\n\n/**\n * Set or get slow `ms` or short-hand such as \"2s\".\n *\n * @private\n * @param {number|string} ms\n * @return {Suite|number} for chaining\n */\nSuite.prototype.slow = function (ms) {\n if (!arguments.length) {\n return this._slow;\n }\n if (typeof ms === 'string') {\n ms = milliseconds(ms);\n }\n debug('slow %d', ms);\n this._slow = ms;\n return this;\n};\n\n/**\n * Set or get whether to bail after first error.\n *\n * @private\n * @param {boolean} bail\n * @return {Suite|number} for chaining\n */\nSuite.prototype.bail = function (bail) {\n if (!arguments.length) {\n return this._bail;\n }\n debug('bail %s', bail);\n this._bail = bail;\n return this;\n};\n\n/**\n * Check if this suite or its parent suite is marked as pending.\n *\n * @private\n */\nSuite.prototype.isPending = function () {\n return this.pending || (this.parent && this.parent.isPending());\n};\n\n/**\n * Generic hook-creator.\n * @private\n * @param {string} title - Title of hook\n * @param {Function} fn - Hook callback\n * @returns {Hook} A new hook\n */\nSuite.prototype._createHook = function (title, fn) {\n var hook = new Hook(title, fn);\n hook.parent = this;\n hook.timeout(this.timeout());\n hook.retries(this.retries());\n hook.slow(this.slow());\n hook.ctx = this.ctx;\n hook.file = this.file;\n return hook;\n};\n\n/**\n * Run `fn(test[, done])` before running tests.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.beforeAll = function (title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"before all\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._beforeAll.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_ALL, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` after running tests.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.afterAll = function (title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"after all\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._afterAll.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_ALL, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` before each test case.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.beforeEach = function (title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"before each\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._beforeEach.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_BEFORE_EACH, hook);\n return this;\n};\n\n/**\n * Run `fn(test[, done])` after each test case.\n *\n * @private\n * @param {string} title\n * @param {Function} fn\n * @return {Suite} for chaining\n */\nSuite.prototype.afterEach = function (title, fn) {\n if (this.isPending()) {\n return this;\n }\n if (typeof title === 'function') {\n fn = title;\n title = fn.name;\n }\n title = '\"after each\" hook' + (title ? ': ' + title : '');\n\n var hook = this._createHook(title, fn);\n this._afterEach.push(hook);\n this.emit(constants.EVENT_SUITE_ADD_HOOK_AFTER_EACH, hook);\n return this;\n};\n\n/**\n * Add a test `suite`.\n *\n * @private\n * @param {Suite} suite\n * @return {Suite} for chaining\n */\nSuite.prototype.addSuite = function (suite) {\n suite.parent = this;\n suite.root = false;\n suite.timeout(this.timeout());\n suite.retries(this.retries());\n suite.slow(this.slow());\n suite.bail(this.bail());\n this.suites.push(suite);\n this.emit(constants.EVENT_SUITE_ADD_SUITE, suite);\n return this;\n};\n\n/**\n * Add a `test` to this suite.\n *\n * @private\n * @param {Test} test\n * @return {Suite} for chaining\n */\nSuite.prototype.addTest = function (test) {\n test.parent = this;\n test.timeout(this.timeout());\n test.retries(this.retries());\n test.slow(this.slow());\n test.ctx = this.ctx;\n this.tests.push(test);\n this.emit(constants.EVENT_SUITE_ADD_TEST, test);\n return this;\n};\n\n/**\n * Return the full title generated by recursively concatenating the parent's\n * full title.\n *\n * @memberof Suite\n * @public\n * @return {string}\n */\nSuite.prototype.fullTitle = function () {\n return this.titlePath().join(' ');\n};\n\n/**\n * Return the title path generated by recursively concatenating the parent's\n * title path.\n *\n * @memberof Suite\n * @public\n * @return {string[]}\n */\nSuite.prototype.titlePath = function () {\n var result = [];\n if (this.parent) {\n result = result.concat(this.parent.titlePath());\n }\n if (!this.root) {\n result.push(this.title);\n }\n return result;\n};\n\n/**\n * Return the total number of tests.\n *\n * @memberof Suite\n * @public\n * @return {number}\n */\nSuite.prototype.total = function () {\n return (\n this.suites.reduce(function (sum, suite) {\n return sum + suite.total();\n }, 0) + this.tests.length\n );\n};\n\n/**\n * Iterates through each suite recursively to find all tests. Applies a\n * function in the format `fn(test)`.\n *\n * @private\n * @param {Function} fn\n * @return {Suite}\n */\nSuite.prototype.eachTest = function (fn) {\n this.tests.forEach(fn);\n this.suites.forEach(function (suite) {\n suite.eachTest(fn);\n });\n return this;\n};\n\n/**\n * This will run the root suite if we happen to be running in delayed mode.\n * @private\n */\nSuite.prototype.run = function run() {\n if (this.root) {\n this.emit(constants.EVENT_ROOT_SUITE_RUN);\n }\n};\n\n/**\n * Determines whether a suite has an `only` test or suite as a descendant.\n *\n * @private\n * @returns {Boolean}\n */\nSuite.prototype.hasOnly = function hasOnly() {\n return (\n this._onlyTests.length > 0 ||\n this._onlySuites.length > 0 ||\n this.suites.some(function (suite) {\n return suite.hasOnly();\n })\n );\n};\n\n/**\n * Filter suites based on `isOnly` logic.\n *\n * @private\n * @returns {Boolean}\n */\nSuite.prototype.filterOnly = function filterOnly() {\n if (this._onlyTests.length) {\n // If the suite contains `only` tests, run those and ignore any nested suites.\n this.tests = this._onlyTests;\n this.suites = [];\n } else {\n // Otherwise, do not run any of the tests in this suite.\n this.tests = [];\n this._onlySuites.forEach(function (onlySuite) {\n // If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.\n // Otherwise, all of the tests on this `only` suite should be run, so don't filter it.\n if (onlySuite.hasOnly()) {\n onlySuite.filterOnly();\n }\n });\n // Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.\n var onlySuites = this._onlySuites;\n this.suites = this.suites.filter(function (childSuite) {\n return onlySuites.indexOf(childSuite) !== -1 || childSuite.filterOnly();\n });\n }\n // Keep the suite only if there is something to run\n return this.tests.length > 0 || this.suites.length > 0;\n};\n\n/**\n * Adds a suite to the list of subsuites marked `only`.\n *\n * @private\n * @param {Suite} suite\n */\nSuite.prototype.appendOnlySuite = function (suite) {\n this._onlySuites.push(suite);\n};\n\n/**\n * Marks a suite to be `only`.\n *\n * @private\n */\nSuite.prototype.markOnly = function () {\n this.parent && this.parent.appendOnlySuite(this);\n};\n\n/**\n * Adds a test to the list of tests marked `only`.\n *\n * @private\n * @param {Test} test\n */\nSuite.prototype.appendOnlyTest = function (test) {\n this._onlyTests.push(test);\n};\n\n/**\n * Returns the array of hooks by hook name; see `HOOK_TYPE_*` constants.\n * @private\n */\nSuite.prototype.getHooks = function getHooks(name) {\n return this['_' + name];\n};\n\n/**\n * cleans all references from this suite and all child suites.\n */\nSuite.prototype.dispose = function () {\n this.suites.forEach(function (suite) {\n suite.dispose();\n });\n this.cleanReferences();\n};\n\n/**\n * Cleans up the references to all the deferred functions\n * (before/after/beforeEach/afterEach) and tests of a Suite.\n * These must be deleted otherwise a memory leak can happen,\n * as those functions may reference variables from closures,\n * thus those variables can never be garbage collected as long\n * as the deferred functions exist.\n *\n * @private\n */\nSuite.prototype.cleanReferences = function cleanReferences() {\n function cleanArrReferences(arr) {\n for (var i = 0; i < arr.length; i++) {\n delete arr[i].fn;\n }\n }\n\n if (Array.isArray(this._beforeAll)) {\n cleanArrReferences(this._beforeAll);\n }\n\n if (Array.isArray(this._beforeEach)) {\n cleanArrReferences(this._beforeEach);\n }\n\n if (Array.isArray(this._afterAll)) {\n cleanArrReferences(this._afterAll);\n }\n\n if (Array.isArray(this._afterEach)) {\n cleanArrReferences(this._afterEach);\n }\n\n for (var i = 0; i < this.tests.length; i++) {\n delete this.tests[i].fn;\n }\n};\n\n/**\n * Returns an object suitable for IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nSuite.prototype.serialize = function serialize() {\n return {\n _bail: this._bail,\n $$fullTitle: this.fullTitle(),\n $$isPending: Boolean(this.isPending()),\n root: this.root,\n title: this.title,\n [MOCHA_ID_PROP_NAME]: this.id,\n parent: this.parent ? {[MOCHA_ID_PROP_NAME]: this.parent.id} : null\n };\n};\n\nvar constants = defineConstants(\n /**\n * {@link Suite}-related constants.\n * @public\n * @memberof Suite\n * @alias constants\n * @readonly\n * @static\n * @enum {string}\n */\n {\n /**\n * Event emitted after a test file has been loaded. Not emitted in browser.\n */\n EVENT_FILE_POST_REQUIRE: 'post-require',\n /**\n * Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.\n */\n EVENT_FILE_PRE_REQUIRE: 'pre-require',\n /**\n * Event emitted immediately after a test file has been loaded. Not emitted in browser.\n */\n EVENT_FILE_REQUIRE: 'require',\n /**\n * Event emitted when `global.run()` is called (use with `delay` option).\n */\n EVENT_ROOT_SUITE_RUN: 'run',\n\n /**\n * Namespace for collection of a `Suite`'s \"after all\" hooks.\n */\n HOOK_TYPE_AFTER_ALL: 'afterAll',\n /**\n * Namespace for collection of a `Suite`'s \"after each\" hooks.\n */\n HOOK_TYPE_AFTER_EACH: 'afterEach',\n /**\n * Namespace for collection of a `Suite`'s \"before all\" hooks.\n */\n HOOK_TYPE_BEFORE_ALL: 'beforeAll',\n /**\n * Namespace for collection of a `Suite`'s \"before each\" hooks.\n */\n HOOK_TYPE_BEFORE_EACH: 'beforeEach',\n\n /**\n * Emitted after a child `Suite` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_SUITE: 'suite',\n /**\n * Emitted after an \"after all\" `Hook` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll',\n /**\n * Emitted after an \"after each\" `Hook` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach',\n /**\n * Emitted after an \"before all\" `Hook` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll',\n /**\n * Emitted after an \"before each\" `Hook` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach',\n /**\n * Emitted after a `Test` has been added to a `Suite`.\n */\n EVENT_SUITE_ADD_TEST: 'test'\n }\n);\n\nSuite.constants = constants;\n","'use strict';\n\n/**\n * Module dependencies.\n * @private\n */\nvar EventEmitter = require('events').EventEmitter;\nvar Pending = require('./pending');\nvar utils = require('./utils');\nvar debug = require('debug')('mocha:runner');\nvar Runnable = require('./runnable');\nvar Suite = require('./suite');\nvar HOOK_TYPE_BEFORE_EACH = Suite.constants.HOOK_TYPE_BEFORE_EACH;\nvar HOOK_TYPE_AFTER_EACH = Suite.constants.HOOK_TYPE_AFTER_EACH;\nvar HOOK_TYPE_AFTER_ALL = Suite.constants.HOOK_TYPE_AFTER_ALL;\nvar HOOK_TYPE_BEFORE_ALL = Suite.constants.HOOK_TYPE_BEFORE_ALL;\nvar EVENT_ROOT_SUITE_RUN = Suite.constants.EVENT_ROOT_SUITE_RUN;\nvar STATE_FAILED = Runnable.constants.STATE_FAILED;\nvar STATE_PASSED = Runnable.constants.STATE_PASSED;\nvar STATE_PENDING = Runnable.constants.STATE_PENDING;\nvar stackFilter = utils.stackTraceFilter();\nvar stringify = utils.stringify;\n\nconst {\n createInvalidExceptionError,\n createUnsupportedError,\n createFatalError,\n isMochaError,\n constants: errorConstants\n} = require('./errors');\n\n/**\n * Non-enumerable globals.\n * @private\n * @readonly\n */\nvar globals = [\n 'setTimeout',\n 'clearTimeout',\n 'setInterval',\n 'clearInterval',\n 'XMLHttpRequest',\n 'Date',\n 'setImmediate',\n 'clearImmediate'\n];\n\nvar constants = utils.defineConstants(\n /**\n * {@link Runner}-related constants.\n * @public\n * @memberof Runner\n * @readonly\n * @alias constants\n * @static\n * @enum {string}\n */\n {\n /**\n * Emitted when {@link Hook} execution begins\n */\n EVENT_HOOK_BEGIN: 'hook',\n /**\n * Emitted when {@link Hook} execution ends\n */\n EVENT_HOOK_END: 'hook end',\n /**\n * Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)\n */\n EVENT_RUN_BEGIN: 'start',\n /**\n * Emitted when Root {@link Suite} execution has been delayed via `delay` option\n */\n EVENT_DELAY_BEGIN: 'waiting',\n /**\n * Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()`\n */\n EVENT_DELAY_END: 'ready',\n /**\n * Emitted when Root {@link Suite} execution ends\n */\n EVENT_RUN_END: 'end',\n /**\n * Emitted when {@link Suite} execution begins\n */\n EVENT_SUITE_BEGIN: 'suite',\n /**\n * Emitted when {@link Suite} execution ends\n */\n EVENT_SUITE_END: 'suite end',\n /**\n * Emitted when {@link Test} execution begins\n */\n EVENT_TEST_BEGIN: 'test',\n /**\n * Emitted when {@link Test} execution ends\n */\n EVENT_TEST_END: 'test end',\n /**\n * Emitted when {@link Test} execution fails\n */\n EVENT_TEST_FAIL: 'fail',\n /**\n * Emitted when {@link Test} execution succeeds\n */\n EVENT_TEST_PASS: 'pass',\n /**\n * Emitted when {@link Test} becomes pending\n */\n EVENT_TEST_PENDING: 'pending',\n /**\n * Emitted when {@link Test} execution has failed, but will retry\n */\n EVENT_TEST_RETRY: 'retry',\n /**\n * Initial state of Runner\n */\n STATE_IDLE: 'idle',\n /**\n * State set to this value when the Runner has started running\n */\n STATE_RUNNING: 'running',\n /**\n * State set to this value when the Runner has stopped\n */\n STATE_STOPPED: 'stopped'\n }\n);\n\nclass Runner extends EventEmitter {\n /**\n * Initialize a `Runner` at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.\n *\n * @extends external:EventEmitter\n * @public\n * @class\n * @param {Suite} suite - Root suite\n * @param {Object} [opts] - Settings object\n * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.\n * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.\n * @param {boolean} [opts.dryRun] - Whether to report tests without running them.\n * @param {boolean} [opts.failZero] - Whether to fail test run if zero tests encountered.\n */\n constructor(suite, opts = {}) {\n super();\n\n var self = this;\n this._globals = [];\n this._abort = false;\n this.suite = suite;\n this._opts = opts;\n this.state = constants.STATE_IDLE;\n this.total = suite.total();\n this.failures = 0;\n /**\n * @type {Map>>}\n */\n this._eventListeners = new Map();\n this.on(constants.EVENT_TEST_END, function (test) {\n if (test.type === 'test' && test.retriedTest() && test.parent) {\n var idx =\n test.parent.tests && test.parent.tests.indexOf(test.retriedTest());\n if (idx > -1) test.parent.tests[idx] = test;\n }\n self.checkGlobals(test);\n });\n this.on(constants.EVENT_HOOK_END, function (hook) {\n self.checkGlobals(hook);\n });\n this._defaultGrep = /.*/;\n this.grep(this._defaultGrep);\n this.globals(this.globalProps());\n\n this.uncaught = this._uncaught.bind(this);\n this.unhandled = (reason, promise) => {\n if (isMochaError(reason)) {\n debug(\n 'trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:',\n reason\n );\n this.uncaught(reason);\n } else {\n debug(\n 'trapped unhandled rejection from (probably) user code; re-emitting on process'\n );\n this._removeEventListener(\n process,\n 'unhandledRejection',\n this.unhandled\n );\n try {\n process.emit('unhandledRejection', reason, promise);\n } finally {\n this._addEventListener(process, 'unhandledRejection', this.unhandled);\n }\n }\n };\n }\n}\n\n/**\n * Wrapper for setImmediate, process.nextTick, or browser polyfill.\n *\n * @param {Function} fn\n * @private\n */\nRunner.immediately = global.setImmediate || process.nextTick;\n\n/**\n * Replacement for `target.on(eventName, listener)` that does bookkeeping to remove them when this runner instance is disposed.\n * @param {EventEmitter} target - The `EventEmitter`\n * @param {string} eventName - The event name\n * @param {string} fn - Listener function\n * @private\n */\nRunner.prototype._addEventListener = function (target, eventName, listener) {\n debug(\n '_addEventListener(): adding for event %s; %d current listeners',\n eventName,\n target.listenerCount(eventName)\n );\n /* istanbul ignore next */\n if (\n this._eventListeners.has(target) &&\n this._eventListeners.get(target).has(eventName) &&\n this._eventListeners.get(target).get(eventName).has(listener)\n ) {\n debug(\n 'warning: tried to attach duplicate event listener for %s',\n eventName\n );\n return;\n }\n target.on(eventName, listener);\n const targetListeners = this._eventListeners.has(target)\n ? this._eventListeners.get(target)\n : new Map();\n const targetEventListeners = targetListeners.has(eventName)\n ? targetListeners.get(eventName)\n : new Set();\n targetEventListeners.add(listener);\n targetListeners.set(eventName, targetEventListeners);\n this._eventListeners.set(target, targetListeners);\n};\n\n/**\n * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping.\n * @param {EventEmitter} target - The `EventEmitter`\n * @param {string} eventName - The event name\n * @param {function} listener - Listener function\n * @private\n */\nRunner.prototype._removeEventListener = function (target, eventName, listener) {\n target.removeListener(eventName, listener);\n\n if (this._eventListeners.has(target)) {\n const targetListeners = this._eventListeners.get(target);\n if (targetListeners.has(eventName)) {\n const targetEventListeners = targetListeners.get(eventName);\n targetEventListeners.delete(listener);\n if (!targetEventListeners.size) {\n targetListeners.delete(eventName);\n }\n }\n if (!targetListeners.size) {\n this._eventListeners.delete(target);\n }\n } else {\n debug('trying to remove listener for untracked object %s', target);\n }\n};\n\n/**\n * Removes all event handlers set during a run on this instance.\n * Remark: this does _not_ clean/dispose the tests or suites themselves.\n */\nRunner.prototype.dispose = function () {\n this.removeAllListeners();\n this._eventListeners.forEach((targetListeners, target) => {\n targetListeners.forEach((targetEventListeners, eventName) => {\n targetEventListeners.forEach(listener => {\n target.removeListener(eventName, listener);\n });\n });\n });\n this._eventListeners.clear();\n};\n\n/**\n * Run tests with full titles matching `re`. Updates runner.total\n * with number of tests matched.\n *\n * @public\n * @memberof Runner\n * @param {RegExp} re\n * @param {boolean} invert\n * @return {Runner} Runner instance.\n */\nRunner.prototype.grep = function (re, invert) {\n debug('grep(): setting to %s', re);\n this._grep = re;\n this._invert = invert;\n this.total = this.grepTotal(this.suite);\n return this;\n};\n\n/**\n * Returns the number of tests matching the grep search for the\n * given suite.\n *\n * @memberof Runner\n * @public\n * @param {Suite} suite\n * @return {number}\n */\nRunner.prototype.grepTotal = function (suite) {\n var self = this;\n var total = 0;\n\n suite.eachTest(function (test) {\n var match = self._grep.test(test.fullTitle());\n if (self._invert) {\n match = !match;\n }\n if (match) {\n total++;\n }\n });\n\n return total;\n};\n\n/**\n * Return a list of global properties.\n *\n * @return {Array}\n * @private\n */\nRunner.prototype.globalProps = function () {\n var props = Object.keys(global);\n\n // non-enumerables\n for (var i = 0; i < globals.length; ++i) {\n if (~props.indexOf(globals[i])) {\n continue;\n }\n props.push(globals[i]);\n }\n\n return props;\n};\n\n/**\n * Allow the given `arr` of globals.\n *\n * @public\n * @memberof Runner\n * @param {Array} arr\n * @return {Runner} Runner instance.\n */\nRunner.prototype.globals = function (arr) {\n if (!arguments.length) {\n return this._globals;\n }\n debug('globals(): setting to %O', arr);\n this._globals = this._globals.concat(arr);\n return this;\n};\n\n/**\n * Check for global variable leaks.\n *\n * @private\n */\nRunner.prototype.checkGlobals = function (test) {\n if (!this.checkLeaks) {\n return;\n }\n var ok = this._globals;\n\n var globals = this.globalProps();\n var leaks;\n\n if (test) {\n ok = ok.concat(test._allowedGlobals || []);\n }\n\n if (this.prevGlobalsLength === globals.length) {\n return;\n }\n this.prevGlobalsLength = globals.length;\n\n leaks = filterLeaks(ok, globals);\n this._globals = this._globals.concat(leaks);\n\n if (leaks.length) {\n var msg = `global leak(s) detected: ${leaks.map(e => `'${e}'`).join(', ')}`;\n this.fail(test, new Error(msg));\n }\n};\n\n/**\n * Fail the given `test`.\n *\n * If `test` is a hook, failures work in the following pattern:\n * - If bail, run corresponding `after each` and `after` hooks,\n * then exit\n * - Failed `before` hook skips all tests in a suite and subsuites,\n * but jumps to corresponding `after` hook\n * - Failed `before each` hook skips remaining tests in a\n * suite and jumps to corresponding `after each` hook,\n * which is run only once\n * - Failed `after` hook does not alter execution order\n * - Failed `after each` hook skips remaining tests in a\n * suite and subsuites, but executes other `after each`\n * hooks\n *\n * @private\n * @param {Runnable} test\n * @param {Error} err\n * @param {boolean} [force=false] - Whether to fail a pending test.\n */\nRunner.prototype.fail = function (test, err, force) {\n force = force === true;\n if (test.isPending() && !force) {\n return;\n }\n if (this.state === constants.STATE_STOPPED) {\n if (err.code === errorConstants.MULTIPLE_DONE) {\n throw err;\n }\n throw createFatalError(\n 'Test failed after root suite execution completed!',\n err\n );\n }\n\n ++this.failures;\n debug('total number of failures: %d', this.failures);\n test.state = STATE_FAILED;\n\n if (!isError(err)) {\n err = thrown2Error(err);\n }\n\n // Filter the stack traces\n if (!this.fullStackTrace) {\n const alreadyFiltered = new Set();\n let currentErr = err;\n\n while (currentErr && currentErr.stack && !alreadyFiltered.has(currentErr)) {\n alreadyFiltered.add(currentErr);\n\n try {\n currentErr.stack = stackFilter(currentErr.stack);\n } catch (ignore) {\n // some environments do not take kindly to monkeying with the stack\n }\n\n currentErr = currentErr.cause;\n }\n }\n\n this.emit(constants.EVENT_TEST_FAIL, test, err);\n};\n\n/**\n * Run hook `name` callbacks and then invoke `fn()`.\n *\n * @private\n * @param {string} name\n * @param {Function} fn\n */\n\nRunner.prototype.hook = function (name, fn) {\n if (this._opts.dryRun) return fn();\n\n var suite = this.suite;\n var hooks = suite.getHooks(name);\n var self = this;\n\n function next(i) {\n var hook = hooks[i];\n if (!hook) {\n return fn();\n }\n self.currentRunnable = hook;\n\n if (name === HOOK_TYPE_BEFORE_ALL) {\n hook.ctx.currentTest = hook.parent.tests[0];\n } else if (name === HOOK_TYPE_AFTER_ALL) {\n hook.ctx.currentTest = hook.parent.tests[hook.parent.tests.length - 1];\n } else {\n hook.ctx.currentTest = self.test;\n }\n\n setHookTitle(hook);\n\n hook.allowUncaught = self.allowUncaught;\n\n self.emit(constants.EVENT_HOOK_BEGIN, hook);\n\n if (!hook.listeners('error').length) {\n self._addEventListener(hook, 'error', function (err) {\n self.fail(hook, err);\n });\n }\n\n hook.run(function cbHookRun(err) {\n var testError = hook.error();\n if (testError) {\n self.fail(self.test, testError);\n }\n // conditional skip\n if (hook.pending) {\n if (name === HOOK_TYPE_AFTER_EACH) {\n // TODO define and implement use case\n if (self.test) {\n self.test.pending = true;\n }\n } else if (name === HOOK_TYPE_BEFORE_EACH) {\n if (self.test) {\n self.test.pending = true;\n }\n self.emit(constants.EVENT_HOOK_END, hook);\n hook.pending = false; // activates hook for next test\n return fn(new Error('abort hookDown'));\n } else if (name === HOOK_TYPE_BEFORE_ALL) {\n suite.tests.forEach(function (test) {\n test.pending = true;\n });\n suite.suites.forEach(function (suite) {\n suite.pending = true;\n });\n hooks = [];\n } else {\n hook.pending = false;\n var errForbid = createUnsupportedError('`this.skip` forbidden');\n self.fail(hook, errForbid);\n return fn(errForbid);\n }\n } else if (err) {\n self.fail(hook, err);\n // stop executing hooks, notify callee of hook err\n return fn(err);\n }\n self.emit(constants.EVENT_HOOK_END, hook);\n delete hook.ctx.currentTest;\n setHookTitle(hook);\n next(++i);\n });\n\n function setHookTitle(hook) {\n hook.originalTitle = hook.originalTitle || hook.title;\n if (hook.ctx && hook.ctx.currentTest) {\n hook.title = `${hook.originalTitle} for \"${hook.ctx.currentTest.title}\"`;\n } else {\n var parentTitle;\n if (hook.parent.title) {\n parentTitle = hook.parent.title;\n } else {\n parentTitle = hook.parent.root ? '{root}' : '';\n }\n hook.title = `${hook.originalTitle} in \"${parentTitle}\"`;\n }\n }\n }\n\n Runner.immediately(function () {\n next(0);\n });\n};\n\n/**\n * Run hook `name` for the given array of `suites`\n * in order, and callback `fn(err, errSuite)`.\n *\n * @private\n * @param {string} name\n * @param {Array} suites\n * @param {Function} fn\n */\nRunner.prototype.hooks = function (name, suites, fn) {\n var self = this;\n var orig = this.suite;\n\n function next(suite) {\n self.suite = suite;\n\n if (!suite) {\n self.suite = orig;\n return fn();\n }\n\n self.hook(name, function (err) {\n if (err) {\n var errSuite = self.suite;\n self.suite = orig;\n return fn(err, errSuite);\n }\n\n next(suites.pop());\n });\n }\n\n next(suites.pop());\n};\n\n/**\n * Run 'afterEach' hooks from bottom up.\n *\n * @param {String} name\n * @param {Function} fn\n * @private\n */\nRunner.prototype.hookUp = function (name, fn) {\n var suites = [this.suite].concat(this.parents()).reverse();\n this.hooks(name, suites, fn);\n};\n\n/**\n * Run 'beforeEach' hooks from top level down.\n *\n * @param {String} name\n * @param {Function} fn\n * @private\n */\nRunner.prototype.hookDown = function (name, fn) {\n var suites = [this.suite].concat(this.parents());\n this.hooks(name, suites, fn);\n};\n\n/**\n * Return an array of parent Suites from\n * closest to furthest.\n *\n * @return {Array}\n * @private\n */\nRunner.prototype.parents = function () {\n var suite = this.suite;\n var suites = [];\n while (suite.parent) {\n suite = suite.parent;\n suites.push(suite);\n }\n return suites;\n};\n\n/**\n * Run the current test and callback `fn(err)`.\n *\n * @param {Function} fn\n * @private\n */\nRunner.prototype.runTest = function (fn) {\n if (this._opts.dryRun) return Runner.immediately(fn);\n\n var self = this;\n var test = this.test;\n\n if (!test) {\n return;\n }\n\n if (this.asyncOnly) {\n test.asyncOnly = true;\n }\n this._addEventListener(test, 'error', function (err) {\n self.fail(test, err);\n });\n if (this.allowUncaught) {\n test.allowUncaught = true;\n return test.run(fn);\n }\n try {\n test.run(fn);\n } catch (err) {\n fn(err);\n }\n};\n\n/**\n * Run tests in the given `suite` and invoke the callback `fn()` when complete.\n *\n * @private\n * @param {Suite} suite\n * @param {Function} fn\n */\nRunner.prototype.runTests = function (suite, fn) {\n var self = this;\n var tests = suite.tests.slice();\n var test;\n\n function hookErr(_, errSuite, after) {\n // before/after Each hook for errSuite failed:\n var orig = self.suite;\n\n // for failed 'after each' hook start from errSuite parent,\n // otherwise start from errSuite itself\n self.suite = after ? errSuite.parent : errSuite;\n\n if (self.suite) {\n self.hookUp(HOOK_TYPE_AFTER_EACH, function (err2, errSuite2) {\n self.suite = orig;\n // some hooks may fail even now\n if (err2) {\n return hookErr(err2, errSuite2, true);\n }\n // report error suite\n fn(errSuite);\n });\n } else {\n // there is no need calling other 'after each' hooks\n self.suite = orig;\n fn(errSuite);\n }\n }\n\n function next(err, errSuite) {\n // if we bail after first err\n if (self.failures && suite._bail) {\n tests = [];\n }\n\n if (self._abort) {\n return fn();\n }\n\n if (err) {\n return hookErr(err, errSuite, true);\n }\n\n // next test\n test = tests.shift();\n\n // all done\n if (!test) {\n return fn();\n }\n\n // grep\n var match = self._grep.test(test.fullTitle());\n if (self._invert) {\n match = !match;\n }\n if (!match) {\n // Run immediately only if we have defined a grep. When we\n // define a grep — It can cause maximum callstack error if\n // the grep is doing a large recursive loop by neglecting\n // all tests. The run immediately function also comes with\n // a performance cost. So we don't want to run immediately\n // if we run the whole test suite, because running the whole\n // test suite don't do any immediate recursive loops. Thus,\n // allowing a JS runtime to breathe.\n if (self._grep !== self._defaultGrep) {\n Runner.immediately(next);\n } else {\n next();\n }\n return;\n }\n\n // static skip, no hooks are executed\n if (test.isPending()) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return next();\n }\n\n // execute test and hook(s)\n self.emit(constants.EVENT_TEST_BEGIN, (self.test = test));\n self.hookDown(HOOK_TYPE_BEFORE_EACH, function (err, errSuite) {\n // conditional skip within beforeEach\n if (test.isPending()) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n // skip inner afterEach hooks below errSuite level\n var origSuite = self.suite;\n self.suite = errSuite || self.suite;\n return self.hookUp(HOOK_TYPE_AFTER_EACH, function (e, eSuite) {\n self.suite = origSuite;\n next(e, eSuite);\n });\n }\n if (err) {\n return hookErr(err, errSuite, false);\n }\n self.currentRunnable = self.test;\n self.runTest(function (err) {\n test = self.test;\n // conditional skip within it\n if (test.pending) {\n if (self.forbidPending) {\n self.fail(test, new Error('Pending test forbidden'), true);\n } else {\n test.state = STATE_PENDING;\n self.emit(constants.EVENT_TEST_PENDING, test);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n } else if (err) {\n var retry = test.currentRetry();\n if (retry < test.retries()) {\n var clonedTest = test.clone();\n clonedTest.currentRetry(retry + 1);\n tests.unshift(clonedTest);\n\n self.emit(constants.EVENT_TEST_RETRY, test, err);\n\n // Early return + hook trigger so that it doesn't\n // increment the count wrong\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n } else {\n self.fail(test, err);\n }\n self.emit(constants.EVENT_TEST_END, test);\n return self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n }\n\n test.state = STATE_PASSED;\n self.emit(constants.EVENT_TEST_PASS, test);\n self.emit(constants.EVENT_TEST_END, test);\n self.hookUp(HOOK_TYPE_AFTER_EACH, next);\n });\n });\n }\n\n this.next = next;\n this.hookErr = hookErr;\n next();\n};\n\n/**\n * Run the given `suite` and invoke the callback `fn()` when complete.\n *\n * @private\n * @param {Suite} suite\n * @param {Function} fn\n */\nRunner.prototype.runSuite = function (suite, fn) {\n var i = 0;\n var self = this;\n var total = this.grepTotal(suite);\n\n debug('runSuite(): running %s', suite.fullTitle());\n\n if (!total || (self.failures && suite._bail)) {\n debug('runSuite(): bailing');\n return fn();\n }\n\n this.emit(constants.EVENT_SUITE_BEGIN, (this.suite = suite));\n\n function next(errSuite) {\n if (errSuite) {\n // current suite failed on a hook from errSuite\n if (errSuite === suite) {\n // if errSuite is current suite\n // continue to the next sibling suite\n return done();\n }\n // errSuite is among the parents of current suite\n // stop execution of errSuite and all sub-suites\n return done(errSuite);\n }\n\n if (self._abort) {\n return done();\n }\n\n var curr = suite.suites[i++];\n if (!curr) {\n return done();\n }\n\n // Avoid grep neglecting large number of tests causing a\n // huge recursive loop and thus a maximum call stack error.\n // See comment in `this.runTests()` for more information.\n if (self._grep !== self._defaultGrep) {\n Runner.immediately(function () {\n self.runSuite(curr, next);\n });\n } else {\n self.runSuite(curr, next);\n }\n }\n\n function done(errSuite) {\n self.suite = suite;\n self.nextSuite = next;\n\n // remove reference to test\n delete self.test;\n\n self.hook(HOOK_TYPE_AFTER_ALL, function () {\n self.emit(constants.EVENT_SUITE_END, suite);\n fn(errSuite);\n });\n }\n\n this.nextSuite = next;\n\n this.hook(HOOK_TYPE_BEFORE_ALL, function (err) {\n if (err) {\n return done();\n }\n self.runTests(suite, next);\n });\n};\n\n/**\n * Handle uncaught exceptions within runner.\n *\n * This function is bound to the instance as `Runner#uncaught` at instantiation\n * time. It's intended to be listening on the `Process.uncaughtException` event.\n * In order to not leak EE listeners, we need to ensure no more than a single\n * `uncaughtException` listener exists per `Runner`. The only way to do\n * this--because this function needs the context (and we don't have lambdas)--is\n * to use `Function.prototype.bind`. We need strict equality to unregister and\n * _only_ unregister the _one_ listener we set from the\n * `Process.uncaughtException` event; would be poor form to just remove\n * everything. See {@link Runner#run} for where the event listener is registered\n * and unregistered.\n * @param {Error} err - Some uncaught error\n * @private\n */\nRunner.prototype._uncaught = function (err) {\n // this is defensive to prevent future developers from mis-calling this function.\n // it's more likely that it'd be called with the incorrect context--say, the global\n // `process` object--than it would to be called with a context that is not a \"subclass\"\n // of `Runner`.\n if (!(this instanceof Runner)) {\n throw createFatalError(\n 'Runner#uncaught() called with invalid context',\n this\n );\n }\n if (err instanceof Pending) {\n debug('uncaught(): caught a Pending');\n return;\n }\n // browser does not exit script when throwing in global.onerror()\n if (this.allowUncaught && !utils.isBrowser()) {\n debug('uncaught(): bubbling exception due to --allow-uncaught');\n throw err;\n }\n\n if (this.state === constants.STATE_STOPPED) {\n debug('uncaught(): throwing after run has completed!');\n throw err;\n }\n\n if (err) {\n debug('uncaught(): got truthy exception %O', err);\n } else {\n debug('uncaught(): undefined/falsy exception');\n err = createInvalidExceptionError(\n 'Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger',\n err\n );\n }\n\n if (!isError(err)) {\n err = thrown2Error(err);\n debug('uncaught(): converted \"error\" %o to Error', err);\n }\n err.uncaught = true;\n\n var runnable = this.currentRunnable;\n\n if (!runnable) {\n runnable = new Runnable('Uncaught error outside test suite');\n debug('uncaught(): no current Runnable; created a phony one');\n runnable.parent = this.suite;\n\n if (this.state === constants.STATE_RUNNING) {\n debug('uncaught(): failing gracefully');\n this.fail(runnable, err);\n } else {\n // Can't recover from this failure\n debug('uncaught(): test run has not yet started; unrecoverable');\n this.emit(constants.EVENT_RUN_BEGIN);\n this.fail(runnable, err);\n this.emit(constants.EVENT_RUN_END);\n }\n\n return;\n }\n\n runnable.clearTimeout();\n\n if (runnable.isFailed()) {\n debug('uncaught(): Runnable has already failed');\n // Ignore error if already failed\n return;\n } else if (runnable.isPending()) {\n debug('uncaught(): pending Runnable wound up failing!');\n // report 'pending test' retrospectively as failed\n this.fail(runnable, err, true);\n return;\n }\n\n // we cannot recover gracefully if a Runnable has already passed\n // then fails asynchronously\n if (runnable.isPassed()) {\n debug('uncaught(): Runnable has already passed; bailing gracefully');\n this.fail(runnable, err);\n this.abort();\n } else {\n debug('uncaught(): forcing Runnable to complete with Error');\n return runnable.callback(err);\n }\n};\n\n/**\n * Run the root suite and invoke `fn(failures)`\n * on completion.\n *\n * @public\n * @memberof Runner\n * @param {Function} fn - Callback when finished\n * @param {Object} [opts] - For subclasses\n * @param {string[]} opts.files - Files to run\n * @param {Options} opts.options - command-line options\n * @returns {Runner} Runner instance.\n */\nRunner.prototype.run = function (fn, opts = {}) {\n var rootSuite = this.suite;\n var options = opts.options || {};\n\n debug('run(): got options: %O', options);\n fn = fn || function () {};\n\n const end = () => {\n if (!this.total && this._opts.failZero) this.failures = 1;\n\n debug('run(): root suite completed; emitting %s', constants.EVENT_RUN_END);\n this.emit(constants.EVENT_RUN_END);\n };\n\n const begin = () => {\n debug('run(): emitting %s', constants.EVENT_RUN_BEGIN);\n this.emit(constants.EVENT_RUN_BEGIN);\n debug('run(): emitted %s', constants.EVENT_RUN_BEGIN);\n\n this.runSuite(rootSuite, end);\n };\n\n const prepare = () => {\n debug('run(): starting');\n // If there is an `only` filter\n if (rootSuite.hasOnly()) {\n rootSuite.filterOnly();\n debug('run(): filtered exclusive Runnables');\n }\n this.state = constants.STATE_RUNNING;\n if (this._opts.delay) {\n this.emit(constants.EVENT_DELAY_END);\n debug('run(): \"delay\" ended');\n }\n\n return begin();\n };\n\n // references cleanup to avoid memory leaks\n if (this._opts.cleanReferencesAfterRun) {\n this.on(constants.EVENT_SUITE_END, suite => {\n suite.cleanReferences();\n });\n }\n\n // callback\n this.on(constants.EVENT_RUN_END, function () {\n this.state = constants.STATE_STOPPED;\n debug('run(): emitted %s', constants.EVENT_RUN_END);\n fn(this.failures);\n });\n\n this._removeEventListener(process, 'uncaughtException', this.uncaught);\n this._removeEventListener(process, 'unhandledRejection', this.unhandled);\n this._addEventListener(process, 'uncaughtException', this.uncaught);\n this._addEventListener(process, 'unhandledRejection', this.unhandled);\n\n if (this._opts.delay) {\n // for reporters, I guess.\n // might be nice to debounce some dots while we wait.\n this.emit(constants.EVENT_DELAY_BEGIN, rootSuite);\n rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare);\n debug('run(): waiting for green light due to --delay');\n } else {\n Runner.immediately(prepare);\n }\n\n return this;\n};\n\n/**\n * Toggle partial object linking behavior; used for building object references from\n * unique ID's. Does nothing in serial mode, because the object references already exist.\n * Subclasses can implement this (e.g., `ParallelBufferedRunner`)\n * @abstract\n * @param {boolean} [value] - If `true`, enable partial object linking, otherwise disable\n * @returns {Runner}\n * @chainable\n * @public\n * @example\n * // this reporter needs proper object references when run in parallel mode\n * class MyReporter() {\n * constructor(runner) {\n * this.runner.linkPartialObjects(true)\n * .on(EVENT_SUITE_BEGIN, suite => {\n // this Suite may be the same object...\n * })\n * .on(EVENT_TEST_BEGIN, test => {\n * // ...as the `test.parent` property\n * });\n * }\n * }\n */\nRunner.prototype.linkPartialObjects = function (value) {\n return this;\n};\n\n/*\n * Like {@link Runner#run}, but does not accept a callback and returns a `Promise` instead of a `Runner`.\n * This function cannot reject; an `unhandledRejection` event will bubble up to the `process` object instead.\n * @public\n * @memberof Runner\n * @param {Object} [opts] - Options for {@link Runner#run}\n * @returns {Promise} Failure count\n */\nRunner.prototype.runAsync = async function runAsync(opts = {}) {\n return new Promise(resolve => {\n this.run(resolve, opts);\n });\n};\n\n/**\n * Cleanly abort execution.\n *\n * @memberof Runner\n * @public\n * @return {Runner} Runner instance.\n */\nRunner.prototype.abort = function () {\n debug('abort(): aborting');\n this._abort = true;\n\n return this;\n};\n\n/**\n * Returns `true` if Mocha is running in parallel mode. For reporters.\n *\n * Subclasses should return an appropriate value.\n * @public\n * @returns {false}\n */\nRunner.prototype.isParallelMode = function isParallelMode() {\n return false;\n};\n\n/**\n * Configures an alternate reporter for worker processes to use. Subclasses\n * using worker processes should implement this.\n * @public\n * @param {string} path - Absolute path to alternate reporter for worker processes to use\n * @returns {Runner}\n * @throws When in serial mode\n * @chainable\n * @abstract\n */\nRunner.prototype.workerReporter = function () {\n throw createUnsupportedError('workerReporter() not supported in serial mode');\n};\n\n/**\n * Filter leaks with the given globals flagged as `ok`.\n *\n * @private\n * @param {Array} ok\n * @param {Array} globals\n * @return {Array}\n */\nfunction filterLeaks(ok, globals) {\n return globals.filter(function (key) {\n // Firefox and Chrome exposes iframes as index inside the window object\n if (/^\\d+/.test(key)) {\n return false;\n }\n\n // in firefox\n // if runner runs in an iframe, this iframe's window.getInterface method\n // not init at first it is assigned in some seconds\n if (global.navigator && /^getInterface/.test(key)) {\n return false;\n }\n\n // an iframe could be approached by window[iframeIndex]\n // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak\n if (global.navigator && /^\\d+/.test(key)) {\n return false;\n }\n\n // Opera and IE expose global variables for HTML element IDs (issue #243)\n if (/^mocha-/.test(key)) {\n return false;\n }\n\n var matched = ok.filter(function (ok) {\n if (~ok.indexOf('*')) {\n return key.indexOf(ok.split('*')[0]) === 0;\n }\n return key === ok;\n });\n return !matched.length && (!global.navigator || key !== 'onerror');\n });\n}\n\n/**\n * Check if argument is an instance of Error object or a duck-typed equivalent.\n *\n * @private\n * @param {Object} err - object to check\n * @param {string} err.message - error message\n * @returns {boolean}\n */\nfunction isError(err) {\n return err instanceof Error || (err && typeof err.message === 'string');\n}\n\n/**\n *\n * Converts thrown non-extensible type into proper Error.\n *\n * @private\n * @param {*} thrown - Non-extensible type thrown by code\n * @return {Error}\n */\nfunction thrown2Error(err) {\n return new Error(\n `the ${utils.canonicalType(err)} ${stringify(\n err\n )} was thrown, throw an Error :)`\n );\n}\n\nRunner.constants = constants;\n\n/**\n * Node.js' `EventEmitter`\n * @external EventEmitter\n * @see {@link https://nodejs.org/api/events.html#events_class_eventemitter}\n */\n\nmodule.exports = Runner;\n","'use strict';\n/**\n * @module Base\n */\n/**\n * Module dependencies.\n */\n\nvar diff = require('diff');\nvar milliseconds = require('ms');\nvar utils = require('../utils');\nvar supportsColor = require('supports-color');\nvar symbols = require('log-symbols');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\n\nconst isBrowser = utils.isBrowser();\n\nfunction getBrowserWindowSize() {\n if ('innerHeight' in global) {\n return [global.innerHeight, global.innerWidth];\n }\n // In a Web Worker, the DOM Window is not available.\n return [640, 480];\n}\n\n/**\n * Expose `Base`.\n */\n\nexports = module.exports = Base;\n\n/**\n * Check if both stdio streams are associated with a tty.\n */\n\nvar isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY);\n\n/**\n * Save log references to avoid tests interfering (see GH-3604).\n */\nvar consoleLog = console.log;\n\n/**\n * Enable coloring by default, except in the browser interface.\n */\n\nexports.useColors =\n !isBrowser &&\n (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);\n\n/**\n * Inline diffs instead of +/-\n */\n\nexports.inlineDiffs = false;\n\n/**\n * Truncate diffs longer than this value to avoid slow performance\n */\nexports.maxDiffSize = 8192;\n\n/**\n * Default color map.\n */\n\nexports.colors = {\n pass: 90,\n fail: 31,\n 'bright pass': 92,\n 'bright fail': 91,\n 'bright yellow': 93,\n pending: 36,\n suite: 0,\n 'error title': 0,\n 'error message': 31,\n 'error stack': 90,\n checkmark: 32,\n fast: 90,\n medium: 33,\n slow: 31,\n green: 32,\n light: 90,\n 'diff gutter': 90,\n 'diff added': 32,\n 'diff removed': 31,\n 'diff added inline': '30;42',\n 'diff removed inline': '30;41'\n};\n\n/**\n * Default symbol map.\n */\n\nexports.symbols = {\n ok: symbols.success,\n err: symbols.error,\n dot: '.',\n comma: ',',\n bang: '!'\n};\n\n/**\n * Color `str` with the given `type`,\n * allowing colors to be disabled,\n * as well as user-defined color\n * schemes.\n *\n * @private\n * @param {string} type\n * @param {string} str\n * @return {string}\n */\nvar color = (exports.color = function (type, str) {\n if (!exports.useColors) {\n return String(str);\n }\n return '\\u001b[' + exports.colors[type] + 'm' + str + '\\u001b[0m';\n});\n\n/**\n * Expose term window size, with some defaults for when stderr is not a tty.\n */\n\nexports.window = {\n width: 75\n};\n\nif (isatty) {\n if (isBrowser) {\n exports.window.width = getBrowserWindowSize()[1];\n } else {\n exports.window.width = process.stdout.getWindowSize(1)[0];\n }\n}\n\n/**\n * Expose some basic cursor interactions that are common among reporters.\n */\n\nexports.cursor = {\n hide: function () {\n isatty && process.stdout.write('\\u001b[?25l');\n },\n\n show: function () {\n isatty && process.stdout.write('\\u001b[?25h');\n },\n\n deleteLine: function () {\n isatty && process.stdout.write('\\u001b[2K');\n },\n\n beginningOfLine: function () {\n isatty && process.stdout.write('\\u001b[0G');\n },\n\n CR: function () {\n if (isatty) {\n exports.cursor.deleteLine();\n exports.cursor.beginningOfLine();\n } else {\n process.stdout.write('\\r');\n }\n }\n};\n\nvar showDiff = (exports.showDiff = function (err) {\n return (\n err &&\n err.showDiff !== false &&\n sameType(err.actual, err.expected) &&\n err.expected !== undefined\n );\n});\n\nfunction stringifyDiffObjs(err) {\n if (!utils.isString(err.actual) || !utils.isString(err.expected)) {\n err.actual = utils.stringify(err.actual);\n err.expected = utils.stringify(err.expected);\n }\n}\n\n/**\n * Returns a diff between 2 strings with coloured ANSI output.\n *\n * @description\n * The diff will be either inline or unified dependent on the value\n * of `Base.inlineDiff`.\n *\n * @param {string} actual\n * @param {string} expected\n * @return {string} Diff\n */\n\nvar generateDiff = (exports.generateDiff = function (actual, expected) {\n try {\n var maxLen = exports.maxDiffSize;\n var skipped = 0;\n if (maxLen > 0) {\n skipped = Math.max(actual.length - maxLen, expected.length - maxLen);\n actual = actual.slice(0, maxLen);\n expected = expected.slice(0, maxLen);\n }\n let result = exports.inlineDiffs\n ? inlineDiff(actual, expected)\n : unifiedDiff(actual, expected);\n if (skipped > 0) {\n result = `${result}\\n [mocha] output truncated to ${maxLen} characters, see \"maxDiffSize\" reporter-option\\n`;\n }\n return result;\n } catch (err) {\n var msg =\n '\\n ' +\n color('diff added', '+ expected') +\n ' ' +\n color('diff removed', '- actual: failed to generate Mocha diff') +\n '\\n';\n return msg;\n }\n});\n\n/**\n * Traverses err.cause and returns all stack traces\n *\n * @private\n * @param {Error} err\n * @param {Set} [seen]\n * @return {FullErrorStack}\n */\nvar getFullErrorStack = function (err, seen) {\n if (seen && seen.has(err)) {\n return { message: '', msg: '', stack: '' };\n }\n\n var message;\n\n if (typeof err.inspect === 'function') {\n message = err.inspect() + '';\n } else if (err.message && typeof err.message.toString === 'function') {\n message = err.message + '';\n } else {\n message = '';\n }\n\n var msg;\n var stack = err.stack || message;\n var index = message ? stack.indexOf(message) : -1;\n\n if (index === -1) {\n msg = message;\n } else {\n index += message.length;\n msg = stack.slice(0, index);\n // remove msg from stack\n stack = stack.slice(index + 1);\n\n if (err.cause) {\n seen = seen || new Set();\n seen.add(err);\n const causeStack = getFullErrorStack(err.cause, seen)\n stack += '\\n Caused by: ' + causeStack.msg + (causeStack.stack ? '\\n' + causeStack.stack : '');\n }\n }\n\n return {\n message,\n msg,\n stack\n };\n};\n\n/**\n * Outputs the given `failures` as a list.\n *\n * @public\n * @memberof Mocha.reporters.Base\n * @variation 1\n * @param {Object[]} failures - Each is Test instance with corresponding\n * Error property\n */\nexports.list = function (failures) {\n var multipleErr, multipleTest;\n Base.consoleLog();\n failures.forEach(function (test, i) {\n // format\n var fmt =\n color('error title', ' %s) %s:\\n') +\n color('error message', ' %s') +\n color('error stack', '\\n%s\\n');\n\n // msg\n var err;\n if (test.err && test.err.multiple) {\n if (multipleTest !== test) {\n multipleTest = test;\n multipleErr = [test.err].concat(test.err.multiple);\n }\n err = multipleErr.shift();\n } else {\n err = test.err;\n }\n\n var { message, msg, stack } = getFullErrorStack(err);\n\n // uncaught\n if (err.uncaught) {\n msg = 'Uncaught ' + msg;\n }\n // explicitly show diff\n if (!exports.hideDiff && showDiff(err)) {\n stringifyDiffObjs(err);\n fmt =\n color('error title', ' %s) %s:\\n%s') + color('error stack', '\\n%s\\n');\n var match = message.match(/^([^:]+): expected/);\n msg = '\\n ' + color('error message', match ? match[1] : msg);\n\n msg += generateDiff(err.actual, err.expected);\n }\n\n // indent stack trace\n stack = stack.replace(/^/gm, ' ');\n\n // indented test title\n var testTitle = '';\n test.titlePath().forEach(function (str, index) {\n if (index !== 0) {\n testTitle += '\\n ';\n }\n for (var i = 0; i < index; i++) {\n testTitle += ' ';\n }\n testTitle += str;\n });\n\n Base.consoleLog(fmt, i + 1, testTitle, msg, stack);\n });\n};\n\n/**\n * Constructs a new `Base` reporter instance.\n *\n * @description\n * All other reporters generally inherit from this reporter.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Base(runner, options) {\n var failures = (this.failures = []);\n\n if (!runner) {\n throw new TypeError('Missing runner argument');\n }\n this.options = options || {};\n this.runner = runner;\n this.stats = runner.stats; // assigned so Reporters keep a closer reference\n\n var maxDiffSizeOpt =\n this.options.reporterOption && this.options.reporterOption.maxDiffSize;\n if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) {\n exports.maxDiffSize = Number(maxDiffSizeOpt);\n }\n\n runner.on(EVENT_TEST_PASS, function (test) {\n if (test.duration > test.slow()) {\n test.speed = 'slow';\n } else if (test.duration > test.slow() / 2) {\n test.speed = 'medium';\n } else {\n test.speed = 'fast';\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function (test, err) {\n if (showDiff(err)) {\n stringifyDiffObjs(err);\n }\n // more than one error per test\n if (test.err && err instanceof Error) {\n test.err.multiple = (test.err.multiple || []).concat(err);\n } else {\n test.err = err;\n }\n failures.push(test);\n });\n}\n\n/**\n * Outputs common epilogue used by many of the bundled reporters.\n *\n * @public\n * @memberof Mocha.reporters\n */\nBase.prototype.epilogue = function () {\n var stats = this.stats;\n var fmt;\n\n Base.consoleLog();\n\n // passes\n fmt =\n color('bright pass', ' ') +\n color('green', ' %d passing') +\n color('light', ' (%s)');\n\n Base.consoleLog(fmt, stats.passes || 0, milliseconds(stats.duration));\n\n // pending\n if (stats.pending) {\n fmt = color('pending', ' ') + color('pending', ' %d pending');\n\n Base.consoleLog(fmt, stats.pending);\n }\n\n // failures\n if (stats.failures) {\n fmt = color('fail', ' %d failing');\n\n Base.consoleLog(fmt, stats.failures);\n\n Base.list(this.failures);\n Base.consoleLog();\n }\n\n Base.consoleLog();\n};\n\n/**\n * Pads the given `str` to `len`.\n *\n * @private\n * @param {string} str\n * @param {string} len\n * @return {string}\n */\nfunction pad(str, len) {\n str = String(str);\n return Array(len - str.length + 1).join(' ') + str;\n}\n\n/**\n * Returns inline diff between 2 strings with coloured ANSI output.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} Diff\n */\nfunction inlineDiff(actual, expected) {\n var msg = errorDiff(actual, expected);\n\n // linenos\n var lines = msg.split('\\n');\n if (lines.length > 4) {\n var width = String(lines.length).length;\n msg = lines\n .map(function (str, i) {\n return pad(++i, width) + ' |' + ' ' + str;\n })\n .join('\\n');\n }\n\n // legend\n msg =\n '\\n' +\n color('diff removed inline', 'actual') +\n ' ' +\n color('diff added inline', 'expected') +\n '\\n\\n' +\n msg +\n '\\n';\n\n // indent\n msg = msg.replace(/^/gm, ' ');\n return msg;\n}\n\n/**\n * Returns unified diff between two strings with coloured ANSI output.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} The diff.\n */\nfunction unifiedDiff(actual, expected) {\n var indent = ' ';\n function cleanUp(line) {\n if (line[0] === '+') {\n return indent + colorLines('diff added', line);\n }\n if (line[0] === '-') {\n return indent + colorLines('diff removed', line);\n }\n if (line.match(/@@/)) {\n return '--';\n }\n if (line.match(/\\\\ No newline/)) {\n return null;\n }\n return indent + line;\n }\n function notBlank(line) {\n return typeof line !== 'undefined' && line !== null;\n }\n var msg = diff.createPatch('string', actual, expected);\n var lines = msg.split('\\n').splice(5);\n return (\n '\\n ' +\n colorLines('diff added', '+ expected') +\n ' ' +\n colorLines('diff removed', '- actual') +\n '\\n\\n' +\n lines.map(cleanUp).filter(notBlank).join('\\n')\n );\n}\n\n/**\n * Returns character diff for `err`.\n *\n * @private\n * @param {String} actual\n * @param {String} expected\n * @return {string} the diff\n */\nfunction errorDiff(actual, expected) {\n return diff\n .diffWordsWithSpace(actual, expected)\n .map(function (str) {\n if (str.added) {\n return colorLines('diff added inline', str.value);\n }\n if (str.removed) {\n return colorLines('diff removed inline', str.value);\n }\n return str.value;\n })\n .join('');\n}\n\n/**\n * Colors lines for `str`, using the color `name`.\n *\n * @private\n * @param {string} name\n * @param {string} str\n * @return {string}\n */\nfunction colorLines(name, str) {\n return str\n .split('\\n')\n .map(function (str) {\n return color(name, str);\n })\n .join('\\n');\n}\n\n/**\n * Object#toString reference.\n */\nvar objToString = Object.prototype.toString;\n\n/**\n * Checks that a / b have the same type.\n *\n * @private\n * @param {Object} a\n * @param {Object} b\n * @return {boolean}\n */\nfunction sameType(a, b) {\n return objToString.call(a) === objToString.call(b);\n}\n\nBase.consoleLog = consoleLog;\n\nBase.abstract = true;\n\n/**\n * An object with all stack traces recursively mounted from each err.cause\n * @memberof module:lib/reporters/base\n * @typedef {Object} FullErrorStack\n * @property {string} message\n * @property {string} msg\n * @property {string} stack\n */\n","'use strict';\n/**\n * @module Dot\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\n\n/**\n * Expose `Dot`.\n */\n\nexports = module.exports = Dot;\n\n/**\n * Constructs a new `Dot` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Dot(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var n = -1;\n\n runner.on(EVENT_RUN_BEGIN, function () {\n process.stdout.write('\\n');\n });\n\n runner.on(EVENT_TEST_PENDING, function () {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n process.stdout.write(Base.color('pending', Base.symbols.comma));\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n if (test.speed === 'slow') {\n process.stdout.write(Base.color('bright yellow', Base.symbols.dot));\n } else {\n process.stdout.write(Base.color(test.speed, Base.symbols.dot));\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function () {\n if (++n % width === 0) {\n process.stdout.write('\\n ');\n }\n process.stdout.write(Base.color('fail', Base.symbols.bang));\n });\n\n runner.once(EVENT_RUN_END, function () {\n process.stdout.write('\\n');\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Dot, Base);\n\nDot.description = 'dot matrix representation';\n","'use strict';\n/**\n * @module Doc\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\n\n/**\n * Expose `Doc`.\n */\n\nexports = module.exports = Doc;\n\n/**\n * Constructs a new `Doc` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Doc(runner, options) {\n Base.call(this, runner, options);\n\n var indents = 2;\n\n function indent() {\n return Array(indents).join(' ');\n }\n\n runner.on(EVENT_SUITE_BEGIN, function (suite) {\n if (suite.root) {\n return;\n }\n ++indents;\n Base.consoleLog('%s
          ', indent());\n ++indents;\n Base.consoleLog('%s

          %s

          ', indent(), utils.escape(suite.title));\n Base.consoleLog('%s
          ', indent());\n });\n\n runner.on(EVENT_SUITE_END, function (suite) {\n if (suite.root) {\n return;\n }\n Base.consoleLog('%s
          ', indent());\n --indents;\n Base.consoleLog('%s
          ', indent());\n --indents;\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n Base.consoleLog('%s
          %s
          ', indent(), utils.escape(test.title));\n Base.consoleLog('%s
          %s
          ', indent(), utils.escape(test.file));\n var code = utils.escape(utils.clean(test.body));\n Base.consoleLog('%s
          %s
          ', indent(), code);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test, err) {\n Base.consoleLog(\n '%s
          %s
          ',\n indent(),\n utils.escape(test.title)\n );\n Base.consoleLog(\n '%s
          %s
          ',\n indent(),\n utils.escape(test.file)\n );\n var code = utils.escape(utils.clean(test.body));\n Base.consoleLog(\n '%s
          %s
          ',\n indent(),\n code\n );\n Base.consoleLog(\n '%s
          %s
          ',\n indent(),\n utils.escape(err)\n );\n });\n}\n\nDoc.description = 'HTML documentation';\n","'use strict';\n/**\n * @module TAP\n */\n/**\n * Module dependencies.\n */\n\nvar util = require('util');\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar inherits = require('../utils').inherits;\nvar sprintf = util.format;\n\n/**\n * Expose `TAP`.\n */\n\nexports = module.exports = TAP;\n\n/**\n * Constructs a new `TAP` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction TAP(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var n = 1;\n\n var tapVersion = '12';\n if (options && options.reporterOptions) {\n if (options.reporterOptions.tapVersion) {\n tapVersion = options.reporterOptions.tapVersion.toString();\n }\n }\n\n this._producer = createProducer(tapVersion);\n\n runner.once(EVENT_RUN_BEGIN, function () {\n self._producer.writeVersion();\n });\n\n runner.on(EVENT_TEST_END, function () {\n ++n;\n });\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n self._producer.writePending(n, test);\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n self._producer.writePass(n, test);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test, err) {\n self._producer.writeFail(n, test, err);\n });\n\n runner.once(EVENT_RUN_END, function () {\n self._producer.writeEpilogue(runner.stats);\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(TAP, Base);\n\n/**\n * Returns a TAP-safe title of `test`.\n *\n * @private\n * @param {Test} test - Test instance.\n * @return {String} title with any hash character removed\n */\nfunction title(test) {\n return test.fullTitle().replace(/#/g, '');\n}\n\n/**\n * Writes newline-terminated formatted string to reporter output stream.\n *\n * @private\n * @param {string} format - `printf`-like format string\n * @param {...*} [varArgs] - Format string arguments\n */\nfunction println(format, varArgs) {\n var vargs = Array.from(arguments);\n vargs[0] += '\\n';\n process.stdout.write(sprintf.apply(null, vargs));\n}\n\n/**\n * Returns a `tapVersion`-appropriate TAP producer instance, if possible.\n *\n * @private\n * @param {string} tapVersion - Version of TAP specification to produce.\n * @returns {TAPProducer} specification-appropriate instance\n * @throws {Error} if specification version has no associated producer.\n */\nfunction createProducer(tapVersion) {\n var producers = {\n 12: new TAP12Producer(),\n 13: new TAP13Producer()\n };\n var producer = producers[tapVersion];\n\n if (!producer) {\n throw new Error(\n 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)\n );\n }\n\n return producer;\n}\n\n/**\n * @summary\n * Constructs a new TAPProducer.\n *\n * @description\n * Only to be used as an abstract base class.\n *\n * @private\n * @constructor\n */\nfunction TAPProducer() {}\n\n/**\n * Writes the TAP version to reporter output stream.\n *\n * @abstract\n */\nTAPProducer.prototype.writeVersion = function () {};\n\n/**\n * Writes the plan to reporter output stream.\n *\n * @abstract\n * @param {number} ntests - Number of tests that are planned to run.\n */\nTAPProducer.prototype.writePlan = function (ntests) {\n println('%d..%d', 1, ntests);\n};\n\n/**\n * Writes that test passed to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that passed.\n * @param {Test} test - Instance containing test information.\n */\nTAPProducer.prototype.writePass = function (n, test) {\n println('ok %d %s', n, title(test));\n};\n\n/**\n * Writes that test was skipped to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that was skipped.\n * @param {Test} test - Instance containing test information.\n */\nTAPProducer.prototype.writePending = function (n, test) {\n println('ok %d %s # SKIP -', n, title(test));\n};\n\n/**\n * Writes that test failed to reporter output stream.\n *\n * @abstract\n * @param {number} n - Index of test that failed.\n * @param {Test} test - Instance containing test information.\n * @param {Error} err - Reason the test failed.\n */\nTAPProducer.prototype.writeFail = function (n, test, err) {\n println('not ok %d %s', n, title(test));\n};\n\n/**\n * Writes the summary epilogue to reporter output stream.\n *\n * @abstract\n * @param {Object} stats - Object containing run statistics.\n */\nTAPProducer.prototype.writeEpilogue = function (stats) {\n // :TBD: Why is this not counting pending tests?\n println('# tests ' + (stats.passes + stats.failures));\n println('# pass ' + stats.passes);\n // :TBD: Why are we not showing pending results?\n println('# fail ' + stats.failures);\n this.writePlan(stats.passes + stats.failures + stats.pending);\n};\n\n/**\n * @summary\n * Constructs a new TAP12Producer.\n *\n * @description\n * Produces output conforming to the TAP12 specification.\n *\n * @private\n * @constructor\n * @extends TAPProducer\n * @see {@link https://testanything.org/tap-specification.html|Specification}\n */\nfunction TAP12Producer() {\n /**\n * Writes that test failed to reporter output stream, with error formatting.\n * @override\n */\n this.writeFail = function (n, test, err) {\n TAPProducer.prototype.writeFail.call(this, n, test, err);\n if (err.message) {\n println(err.message.replace(/^/gm, ' '));\n }\n if (err.stack) {\n println(err.stack.replace(/^/gm, ' '));\n }\n };\n}\n\n/**\n * Inherit from `TAPProducer.prototype`.\n */\ninherits(TAP12Producer, TAPProducer);\n\n/**\n * @summary\n * Constructs a new TAP13Producer.\n *\n * @description\n * Produces output conforming to the TAP13 specification.\n *\n * @private\n * @constructor\n * @extends TAPProducer\n * @see {@link https://testanything.org/tap-version-13-specification.html|Specification}\n */\nfunction TAP13Producer() {\n /**\n * Writes the TAP version to reporter output stream.\n * @override\n */\n this.writeVersion = function () {\n println('TAP version 13');\n };\n\n /**\n * Writes that test failed to reporter output stream, with error formatting.\n * @override\n */\n this.writeFail = function (n, test, err) {\n TAPProducer.prototype.writeFail.call(this, n, test, err);\n var emitYamlBlock = err.message != null || err.stack != null;\n if (emitYamlBlock) {\n println(indent(1) + '---');\n if (err.message) {\n println(indent(2) + 'message: |-');\n println(err.message.replace(/^/gm, indent(3)));\n }\n if (err.stack) {\n println(indent(2) + 'stack: |-');\n println(err.stack.replace(/^/gm, indent(3)));\n }\n println(indent(1) + '...');\n }\n };\n\n function indent(level) {\n return Array(level + 1).join(' ');\n }\n}\n\n/**\n * Inherit from `TAPProducer.prototype`.\n */\ninherits(TAP13Producer, TAPProducer);\n\nTAP.description = 'TAP-compatible output';\n","'use strict';\n/**\n * @module JSON\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar fs = require('fs');\nvar path = require('path');\nconst createUnsupportedError = require('../errors').createUnsupportedError;\nconst utils = require('../utils');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\n\n/**\n * Expose `JSON`.\n */\n\nexports = module.exports = JSONReporter;\n\n/**\n * Constructs a new `JSON` reporter instance.\n *\n * @public\n * @class JSON\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction JSONReporter(runner, options = {}) {\n Base.call(this, runner, options);\n\n var self = this;\n var tests = [];\n var pending = [];\n var failures = [];\n var passes = [];\n var output;\n\n if (options.reporterOption && options.reporterOption.output) {\n if (utils.isBrowser()) {\n throw createUnsupportedError('file output not supported in browser');\n }\n output = options.reporterOption.output;\n }\n\n runner.on(EVENT_TEST_END, function (test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n passes.push(test);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test) {\n failures.push(test);\n });\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n pending.push(test);\n });\n\n runner.once(EVENT_RUN_END, function () {\n var obj = {\n stats: self.stats,\n tests: tests.map(clean),\n pending: pending.map(clean),\n failures: failures.map(clean),\n passes: passes.map(clean)\n };\n\n runner.testResults = obj;\n\n var json = JSON.stringify(obj, null, 2);\n if (output) {\n try {\n fs.mkdirSync(path.dirname(output), {recursive: true});\n fs.writeFileSync(output, json);\n } catch (err) {\n console.error(\n `${Base.symbols.err} [mocha] writing output to \"${output}\" failed: ${err.message}\\n`\n );\n process.stdout.write(json);\n }\n } else {\n process.stdout.write(json);\n }\n });\n}\n\n/**\n * Return a plain-object representation of `test`\n * free of cyclic properties etc.\n *\n * @private\n * @param {Object} test\n * @return {Object}\n */\nfunction clean(test) {\n var err = test.err || {};\n if (err instanceof Error) {\n err = errorJSON(err);\n }\n\n return {\n title: test.title,\n fullTitle: test.fullTitle(),\n file: test.file,\n duration: test.duration,\n currentRetry: test.currentRetry(),\n speed: test.speed,\n err: cleanCycles(err)\n };\n}\n\n/**\n * Replaces any circular references inside `obj` with '[object Object]'\n *\n * @private\n * @param {Object} obj\n * @return {Object}\n */\nfunction cleanCycles(obj) {\n var cache = [];\n return JSON.parse(\n JSON.stringify(obj, function (key, value) {\n if (typeof value === 'object' && value !== null) {\n if (cache.indexOf(value) !== -1) {\n // Instead of going in a circle, we'll print [object Object]\n return '' + value;\n }\n cache.push(value);\n }\n\n return value;\n })\n );\n}\n\n/**\n * Transform an Error object into a JSON object.\n *\n * @private\n * @param {Error} err\n * @return {Object}\n */\nfunction errorJSON(err) {\n var res = {};\n Object.getOwnPropertyNames(err).forEach(function (key) {\n res[key] = err[key];\n }, err);\n return res;\n}\n\nJSONReporter.description = 'single JSON object';\n","'use strict';\n\n/**\n @module browser/Progress\n*/\n\n/**\n * Expose `Progress`.\n */\n\nmodule.exports = Progress;\n\n/**\n * Initialize a new `Progress` indicator.\n */\nfunction Progress() {\n this.percent = 0;\n this.size(0);\n this.fontSize(11);\n this.font('helvetica, arial, sans-serif');\n}\n\n/**\n * Set progress size to `size`.\n *\n * @public\n * @param {number} size\n * @return {Progress} Progress instance.\n */\nProgress.prototype.size = function (size) {\n this._size = size;\n return this;\n};\n\n/**\n * Set text to `text`.\n *\n * @public\n * @param {string} text\n * @return {Progress} Progress instance.\n */\nProgress.prototype.text = function (text) {\n this._text = text;\n return this;\n};\n\n/**\n * Set font size to `size`.\n *\n * @public\n * @param {number} size\n * @return {Progress} Progress instance.\n */\nProgress.prototype.fontSize = function (size) {\n this._fontSize = size;\n return this;\n};\n\n/**\n * Set font to `family`.\n *\n * @param {string} family\n * @return {Progress} Progress instance.\n */\nProgress.prototype.font = function (family) {\n this._font = family;\n return this;\n};\n\n/**\n * Update percentage to `n`.\n *\n * @param {number} n\n * @return {Progress} Progress instance.\n */\nProgress.prototype.update = function (n) {\n this.percent = n;\n return this;\n};\n\n/**\n * Draw on `ctx`.\n *\n * @param {CanvasRenderingContext2d} ctx\n * @return {Progress} Progress instance.\n */\nProgress.prototype.draw = function (ctx) {\n try {\n var darkMatcher = window.matchMedia('(prefers-color-scheme: dark)');\n var isDarkMode = !!darkMatcher.matches;\n var lightColors = {\n outerCircle: '#9f9f9f',\n innerCircle: '#eee',\n text: '#000'\n };\n var darkColors = {\n outerCircle: '#888',\n innerCircle: '#444',\n text: '#fff'\n };\n var colors = isDarkMode ? darkColors : lightColors;\n\n var percent = Math.min(this.percent, 100);\n var size = this._size;\n var half = size / 2;\n var x = half;\n var y = half;\n var rad = half - 1;\n var fontSize = this._fontSize;\n\n ctx.font = fontSize + 'px ' + this._font;\n\n var angle = Math.PI * 2 * (percent / 100);\n ctx.clearRect(0, 0, size, size);\n\n // outer circle\n ctx.strokeStyle = colors.outerCircle;\n ctx.beginPath();\n ctx.arc(x, y, rad, 0, angle, false);\n ctx.stroke();\n\n // inner circle\n ctx.strokeStyle = colors.innerCircle;\n ctx.beginPath();\n ctx.arc(x, y, rad - 1, 0, angle, true);\n ctx.stroke();\n\n // text\n var text = this._text || (percent | 0) + '%';\n var w = ctx.measureText(text).width;\n\n ctx.fillStyle = colors.text;\n ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);\n } catch (ignore) {\n // don't fail if we can't render progress\n }\n return this;\n};\n","'use strict';\n\n/* eslint-env browser */\n/**\n * @module HTML\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar Progress = require('../browser/progress');\nvar escapeRe = require('escape-string-regexp');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar escape = utils.escape;\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\n\nvar Date = global.Date;\n\n/**\n * Expose `HTML`.\n */\n\nexports = module.exports = HTML;\n\n/**\n * Stats template.\n */\n\nvar statsTemplate =\n '';\n\nvar playIcon = '‣';\n\n/**\n * Constructs a new `HTML` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction HTML(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var stats = this.stats;\n var stat = fragment(statsTemplate);\n var items = stat.getElementsByTagName('li');\n var passes = items[1].getElementsByTagName('em')[0];\n var passesLink = items[1].getElementsByTagName('a')[0];\n var failures = items[2].getElementsByTagName('em')[0];\n var failuresLink = items[2].getElementsByTagName('a')[0];\n var duration = items[3].getElementsByTagName('em')[0];\n var canvas = stat.getElementsByTagName('canvas')[0];\n var report = fragment('
            ');\n var stack = [report];\n var progress;\n var ctx;\n var root = document.getElementById('mocha');\n\n if (canvas.getContext) {\n var ratio = window.devicePixelRatio || 1;\n canvas.style.width = canvas.width;\n canvas.style.height = canvas.height;\n canvas.width *= ratio;\n canvas.height *= ratio;\n ctx = canvas.getContext('2d');\n ctx.scale(ratio, ratio);\n progress = new Progress();\n }\n\n if (!root) {\n return error('#mocha div missing, add it to your document');\n }\n\n // pass toggle\n on(passesLink, 'click', function (evt) {\n evt.preventDefault();\n unhide();\n var name = /pass/.test(report.className) ? '' : ' pass';\n report.className = report.className.replace(/fail|pass/g, '') + name;\n if (report.className.trim()) {\n hideSuitesWithout('test pass');\n }\n });\n\n // failure toggle\n on(failuresLink, 'click', function (evt) {\n evt.preventDefault();\n unhide();\n var name = /fail/.test(report.className) ? '' : ' fail';\n report.className = report.className.replace(/fail|pass/g, '') + name;\n if (report.className.trim()) {\n hideSuitesWithout('test fail');\n }\n });\n\n root.appendChild(stat);\n root.appendChild(report);\n\n if (progress) {\n progress.size(40);\n }\n\n runner.on(EVENT_SUITE_BEGIN, function (suite) {\n if (suite.root) {\n return;\n }\n\n // suite\n var url = self.suiteURL(suite);\n var el = fragment(\n '
          • %s

          • ',\n url,\n escape(suite.title)\n );\n\n // container\n stack[0].appendChild(el);\n stack.unshift(document.createElement('ul'));\n el.appendChild(stack[0]);\n });\n\n runner.on(EVENT_SUITE_END, function (suite) {\n if (suite.root) {\n updateStats();\n return;\n }\n stack.shift();\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n var url = self.testURL(test);\n var markup =\n '
          • %e%ems ' +\n '' +\n playIcon +\n '

          • ';\n var el = fragment(markup, test.speed, test.title, test.duration, url);\n self.addCodeToggle(el, test.body);\n appendToStack(el);\n updateStats();\n });\n\n runner.on(EVENT_TEST_FAIL, function (test) {\n var el = fragment(\n '
          • %e ' +\n playIcon +\n '

          • ',\n test.title,\n self.testURL(test)\n );\n var stackString; // Note: Includes leading newline\n var message = test.err.toString();\n\n // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we\n // check for the result of the stringifying.\n if (message === '[object Error]') {\n message = test.err.message;\n }\n\n if (test.err.stack) {\n var indexOfMessage = test.err.stack.indexOf(test.err.message);\n if (indexOfMessage === -1) {\n stackString = test.err.stack;\n } else {\n stackString = test.err.stack.slice(\n test.err.message.length + indexOfMessage\n );\n }\n } else if (test.err.sourceURL && test.err.line !== undefined) {\n // Safari doesn't give you a stack. Let's at least provide a source line.\n stackString = '\\n(' + test.err.sourceURL + ':' + test.err.line + ')';\n }\n\n stackString = stackString || '';\n\n if (test.err.htmlMessage && stackString) {\n el.appendChild(\n fragment(\n '
            %s\\n
            %e
            ',\n test.err.htmlMessage,\n stackString\n )\n );\n } else if (test.err.htmlMessage) {\n el.appendChild(\n fragment('
            %s
            ', test.err.htmlMessage)\n );\n } else {\n el.appendChild(\n fragment('
            %e%e
            ', message, stackString)\n );\n }\n\n self.addCodeToggle(el, test.body);\n appendToStack(el);\n updateStats();\n });\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n var el = fragment(\n '
          • %e

          • ',\n test.title\n );\n appendToStack(el);\n updateStats();\n });\n\n function appendToStack(el) {\n // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.\n if (stack[0]) {\n stack[0].appendChild(el);\n }\n }\n\n function updateStats() {\n // TODO: add to stats\n var percent = ((stats.tests / runner.total) * 100) | 0;\n if (progress) {\n progress.update(percent).draw(ctx);\n }\n\n // update stats\n var ms = new Date() - stats.start;\n text(passes, stats.passes);\n text(failures, stats.failures);\n text(duration, (ms / 1000).toFixed(2));\n }\n}\n\n/**\n * Makes a URL, preserving querystring (\"search\") parameters.\n *\n * @param {string} s\n * @return {string} A new URL.\n */\nfunction makeUrl(s) {\n var search = window.location.search;\n\n // Remove previous grep query parameter if present\n if (search) {\n search = search.replace(/[?&]grep=[^&\\s]*/g, '').replace(/^&/, '?');\n }\n\n return (\n window.location.pathname +\n (search ? search + '&' : '?') +\n 'grep=' +\n encodeURIComponent(escapeRe(s))\n );\n}\n\n/**\n * Provide suite URL.\n *\n * @param {Object} [suite]\n */\nHTML.prototype.suiteURL = function (suite) {\n return makeUrl(suite.fullTitle());\n};\n\n/**\n * Provide test URL.\n *\n * @param {Object} [test]\n */\nHTML.prototype.testURL = function (test) {\n return makeUrl(test.fullTitle());\n};\n\n/**\n * Adds code toggle functionality for the provided test's list element.\n *\n * @param {HTMLLIElement} el\n * @param {string} contents\n */\nHTML.prototype.addCodeToggle = function (el, contents) {\n var h2 = el.getElementsByTagName('h2')[0];\n\n on(h2, 'click', function () {\n pre.style.display = pre.style.display === 'none' ? 'block' : 'none';\n });\n\n var pre = fragment('
            %e
            ', utils.clean(contents));\n el.appendChild(pre);\n pre.style.display = 'none';\n};\n\n/**\n * Display error `msg`.\n *\n * @param {string} msg\n */\nfunction error(msg) {\n document.body.appendChild(fragment('
            %s
            ', msg));\n}\n\n/**\n * Return a DOM fragment from `html`.\n *\n * @param {string} html\n */\nfunction fragment(html) {\n var args = arguments;\n var div = document.createElement('div');\n var i = 1;\n\n div.innerHTML = html.replace(/%([se])/g, function (_, type) {\n switch (type) {\n case 's':\n return String(args[i++]);\n case 'e':\n return escape(args[i++]);\n // no default\n }\n });\n\n return div.firstChild;\n}\n\n/**\n * Check for suites that do not have elements\n * with `classname`, and hide them.\n *\n * @param {text} classname\n */\nfunction hideSuitesWithout(classname) {\n var suites = document.getElementsByClassName('suite');\n for (var i = 0; i < suites.length; i++) {\n var els = suites[i].getElementsByClassName(classname);\n if (!els.length) {\n suites[i].className += ' hidden';\n }\n }\n}\n\n/**\n * Unhide .hidden suites.\n */\nfunction unhide() {\n var els = document.getElementsByClassName('suite hidden');\n while (els.length > 0) {\n els[0].className = els[0].className.replace('suite hidden', 'suite');\n }\n}\n\n/**\n * Set an element's text contents.\n *\n * @param {HTMLElement} el\n * @param {string} contents\n */\nfunction text(el, contents) {\n if (el.textContent) {\n el.textContent = contents;\n } else {\n el.innerText = contents;\n }\n}\n\n/**\n * Listen on `event` with callback `fn`.\n */\nfunction on(el, event, fn) {\n if (el.addEventListener) {\n el.addEventListener(event, fn, false);\n } else {\n el.attachEvent('on' + event, fn);\n }\n}\n\nHTML.browserOnly = true;\n","'use strict';\n/**\n * @module List\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar color = Base.color;\nvar cursor = Base.cursor;\n\n/**\n * Expose `List`.\n */\n\nexports = module.exports = List;\n\n/**\n * Constructs a new `List` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction List(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var n = 0;\n\n runner.on(EVENT_RUN_BEGIN, function () {\n Base.consoleLog();\n });\n\n runner.on(EVENT_TEST_BEGIN, function (test) {\n process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));\n });\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n var fmt = color('checkmark', ' -') + color('pending', ' %s');\n Base.consoleLog(fmt, test.fullTitle());\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n var fmt =\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s: ') +\n color(test.speed, '%dms');\n cursor.CR();\n Base.consoleLog(fmt, test.fullTitle(), test.duration);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test) {\n cursor.CR();\n Base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle());\n });\n\n runner.once(EVENT_RUN_END, self.epilogue.bind(self));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(List, Base);\n\nList.description = 'like \"spec\" reporter but flat';\n","'use strict';\n/**\n * @module Min\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\n\n/**\n * Expose `Min`.\n */\n\nexports = module.exports = Min;\n\n/**\n * Constructs a new `Min` reporter instance.\n *\n * @description\n * This minimal test reporter is best used with '--watch'.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Min(runner, options) {\n Base.call(this, runner, options);\n\n runner.on(EVENT_RUN_BEGIN, function () {\n // clear screen\n process.stdout.write('\\u001b[2J');\n // set cursor position\n process.stdout.write('\\u001b[1;3H');\n });\n\n runner.once(EVENT_RUN_END, this.epilogue.bind(this));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Min, Base);\n\nMin.description = 'essentially just a summary';\n","'use strict';\n/**\n * @module Spec\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_SUITE_END = constants.EVENT_SUITE_END;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar inherits = require('../utils').inherits;\nvar color = Base.color;\n\n/**\n * Expose `Spec`.\n */\n\nexports = module.exports = Spec;\n\n/**\n * Constructs a new `Spec` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Spec(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var indents = 0;\n var n = 0;\n\n function indent() {\n return Array(indents).join(' ');\n }\n\n runner.on(EVENT_RUN_BEGIN, function () {\n Base.consoleLog();\n });\n\n runner.on(EVENT_SUITE_BEGIN, function (suite) {\n ++indents;\n Base.consoleLog(color('suite', '%s%s'), indent(), suite.title);\n });\n\n runner.on(EVENT_SUITE_END, function () {\n --indents;\n if (indents === 1) {\n Base.consoleLog();\n }\n });\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n var fmt = indent() + color('pending', ' - %s');\n Base.consoleLog(fmt, test.title);\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n var fmt;\n if (test.speed === 'fast') {\n fmt =\n indent() +\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s');\n Base.consoleLog(fmt, test.title);\n } else {\n fmt =\n indent() +\n color('checkmark', ' ' + Base.symbols.ok) +\n color('pass', ' %s') +\n color(test.speed, ' (%dms)');\n Base.consoleLog(fmt, test.title, test.duration);\n }\n });\n\n runner.on(EVENT_TEST_FAIL, function (test) {\n Base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title);\n });\n\n runner.once(EVENT_RUN_END, self.epilogue.bind(self));\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Spec, Base);\n\nSpec.description = 'hierarchical & verbose [default]';\n","'use strict';\n/**\n * @module Nyan\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar inherits = require('../utils').inherits;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\n\n/**\n * Expose `Dot`.\n */\n\nexports = module.exports = NyanCat;\n\n/**\n * Constructs a new `Nyan` reporter instance.\n *\n * @public\n * @class Nyan\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction NyanCat(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var nyanCatWidth = (this.nyanCatWidth = 11);\n\n this.colorIndex = 0;\n this.numberOfLines = 4;\n this.rainbowColors = self.generateColors();\n this.scoreboardWidth = 5;\n this.tick = 0;\n this.trajectories = [[], [], [], []];\n this.trajectoryWidthMax = width - nyanCatWidth;\n\n runner.on(EVENT_RUN_BEGIN, function () {\n Base.cursor.hide();\n self.draw();\n });\n\n runner.on(EVENT_TEST_PENDING, function () {\n self.draw();\n });\n\n runner.on(EVENT_TEST_PASS, function () {\n self.draw();\n });\n\n runner.on(EVENT_TEST_FAIL, function () {\n self.draw();\n });\n\n runner.once(EVENT_RUN_END, function () {\n Base.cursor.show();\n for (var i = 0; i < self.numberOfLines; i++) {\n process.stdout.write('\\n');\n }\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(NyanCat, Base);\n\n/**\n * Draw the nyan cat\n *\n * @private\n */\n\nNyanCat.prototype.draw = function () {\n this.appendRainbow();\n this.drawScoreboard();\n this.drawRainbow();\n this.drawNyanCat();\n this.tick = !this.tick;\n};\n\n/**\n * Draw the \"scoreboard\" showing the number\n * of passes, failures and pending tests.\n *\n * @private\n */\n\nNyanCat.prototype.drawScoreboard = function () {\n var stats = this.stats;\n\n function draw(type, n) {\n process.stdout.write(' ');\n process.stdout.write(Base.color(type, n));\n process.stdout.write('\\n');\n }\n\n draw('green', stats.passes);\n draw('fail', stats.failures);\n draw('pending', stats.pending);\n process.stdout.write('\\n');\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Append the rainbow.\n *\n * @private\n */\n\nNyanCat.prototype.appendRainbow = function () {\n var segment = this.tick ? '_' : '-';\n var rainbowified = this.rainbowify(segment);\n\n for (var index = 0; index < this.numberOfLines; index++) {\n var trajectory = this.trajectories[index];\n if (trajectory.length >= this.trajectoryWidthMax) {\n trajectory.shift();\n }\n trajectory.push(rainbowified);\n }\n};\n\n/**\n * Draw the rainbow.\n *\n * @private\n */\n\nNyanCat.prototype.drawRainbow = function () {\n var self = this;\n\n this.trajectories.forEach(function (line) {\n process.stdout.write('\\u001b[' + self.scoreboardWidth + 'C');\n process.stdout.write(line.join(''));\n process.stdout.write('\\n');\n });\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Draw the nyan cat\n *\n * @private\n */\nNyanCat.prototype.drawNyanCat = function () {\n var self = this;\n var startWidth = this.scoreboardWidth + this.trajectories[0].length;\n var dist = '\\u001b[' + startWidth + 'C';\n var padding = '';\n\n process.stdout.write(dist);\n process.stdout.write('_,------,');\n process.stdout.write('\\n');\n\n process.stdout.write(dist);\n padding = self.tick ? ' ' : ' ';\n process.stdout.write('_|' + padding + '/\\\\_/\\\\ ');\n process.stdout.write('\\n');\n\n process.stdout.write(dist);\n padding = self.tick ? '_' : '__';\n var tail = self.tick ? '~' : '^';\n process.stdout.write(tail + '|' + padding + this.face() + ' ');\n process.stdout.write('\\n');\n\n process.stdout.write(dist);\n padding = self.tick ? ' ' : ' ';\n process.stdout.write(padding + '\"\" \"\" ');\n process.stdout.write('\\n');\n\n this.cursorUp(this.numberOfLines);\n};\n\n/**\n * Draw nyan cat face.\n *\n * @private\n * @return {string}\n */\n\nNyanCat.prototype.face = function () {\n var stats = this.stats;\n if (stats.failures) {\n return '( x .x)';\n } else if (stats.pending) {\n return '( o .o)';\n } else if (stats.passes) {\n return '( ^ .^)';\n }\n return '( - .-)';\n};\n\n/**\n * Move cursor up `n`.\n *\n * @private\n * @param {number} n\n */\n\nNyanCat.prototype.cursorUp = function (n) {\n process.stdout.write('\\u001b[' + n + 'A');\n};\n\n/**\n * Move cursor down `n`.\n *\n * @private\n * @param {number} n\n */\n\nNyanCat.prototype.cursorDown = function (n) {\n process.stdout.write('\\u001b[' + n + 'B');\n};\n\n/**\n * Generate rainbow colors.\n *\n * @private\n * @return {Array}\n */\nNyanCat.prototype.generateColors = function () {\n var colors = [];\n\n for (var i = 0; i < 6 * 7; i++) {\n var pi3 = Math.floor(Math.PI / 3);\n var n = i * (1.0 / 6);\n var r = Math.floor(3 * Math.sin(n) + 3);\n var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);\n var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);\n colors.push(36 * r + 6 * g + b + 16);\n }\n\n return colors;\n};\n\n/**\n * Apply rainbow to the given `str`.\n *\n * @private\n * @param {string} str\n * @return {string}\n */\nNyanCat.prototype.rainbowify = function (str) {\n if (!Base.useColors) {\n return str;\n }\n var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];\n this.colorIndex += 1;\n return '\\u001b[38;5;' + color + 'm' + str + '\\u001b[0m';\n};\n\nNyanCat.description = '\"nyan cat\"';\n","'use strict';\n/**\n * @module XUnit\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar utils = require('../utils');\nvar fs = require('fs');\nvar path = require('path');\nvar errors = require('../errors');\nvar createUnsupportedError = errors.createUnsupportedError;\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar STATE_FAILED = require('../runnable').constants.STATE_FAILED;\nvar inherits = utils.inherits;\nvar escape = utils.escape;\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\nvar Date = global.Date;\n\n/**\n * Expose `XUnit`.\n */\n\nexports = module.exports = XUnit;\n\n/**\n * Constructs a new `XUnit` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction XUnit(runner, options) {\n Base.call(this, runner, options);\n\n var stats = this.stats;\n var tests = [];\n var self = this;\n\n // the name of the test suite, as it will appear in the resulting XML file\n var suiteName;\n\n // the default name of the test suite if none is provided\n var DEFAULT_SUITE_NAME = 'Mocha Tests';\n\n if (options && options.reporterOptions) {\n if (options.reporterOptions.output) {\n if (!fs.createWriteStream) {\n throw createUnsupportedError('file output not supported in browser');\n }\n\n fs.mkdirSync(path.dirname(options.reporterOptions.output), {\n recursive: true\n });\n self.fileStream = fs.createWriteStream(options.reporterOptions.output);\n }\n\n // get the suite name from the reporter options (if provided)\n suiteName = options.reporterOptions.suiteName;\n }\n\n // fall back to the default suite name\n suiteName = suiteName || DEFAULT_SUITE_NAME;\n\n runner.on(EVENT_TEST_PENDING, function (test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n tests.push(test);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test) {\n tests.push(test);\n });\n\n runner.once(EVENT_RUN_END, function () {\n self.write(\n tag(\n 'testsuite',\n {\n name: suiteName,\n tests: stats.tests,\n failures: 0,\n errors: stats.failures,\n skipped: stats.tests - stats.failures - stats.passes,\n timestamp: new Date().toUTCString(),\n time: stats.duration / 1000 || 0\n },\n false\n )\n );\n\n tests.forEach(function (t) {\n self.test(t);\n });\n\n self.write('');\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(XUnit, Base);\n\n/**\n * Override done to close the stream (if it's a file).\n *\n * @param failures\n * @param {Function} fn\n */\nXUnit.prototype.done = function (failures, fn) {\n if (this.fileStream) {\n this.fileStream.end(function () {\n fn(failures);\n });\n } else {\n fn(failures);\n }\n};\n\n/**\n * Write out the given line.\n *\n * @param {string} line\n */\nXUnit.prototype.write = function (line) {\n if (this.fileStream) {\n this.fileStream.write(line + '\\n');\n } else if (typeof process === 'object' && process.stdout) {\n process.stdout.write(line + '\\n');\n } else {\n Base.consoleLog(line);\n }\n};\n\n/**\n * Output tag for the given `test.`\n *\n * @param {Test} test\n */\nXUnit.prototype.test = function (test) {\n Base.useColors = false;\n\n var attrs = {\n classname: test.parent.fullTitle(),\n name: test.title,\n file: test.file,\n time: test.duration / 1000 || 0\n };\n\n if (test.state === STATE_FAILED) {\n var err = test.err;\n var diff =\n !Base.hideDiff && Base.showDiff(err)\n ? '\\n' + Base.generateDiff(err.actual, err.expected)\n : '';\n this.write(\n tag(\n 'testcase',\n attrs,\n false,\n tag(\n 'failure',\n {},\n false,\n escape(err.message) + escape(diff) + '\\n' + escape(err.stack)\n )\n )\n );\n } else if (test.isPending()) {\n this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));\n } else {\n this.write(tag('testcase', attrs, true));\n }\n};\n\n/**\n * HTML tag helper.\n *\n * @param name\n * @param attrs\n * @param close\n * @param content\n * @return {string}\n */\nfunction tag(name, attrs, close, content) {\n var end = close ? '/>' : '>';\n var pairs = [];\n var tag;\n\n for (var key in attrs) {\n if (Object.prototype.hasOwnProperty.call(attrs, key)) {\n pairs.push(key + '=\"' + escape(attrs[key]) + '\"');\n }\n }\n\n tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;\n if (content) {\n tag += content + '' + '\\n';\n buf += title(suite.title) + '\\n';\n });\n\n runner.on(EVENT_SUITE_END, function () {\n --level;\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n var code = utils.clean(test.body);\n buf += test.title + '.\\n';\n buf += '\\n```js\\n';\n buf += code + '\\n';\n buf += '```\\n\\n';\n });\n\n runner.once(EVENT_RUN_END, function () {\n process.stdout.write('# TOC\\n');\n process.stdout.write(generateTOC(runner.suite));\n process.stdout.write(buf);\n });\n}\n\nMarkdown.description = 'GitHub Flavored Markdown';\n","'use strict';\n/**\n * @module Progress\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar inherits = require('../utils').inherits;\nvar color = Base.color;\nvar cursor = Base.cursor;\n\n/**\n * Expose `Progress`.\n */\n\nexports = module.exports = Progress;\n\n/**\n * General progress bar color.\n */\n\nBase.colors.progress = 90;\n\n/**\n * Constructs a new `Progress` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Progress(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.5) | 0;\n var total = runner.total;\n var complete = 0;\n var lastN = -1;\n\n // default chars\n options = options || {};\n var reporterOptions = options.reporterOptions || {};\n\n options.open = reporterOptions.open || '[';\n options.complete = reporterOptions.complete || '▬';\n options.incomplete = reporterOptions.incomplete || Base.symbols.dot;\n options.close = reporterOptions.close || ']';\n options.verbose = reporterOptions.verbose || false;\n\n // tests started\n runner.on(EVENT_RUN_BEGIN, function () {\n process.stdout.write('\\n');\n cursor.hide();\n });\n\n // tests complete\n runner.on(EVENT_TEST_END, function () {\n complete++;\n\n var percent = complete / total;\n var n = (width * percent) | 0;\n var i = width - n;\n\n if (n === lastN && !options.verbose) {\n // Don't re-render the line if it hasn't changed\n return;\n }\n lastN = n;\n\n cursor.CR();\n process.stdout.write('\\u001b[J');\n process.stdout.write(color('progress', ' ' + options.open));\n process.stdout.write(Array(n).join(options.complete));\n process.stdout.write(Array(i).join(options.incomplete));\n process.stdout.write(color('progress', options.close));\n if (options.verbose) {\n process.stdout.write(color('progress', ' ' + complete + ' of ' + total));\n }\n });\n\n // tests are complete, output some stats\n // and the failures if any\n runner.once(EVENT_RUN_END, function () {\n cursor.show();\n process.stdout.write('\\n');\n self.epilogue();\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Progress, Base);\n\nProgress.description = 'a progress bar';\n","'use strict';\n/**\n * @module Landing\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar inherits = require('../utils').inherits;\nvar constants = require('../runner').constants;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\nvar STATE_FAILED = require('../runnable').constants.STATE_FAILED;\n\nvar cursor = Base.cursor;\nvar color = Base.color;\n\n/**\n * Expose `Landing`.\n */\n\nexports = module.exports = Landing;\n\n/**\n * Airplane color.\n */\n\nBase.colors.plane = 0;\n\n/**\n * Airplane crash color.\n */\n\nBase.colors['plane crash'] = 31;\n\n/**\n * Runway color.\n */\n\nBase.colors.runway = 90;\n\n/**\n * Constructs a new `Landing` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction Landing(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var width = (Base.window.width * 0.75) | 0;\n var stream = process.stdout;\n\n var plane = color('plane', '✈');\n var crashed = -1;\n var n = 0;\n var total = 0;\n\n function runway() {\n var buf = Array(width).join('-');\n return ' ' + color('runway', buf);\n }\n\n runner.on(EVENT_RUN_BEGIN, function () {\n stream.write('\\n\\n\\n ');\n cursor.hide();\n });\n\n runner.on(EVENT_TEST_END, function (test) {\n // check if the plane crashed\n var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed;\n // show the crash\n if (test.state === STATE_FAILED) {\n plane = color('plane crash', '✈');\n crashed = col;\n }\n\n // render landing strip\n stream.write('\\u001b[' + (width + 1) + 'D\\u001b[2A');\n stream.write(runway());\n stream.write('\\n ');\n stream.write(color('runway', Array(col).join('⋅')));\n stream.write(plane);\n stream.write(color('runway', Array(width - col).join('⋅') + '\\n'));\n stream.write(runway());\n stream.write('\\u001b[0m');\n });\n\n runner.once(EVENT_RUN_END, function () {\n cursor.show();\n process.stdout.write('\\n');\n self.epilogue();\n });\n\n // if cursor is hidden when we ctrl-C, then it will remain hidden unless...\n process.once('SIGINT', function () {\n cursor.show();\n process.nextTick(function () {\n process.kill(process.pid, 'SIGINT');\n });\n });\n}\n\n/**\n * Inherit from `Base.prototype`.\n */\ninherits(Landing, Base);\n\nLanding.description = 'Unicode landing strip';\n","'use strict';\n/**\n * @module JSONStream\n */\n/**\n * Module dependencies.\n */\n\nvar Base = require('./base');\nvar constants = require('../runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\n\n/**\n * Expose `JSONStream`.\n */\n\nexports = module.exports = JSONStream;\n\n/**\n * Constructs a new `JSONStream` reporter instance.\n *\n * @public\n * @class\n * @memberof Mocha.reporters\n * @extends Mocha.reporters.Base\n * @param {Runner} runner - Instance triggers reporter actions.\n * @param {Object} [options] - runner options\n */\nfunction JSONStream(runner, options) {\n Base.call(this, runner, options);\n\n var self = this;\n var total = runner.total;\n\n runner.once(EVENT_RUN_BEGIN, function () {\n writeEvent(['start', {total}]);\n });\n\n runner.on(EVENT_TEST_PASS, function (test) {\n writeEvent(['pass', clean(test)]);\n });\n\n runner.on(EVENT_TEST_FAIL, function (test, err) {\n test = clean(test);\n test.err = err.message;\n test.stack = err.stack || null;\n writeEvent(['fail', test]);\n });\n\n runner.once(EVENT_RUN_END, function () {\n writeEvent(['end', self.stats]);\n });\n}\n\n/**\n * Mocha event to be written to the output stream.\n * @typedef {Array} JSONStream~MochaEvent\n */\n\n/**\n * Writes Mocha event to reporter output stream.\n *\n * @private\n * @param {JSONStream~MochaEvent} event - Mocha event to be output.\n */\nfunction writeEvent(event) {\n process.stdout.write(JSON.stringify(event) + '\\n');\n}\n\n/**\n * Returns an object literal representation of `test`\n * free of cyclic properties, etc.\n *\n * @private\n * @param {Test} test - Instance used as data source.\n * @return {Object} object containing pared-down test instance data\n */\nfunction clean(test) {\n return {\n title: test.title,\n fullTitle: test.fullTitle(),\n file: test.file,\n duration: test.duration,\n currentRetry: test.currentRetry(),\n speed: test.speed\n };\n}\n\nJSONStream.description = 'newline delimited JSON events';\n","'use strict';\n\n// Alias exports to a their normalized format Mocha#reporter to prevent a need\n// for dynamic (try/catch) requires, which Browserify doesn't handle.\nexports.Base = exports.base = require('./base');\nexports.Dot = exports.dot = require('./dot');\nexports.Doc = exports.doc = require('./doc');\nexports.TAP = exports.tap = require('./tap');\nexports.JSON = exports.json = require('./json');\nexports.HTML = exports.html = require('./html');\nexports.List = exports.list = require('./list');\nexports.Min = exports.min = require('./min');\nexports.Spec = exports.spec = require('./spec');\nexports.Nyan = exports.nyan = require('./nyan');\nexports.XUnit = exports.xunit = require('./xunit');\nexports.Markdown = exports.markdown = require('./markdown');\nexports.Progress = exports.progress = require('./progress');\nexports.Landing = exports.landing = require('./landing');\nexports.JSONStream = exports['json-stream'] = require('./json-stream');\n","'use strict';\n\n/**\n * Provides a factory function for a {@link StatsCollector} object.\n * @module\n */\n\nvar constants = require('./runner').constants;\nvar EVENT_TEST_PASS = constants.EVENT_TEST_PASS;\nvar EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;\nvar EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;\nvar EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;\nvar EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;\nvar EVENT_RUN_END = constants.EVENT_RUN_END;\nvar EVENT_TEST_END = constants.EVENT_TEST_END;\n\n/**\n * Test statistics collector.\n *\n * @public\n * @typedef {Object} StatsCollector\n * @property {number} suites - integer count of suites run.\n * @property {number} tests - integer count of tests run.\n * @property {number} passes - integer count of passing tests.\n * @property {number} pending - integer count of pending tests.\n * @property {number} failures - integer count of failed tests.\n * @property {Date} start - time when testing began.\n * @property {Date} end - time when testing concluded.\n * @property {number} duration - number of msecs that testing took.\n */\n\nvar Date = global.Date;\n\n/**\n * Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by `runner`.\n *\n * @private\n * @param {Runner} runner - Runner instance\n * @throws {TypeError} If falsy `runner`\n */\nfunction createStatsCollector(runner) {\n /**\n * @type StatsCollector\n */\n var stats = {\n suites: 0,\n tests: 0,\n passes: 0,\n pending: 0,\n failures: 0\n };\n\n if (!runner) {\n throw new TypeError('Missing runner argument');\n }\n\n runner.stats = stats;\n\n runner.once(EVENT_RUN_BEGIN, function () {\n stats.start = new Date();\n });\n runner.on(EVENT_SUITE_BEGIN, function (suite) {\n suite.root || stats.suites++;\n });\n runner.on(EVENT_TEST_PASS, function () {\n stats.passes++;\n });\n runner.on(EVENT_TEST_FAIL, function () {\n stats.failures++;\n });\n runner.on(EVENT_TEST_PENDING, function () {\n stats.pending++;\n });\n runner.on(EVENT_TEST_END, function () {\n stats.tests++;\n });\n runner.once(EVENT_RUN_END, function () {\n stats.end = new Date();\n stats.duration = stats.end - stats.start;\n });\n}\n\nmodule.exports = createStatsCollector;\n","'use strict';\nvar Runnable = require('./runnable');\nvar utils = require('./utils');\nvar errors = require('./errors');\nvar createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;\nvar isString = utils.isString;\n\nconst {MOCHA_ID_PROP_NAME} = utils.constants;\n\nmodule.exports = Test;\n\n/**\n * Initialize a new `Test` with the given `title` and callback `fn`.\n *\n * @public\n * @class\n * @extends Runnable\n * @param {String} title - Test title (required)\n * @param {Function} [fn] - Test callback. If omitted, the Test is considered \"pending\"\n */\nfunction Test(title, fn) {\n if (!isString(title)) {\n throw createInvalidArgumentTypeError(\n 'Test argument \"title\" should be a string. Received type \"' +\n typeof title +\n '\"',\n 'title',\n 'string'\n );\n }\n this.type = 'test';\n Runnable.call(this, title, fn);\n this.reset();\n}\n\n/**\n * Inherit from `Runnable.prototype`.\n */\nutils.inherits(Test, Runnable);\n\n/**\n * Resets the state initially or for a next run.\n */\nTest.prototype.reset = function () {\n Runnable.prototype.reset.call(this);\n this.pending = !this.fn;\n delete this.state;\n};\n\n/**\n * Set or get retried test\n *\n * @private\n */\nTest.prototype.retriedTest = function (n) {\n if (!arguments.length) {\n return this._retriedTest;\n }\n this._retriedTest = n;\n};\n\n/**\n * Add test to the list of tests marked `only`.\n *\n * @private\n */\nTest.prototype.markOnly = function () {\n this.parent.appendOnlyTest(this);\n};\n\nTest.prototype.clone = function () {\n var test = new Test(this.title, this.fn);\n test.timeout(this.timeout());\n test.slow(this.slow());\n test.retries(this.retries());\n test.currentRetry(this.currentRetry());\n test.retriedTest(this.retriedTest() || this);\n test.globals(this.globals());\n test.parent = this.parent;\n test.file = this.file;\n test.ctx = this.ctx;\n return test;\n};\n\n/**\n * Returns an minimal object suitable for transmission over IPC.\n * Functions are represented by keys beginning with `$$`.\n * @private\n * @returns {Object}\n */\nTest.prototype.serialize = function serialize() {\n return {\n $$currentRetry: this._currentRetry,\n $$fullTitle: this.fullTitle(),\n $$isPending: Boolean(this.pending),\n $$retriedTest: this._retriedTest || null,\n $$slow: this._slow,\n $$titlePath: this.titlePath(),\n body: this.body,\n duration: this.duration,\n err: this.err,\n parent: {\n $$fullTitle: this.parent.fullTitle(),\n [MOCHA_ID_PROP_NAME]: this.parent.id\n },\n speed: this.speed,\n state: this.state,\n title: this.title,\n type: this.type,\n file: this.file,\n [MOCHA_ID_PROP_NAME]: this.id\n };\n};\n","'use strict';\n\n/**\n @module interfaces/common\n*/\n\nvar Suite = require('../suite');\nvar errors = require('../errors');\nvar createMissingArgumentError = errors.createMissingArgumentError;\nvar createUnsupportedError = errors.createUnsupportedError;\nvar createForbiddenExclusivityError = errors.createForbiddenExclusivityError;\n\n/**\n * Functions common to more than one interface.\n *\n * @private\n * @param {Suite[]} suites\n * @param {Context} context\n * @param {Mocha} mocha\n * @return {Object} An object containing common functions.\n */\nmodule.exports = function (suites, context, mocha) {\n /**\n * Check if the suite should be tested.\n *\n * @private\n * @param {Suite} suite - suite to check\n * @returns {boolean}\n */\n function shouldBeTested(suite) {\n return (\n !mocha.options.grep ||\n (mocha.options.grep &&\n mocha.options.grep.test(suite.fullTitle()) &&\n !mocha.options.invert)\n );\n }\n\n return {\n /**\n * This is only present if flag --delay is passed into Mocha. It triggers\n * root suite execution.\n *\n * @param {Suite} suite The root suite.\n * @return {Function} A function which runs the root suite\n */\n runWithSuite: function runWithSuite(suite) {\n return function run() {\n suite.run();\n };\n },\n\n /**\n * Execute before running tests.\n *\n * @param {string} name\n * @param {Function} fn\n */\n before: function (name, fn) {\n suites[0].beforeAll(name, fn);\n },\n\n /**\n * Execute after running tests.\n *\n * @param {string} name\n * @param {Function} fn\n */\n after: function (name, fn) {\n suites[0].afterAll(name, fn);\n },\n\n /**\n * Execute before each test case.\n *\n * @param {string} name\n * @param {Function} fn\n */\n beforeEach: function (name, fn) {\n suites[0].beforeEach(name, fn);\n },\n\n /**\n * Execute after each test case.\n *\n * @param {string} name\n * @param {Function} fn\n */\n afterEach: function (name, fn) {\n suites[0].afterEach(name, fn);\n },\n\n suite: {\n /**\n * Create an exclusive Suite; convenience function\n * See docstring for create() below.\n *\n * @param {Object} opts\n * @returns {Suite}\n */\n only: function only(opts) {\n if (mocha.options.forbidOnly) {\n throw createForbiddenExclusivityError(mocha);\n }\n opts.isOnly = true;\n return this.create(opts);\n },\n\n /**\n * Create a Suite, but skip it; convenience function\n * See docstring for create() below.\n *\n * @param {Object} opts\n * @returns {Suite}\n */\n skip: function skip(opts) {\n opts.pending = true;\n return this.create(opts);\n },\n\n /**\n * Creates a suite.\n *\n * @param {Object} opts Options\n * @param {string} opts.title Title of Suite\n * @param {Function} [opts.fn] Suite Function (not always applicable)\n * @param {boolean} [opts.pending] Is Suite pending?\n * @param {string} [opts.file] Filepath where this Suite resides\n * @param {boolean} [opts.isOnly] Is Suite exclusive?\n * @returns {Suite}\n */\n create: function create(opts) {\n var suite = Suite.create(suites[0], opts.title);\n suite.pending = Boolean(opts.pending);\n suite.file = opts.file;\n suites.unshift(suite);\n if (opts.isOnly) {\n suite.markOnly();\n }\n if (\n suite.pending &&\n mocha.options.forbidPending &&\n shouldBeTested(suite)\n ) {\n throw createUnsupportedError('Pending test forbidden');\n }\n if (typeof opts.fn === 'function') {\n opts.fn.call(suite);\n suites.shift();\n } else if (typeof opts.fn === 'undefined' && !suite.pending) {\n throw createMissingArgumentError(\n 'Suite \"' +\n suite.fullTitle() +\n '\" was defined but no callback was supplied. ' +\n 'Supply a callback or explicitly skip the suite.',\n 'callback',\n 'function'\n );\n } else if (!opts.fn && suite.pending) {\n suites.shift();\n }\n\n return suite;\n }\n },\n\n test: {\n /**\n * Exclusive test-case.\n *\n * @param {Object} mocha\n * @param {Function} test\n * @returns {*}\n */\n only: function (mocha, test) {\n if (mocha.options.forbidOnly) {\n throw createForbiddenExclusivityError(mocha);\n }\n test.markOnly();\n return test;\n },\n\n /**\n * Pending test case.\n *\n * @param {string} title\n */\n skip: function (title) {\n context.test(title);\n }\n }\n };\n};\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE =\n require('../suite').constants.EVENT_FILE_PRE_REQUIRE;\n\n/**\n * BDD-style interface:\n *\n * describe('Array', function() {\n * describe('#indexOf()', function() {\n * it('should return -1 when not present', function() {\n * // ...\n * });\n *\n * it('should return the index when present', function() {\n * // ...\n * });\n * });\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function bddInterface(suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.before = common.before;\n context.after = common.after;\n context.beforeEach = common.beforeEach;\n context.afterEach = common.afterEach;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n /**\n * Describe a \"suite\" with the given `title`\n * and callback `fn` containing nested suites\n * and/or tests.\n */\n\n context.describe = context.context = function (title, fn) {\n return common.suite.create({\n title,\n file,\n fn\n });\n };\n\n /**\n * Pending describe.\n */\n\n context.xdescribe =\n context.xcontext =\n context.describe.skip =\n function (title, fn) {\n return common.suite.skip({\n title,\n file,\n fn\n });\n };\n\n /**\n * Exclusive suite.\n */\n\n context.describe.only = function (title, fn) {\n return common.suite.only({\n title,\n file,\n fn\n });\n };\n\n /**\n * Describe a specification or test-case\n * with the given `title` and callback `fn`\n * acting as a thunk.\n */\n\n context.it = context.specify = function (title, fn) {\n var suite = suites[0];\n if (suite.isPending()) {\n fn = null;\n }\n var test = new Test(title, fn);\n test.file = file;\n suite.addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.it.only = function (title, fn) {\n return common.test.only(mocha, context.it(title, fn));\n };\n\n /**\n * Pending test case.\n */\n\n context.xit =\n context.xspecify =\n context.it.skip =\n function (title) {\n return context.it(title);\n };\n });\n};\n\nmodule.exports.description = 'BDD or RSpec style [default]';\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE =\n require('../suite').constants.EVENT_FILE_PRE_REQUIRE;\n\n/**\n * TDD-style interface:\n *\n * suite('Array', function() {\n * suite('#indexOf()', function() {\n * suiteSetup(function() {\n *\n * });\n *\n * test('should return -1 when not present', function() {\n *\n * });\n *\n * test('should return the index when present', function() {\n *\n * });\n *\n * suiteTeardown(function() {\n *\n * });\n * });\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function (suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.setup = common.beforeEach;\n context.teardown = common.afterEach;\n context.suiteSetup = common.before;\n context.suiteTeardown = common.after;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n\n /**\n * Describe a \"suite\" with the given `title` and callback `fn` containing\n * nested suites and/or tests.\n */\n context.suite = function (title, fn) {\n return common.suite.create({\n title,\n file,\n fn\n });\n };\n\n /**\n * Pending suite.\n */\n context.suite.skip = function (title, fn) {\n return common.suite.skip({\n title,\n file,\n fn\n });\n };\n\n /**\n * Exclusive test-case.\n */\n context.suite.only = function (title, fn) {\n return common.suite.only({\n title,\n file,\n fn\n });\n };\n\n /**\n * Describe a specification or test-case with the given `title` and\n * callback `fn` acting as a thunk.\n */\n context.test = function (title, fn) {\n var suite = suites[0];\n if (suite.isPending()) {\n fn = null;\n }\n var test = new Test(title, fn);\n test.file = file;\n suite.addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.test.only = function (title, fn) {\n return common.test.only(mocha, context.test(title, fn));\n };\n\n context.test.skip = common.test.skip;\n });\n};\n\nmodule.exports.description =\n 'traditional \"suite\"/\"test\" instead of BDD\\'s \"describe\"/\"it\"';\n","'use strict';\n\nvar Test = require('../test');\nvar EVENT_FILE_PRE_REQUIRE =\n require('../suite').constants.EVENT_FILE_PRE_REQUIRE;\n\n/**\n * QUnit-style interface:\n *\n * suite('Array');\n *\n * test('#length', function() {\n * var arr = [1,2,3];\n * ok(arr.length == 3);\n * });\n *\n * test('#indexOf()', function() {\n * var arr = [1,2,3];\n * ok(arr.indexOf(1) == 0);\n * ok(arr.indexOf(2) == 1);\n * ok(arr.indexOf(3) == 2);\n * });\n *\n * suite('String');\n *\n * test('#length', function() {\n * ok('foo'.length == 3);\n * });\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function qUnitInterface(suite) {\n var suites = [suite];\n\n suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {\n var common = require('./common')(suites, context, mocha);\n\n context.before = common.before;\n context.after = common.after;\n context.beforeEach = common.beforeEach;\n context.afterEach = common.afterEach;\n context.run = mocha.options.delay && common.runWithSuite(suite);\n /**\n * Describe a \"suite\" with the given `title`.\n */\n\n context.suite = function (title) {\n if (suites.length > 1) {\n suites.shift();\n }\n return common.suite.create({\n title,\n file,\n fn: false\n });\n };\n\n /**\n * Exclusive Suite.\n */\n\n context.suite.only = function (title) {\n if (suites.length > 1) {\n suites.shift();\n }\n return common.suite.only({\n title,\n file,\n fn: false\n });\n };\n\n /**\n * Describe a specification or test-case\n * with the given `title` and callback `fn`\n * acting as a thunk.\n */\n\n context.test = function (title, fn) {\n var test = new Test(title, fn);\n test.file = file;\n suites[0].addTest(test);\n return test;\n };\n\n /**\n * Exclusive test-case.\n */\n\n context.test.only = function (title, fn) {\n return common.test.only(mocha, context.test(title, fn));\n };\n\n context.test.skip = common.test.skip;\n });\n};\n\nmodule.exports.description = 'QUnit style';\n","'use strict';\nvar Suite = require('../suite');\nvar Test = require('../test');\n\n/**\n * Exports-style (as Node.js module) interface:\n *\n * exports.Array = {\n * '#indexOf()': {\n * 'should return -1 when the value is not present': function() {\n *\n * },\n *\n * 'should return the correct index when the value is present': function() {\n *\n * }\n * }\n * };\n *\n * @param {Suite} suite Root suite.\n */\nmodule.exports = function (suite) {\n var suites = [suite];\n\n suite.on(Suite.constants.EVENT_FILE_REQUIRE, visit);\n\n function visit(obj, file) {\n var suite;\n for (var key in obj) {\n if (typeof obj[key] === 'function') {\n var fn = obj[key];\n switch (key) {\n case 'before':\n suites[0].beforeAll(fn);\n break;\n case 'after':\n suites[0].afterAll(fn);\n break;\n case 'beforeEach':\n suites[0].beforeEach(fn);\n break;\n case 'afterEach':\n suites[0].afterEach(fn);\n break;\n default:\n var test = new Test(key, fn);\n test.file = file;\n suites[0].addTest(test);\n }\n } else {\n suite = Suite.create(suites[0], key);\n suites.unshift(suite);\n visit(obj[key], file);\n suites.shift();\n }\n }\n }\n};\n\nmodule.exports.description = 'Node.js module (\"exports\") style';\n","'use strict';\n\nexports.bdd = require('./bdd');\nexports.tdd = require('./tdd');\nexports.qunit = require('./qunit');\nexports.exports = require('./exports');\n","'use strict';\n/**\n * @module Context\n */\n/**\n * Expose `Context`.\n */\n\nmodule.exports = Context;\n\n/**\n * Initialize a new `Context`.\n *\n * @private\n */\nfunction Context() {}\n\n/**\n * Set or get the context `Runnable` to `runnable`.\n *\n * @private\n * @param {Runnable} runnable\n * @return {Context} context\n */\nContext.prototype.runnable = function (runnable) {\n if (!arguments.length) {\n return this._runnable;\n }\n this.test = this._runnable = runnable;\n return this;\n};\n\n/**\n * Set or get test timeout `ms`.\n *\n * @private\n * @param {number} ms\n * @return {Context} self\n */\nContext.prototype.timeout = function (ms) {\n if (!arguments.length) {\n return this.runnable().timeout();\n }\n this.runnable().timeout(ms);\n return this;\n};\n\n/**\n * Set or get test slowness threshold `ms`.\n *\n * @private\n * @param {number} ms\n * @return {Context} self\n */\nContext.prototype.slow = function (ms) {\n if (!arguments.length) {\n return this.runnable().slow();\n }\n this.runnable().slow(ms);\n return this;\n};\n\n/**\n * Mark a test as skipped.\n *\n * @private\n * @throws Pending\n */\nContext.prototype.skip = function () {\n this.runnable().skip();\n};\n\n/**\n * Set or get a number of allowed retries on failed tests\n *\n * @private\n * @param {number} n\n * @return {Context} self\n */\nContext.prototype.retries = function (n) {\n if (!arguments.length) {\n return this.runnable().retries();\n }\n this.runnable().retries(n);\n return this;\n};\n","'use strict';\n\n/*!\n * mocha\n * Copyright(c) 2011 TJ Holowaychuk \n * MIT Licensed\n */\n\nvar escapeRe = require('escape-string-regexp');\nvar path = require('path');\nvar builtinReporters = require('./reporters');\nvar utils = require('./utils');\nvar mocharc = require('./mocharc.json');\nvar Suite = require('./suite');\nvar esmUtils = require('./nodejs/esm-utils');\nvar createStatsCollector = require('./stats-collector');\nconst {\n createInvalidReporterError,\n createInvalidInterfaceError,\n createMochaInstanceAlreadyDisposedError,\n createMochaInstanceAlreadyRunningError,\n createUnsupportedError\n} = require('./errors');\nconst {EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE} =\n Suite.constants;\nvar debug = require('debug')('mocha:mocha');\n\nexports = module.exports = Mocha;\n\n/**\n * A Mocha instance is a finite state machine.\n * These are the states it can be in.\n * @private\n */\nvar mochaStates = utils.defineConstants({\n /**\n * Initial state of the mocha instance\n * @private\n */\n INIT: 'init',\n /**\n * Mocha instance is running tests\n * @private\n */\n RUNNING: 'running',\n /**\n * Mocha instance is done running tests and references to test functions and hooks are cleaned.\n * You can reset this state by unloading the test files.\n * @private\n */\n REFERENCES_CLEANED: 'referencesCleaned',\n /**\n * Mocha instance is disposed and can no longer be used.\n * @private\n */\n DISPOSED: 'disposed'\n});\n\n/**\n * To require local UIs and reporters when running in node.\n */\n\nif (!utils.isBrowser() && typeof module.paths !== 'undefined') {\n var cwd = utils.cwd();\n module.paths.push(cwd, path.join(cwd, 'node_modules'));\n}\n\n/**\n * Expose internals.\n * @private\n */\n\nexports.utils = utils;\nexports.interfaces = require('./interfaces');\n/**\n * @public\n * @memberof Mocha\n */\nexports.reporters = builtinReporters;\nexports.Runnable = require('./runnable');\nexports.Context = require('./context');\n/**\n *\n * @memberof Mocha\n */\nexports.Runner = require('./runner');\nexports.Suite = Suite;\nexports.Hook = require('./hook');\nexports.Test = require('./test');\n\nlet currentContext;\nexports.afterEach = function (...args) {\n return (currentContext.afterEach || currentContext.teardown).apply(\n this,\n args\n );\n};\nexports.after = function (...args) {\n return (currentContext.after || currentContext.suiteTeardown).apply(\n this,\n args\n );\n};\nexports.beforeEach = function (...args) {\n return (currentContext.beforeEach || currentContext.setup).apply(this, args);\n};\nexports.before = function (...args) {\n return (currentContext.before || currentContext.suiteSetup).apply(this, args);\n};\nexports.describe = function (...args) {\n return (currentContext.describe || currentContext.suite).apply(this, args);\n};\nexports.describe.only = function (...args) {\n return (currentContext.describe || currentContext.suite).only.apply(\n this,\n args\n );\n};\nexports.describe.skip = function (...args) {\n return (currentContext.describe || currentContext.suite).skip.apply(\n this,\n args\n );\n};\nexports.it = function (...args) {\n return (currentContext.it || currentContext.test).apply(this, args);\n};\nexports.it.only = function (...args) {\n return (currentContext.it || currentContext.test).only.apply(this, args);\n};\nexports.it.skip = function (...args) {\n return (currentContext.it || currentContext.test).skip.apply(this, args);\n};\nexports.xdescribe = exports.describe.skip;\nexports.xit = exports.it.skip;\nexports.setup = exports.beforeEach;\nexports.suiteSetup = exports.before;\nexports.suiteTeardown = exports.after;\nexports.suite = exports.describe;\nexports.teardown = exports.afterEach;\nexports.test = exports.it;\nexports.run = function (...args) {\n return currentContext.run.apply(this, args);\n};\n\n/**\n * Constructs a new Mocha instance with `options`.\n *\n * @public\n * @class Mocha\n * @param {Object} [options] - Settings object.\n * @param {boolean} [options.allowUncaught] - Propagate uncaught errors?\n * @param {boolean} [options.asyncOnly] - Force `done` callback or promise?\n * @param {boolean} [options.bail] - Bail after first test failure?\n * @param {boolean} [options.checkLeaks] - Check for global variable leaks?\n * @param {boolean} [options.color] - Color TTY output from reporter?\n * @param {boolean} [options.delay] - Delay root suite execution?\n * @param {boolean} [options.diff] - Show diff on failure?\n * @param {boolean} [options.dryRun] - Report tests without running them?\n * @param {boolean} [options.failZero] - Fail test run if zero tests?\n * @param {string} [options.fgrep] - Test filter given string.\n * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite?\n * @param {boolean} [options.forbidPending] - Pending tests fail the suite?\n * @param {boolean} [options.fullTrace] - Full stacktrace upon failure?\n * @param {string[]} [options.global] - Variables expected in global scope.\n * @param {RegExp|string} [options.grep] - Test filter given regular expression.\n * @param {boolean} [options.inlineDiffs] - Display inline diffs?\n * @param {boolean} [options.invert] - Invert test filter matches?\n * @param {boolean} [options.noHighlighting] - Disable syntax highlighting?\n * @param {string|constructor} [options.reporter] - Reporter name or constructor.\n * @param {Object} [options.reporterOption] - Reporter settings object.\n * @param {number} [options.retries] - Number of times to retry failed tests.\n * @param {number} [options.slow] - Slow threshold value.\n * @param {number|string} [options.timeout] - Timeout threshold value.\n * @param {string} [options.ui] - Interface name.\n * @param {boolean} [options.parallel] - Run jobs in parallel.\n * @param {number} [options.jobs] - Max number of worker processes for parallel runs.\n * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with.\n * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs.\n * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process.\n */\nfunction Mocha(options = {}) {\n options = {...mocharc, ...options};\n this.files = [];\n this.options = options;\n // root suite\n this.suite = new exports.Suite('', new exports.Context(), true);\n this._cleanReferencesAfterRun = true;\n this._state = mochaStates.INIT;\n\n this.grep(options.grep)\n .fgrep(options.fgrep)\n .ui(options.ui)\n .reporter(\n options.reporter,\n options.reporterOption || options.reporterOptions // for backwards compatibility\n )\n .slow(options.slow)\n .global(options.global);\n\n // this guard exists because Suite#timeout does not consider `undefined` to be valid input\n if (typeof options.timeout !== 'undefined') {\n this.timeout(options.timeout === false ? 0 : options.timeout);\n }\n\n if ('retries' in options) {\n this.retries(options.retries);\n }\n\n [\n 'allowUncaught',\n 'asyncOnly',\n 'bail',\n 'checkLeaks',\n 'color',\n 'delay',\n 'diff',\n 'dryRun',\n 'failZero',\n 'forbidOnly',\n 'forbidPending',\n 'fullTrace',\n 'inlineDiffs',\n 'invert'\n ].forEach(function (opt) {\n if (options[opt]) {\n this[opt]();\n }\n }, this);\n\n if (options.rootHooks) {\n this.rootHooks(options.rootHooks);\n }\n\n /**\n * The class which we'll instantiate in {@link Mocha#run}. Defaults to\n * {@link Runner} in serial mode; changes in parallel mode.\n * @memberof Mocha\n * @private\n */\n this._runnerClass = exports.Runner;\n\n /**\n * Whether or not to call {@link Mocha#loadFiles} implicitly when calling\n * {@link Mocha#run}. If this is `true`, then it's up to the consumer to call\n * {@link Mocha#loadFiles} _or_ {@link Mocha#loadFilesAsync}.\n * @private\n * @memberof Mocha\n */\n this._lazyLoadFiles = false;\n\n /**\n * It's useful for a Mocha instance to know if it's running in a worker process.\n * We could derive this via other means, but it's helpful to have a flag to refer to.\n * @memberof Mocha\n * @private\n */\n this.isWorker = Boolean(options.isWorker);\n\n this.globalSetup(options.globalSetup)\n .globalTeardown(options.globalTeardown)\n .enableGlobalSetup(options.enableGlobalSetup)\n .enableGlobalTeardown(options.enableGlobalTeardown);\n\n if (\n options.parallel &&\n (typeof options.jobs === 'undefined' || options.jobs > 1)\n ) {\n debug('attempting to enable parallel mode');\n this.parallelMode(true);\n }\n}\n\n/**\n * Enables or disables bailing on the first failure.\n *\n * @public\n * @see [CLI option](../#-bail-b)\n * @param {boolean} [bail=true] - Whether to bail on first error.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.bail = function (bail) {\n this.suite.bail(bail !== false);\n return this;\n};\n\n/**\n * @summary\n * Adds `file` to be loaded for execution.\n *\n * @description\n * Useful for generic setup code that must be included within test suite.\n *\n * @public\n * @see [CLI option](../#-file-filedirectoryglob)\n * @param {string} file - Pathname of file to be loaded.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.addFile = function (file) {\n this.files.push(file);\n return this;\n};\n\n/**\n * Sets reporter to `reporter`, defaults to \"spec\".\n *\n * @public\n * @see [CLI option](../#-reporter-name-r-name)\n * @see [Reporters](../#reporters)\n * @param {String|Function} reporterName - Reporter name or constructor.\n * @param {Object} [reporterOptions] - Options used to configure the reporter.\n * @returns {Mocha} this\n * @chainable\n * @throws {Error} if requested reporter cannot be loaded\n * @example\n *\n * // Use XUnit reporter and direct its output to file\n * mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });\n */\nMocha.prototype.reporter = function (reporterName, reporterOptions) {\n if (typeof reporterName === 'function') {\n this._reporter = reporterName;\n } else {\n reporterName = reporterName || 'spec';\n var reporter;\n // Try to load a built-in reporter.\n if (builtinReporters[reporterName]) {\n reporter = builtinReporters[reporterName];\n }\n // Try to load reporters from process.cwd() and node_modules\n if (!reporter) {\n let foundReporter;\n try {\n foundReporter = require.resolve(reporterName);\n reporter = require(foundReporter);\n } catch (err) {\n if (foundReporter) {\n throw createInvalidReporterError(err.message, foundReporter);\n }\n // Try to load reporters from a cwd-relative path\n try {\n reporter = require(path.resolve(reporterName));\n } catch (e) {\n throw createInvalidReporterError(e.message, reporterName);\n }\n }\n }\n this._reporter = reporter;\n }\n this.options.reporterOption = reporterOptions;\n // alias option name is used in built-in reporters xunit/tap/progress\n this.options.reporterOptions = reporterOptions;\n return this;\n};\n\n/**\n * Sets test UI `name`, defaults to \"bdd\".\n *\n * @public\n * @see [CLI option](../#-ui-name-u-name)\n * @see [Interface DSLs](../#interfaces)\n * @param {string|Function} [ui=bdd] - Interface name or class.\n * @returns {Mocha} this\n * @chainable\n * @throws {Error} if requested interface cannot be loaded\n */\nMocha.prototype.ui = function (ui) {\n var bindInterface;\n if (typeof ui === 'function') {\n bindInterface = ui;\n } else {\n ui = ui || 'bdd';\n bindInterface = exports.interfaces[ui];\n if (!bindInterface) {\n try {\n bindInterface = require(ui);\n } catch (err) {\n throw createInvalidInterfaceError(`invalid interface '${ui}'`, ui);\n }\n }\n }\n bindInterface(this.suite);\n\n this.suite.on(EVENT_FILE_PRE_REQUIRE, function (context) {\n currentContext = context;\n });\n\n return this;\n};\n\n/**\n * Loads `files` prior to execution. Does not support ES Modules.\n *\n * @description\n * The implementation relies on Node's `require` to execute\n * the test interface functions and will be subject to its cache.\n * Supports only CommonJS modules. To load ES modules, use Mocha#loadFilesAsync.\n *\n * @private\n * @see {@link Mocha#addFile}\n * @see {@link Mocha#run}\n * @see {@link Mocha#unloadFiles}\n * @see {@link Mocha#loadFilesAsync}\n * @param {Function} [fn] - Callback invoked upon completion.\n */\nMocha.prototype.loadFiles = function (fn) {\n var self = this;\n var suite = this.suite;\n this.files.forEach(function (file) {\n file = path.resolve(file);\n suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);\n suite.emit(EVENT_FILE_REQUIRE, require(file), file, self);\n suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);\n });\n fn && fn();\n};\n\n/**\n * Loads `files` prior to execution. Supports Node ES Modules.\n *\n * @description\n * The implementation relies on Node's `require` and `import` to execute\n * the test interface functions and will be subject to its cache.\n * Supports both CJS and ESM modules.\n *\n * @public\n * @see {@link Mocha#addFile}\n * @see {@link Mocha#run}\n * @see {@link Mocha#unloadFiles}\n * @param {Object} [options] - Settings object.\n * @param {Function} [options.esmDecorator] - Function invoked on esm module name right before importing it. By default will passthrough as is.\n * @returns {Promise}\n * @example\n *\n * // loads ESM (and CJS) test files asynchronously, then runs root suite\n * mocha.loadFilesAsync()\n * .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))\n * .catch(() => process.exitCode = 1);\n */\nMocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) {\n var self = this;\n var suite = this.suite;\n this.lazyLoadFiles(true);\n\n return esmUtils.loadFilesAsync(\n this.files,\n function (file) {\n suite.emit(EVENT_FILE_PRE_REQUIRE, global, file, self);\n },\n function (file, resultModule) {\n suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self);\n suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);\n },\n esmDecorator\n );\n};\n\n/**\n * Removes a previously loaded file from Node's `require` cache.\n *\n * @private\n * @static\n * @see {@link Mocha#unloadFiles}\n * @param {string} file - Pathname of file to be unloaded.\n */\nMocha.unloadFile = function (file) {\n if (utils.isBrowser()) {\n throw createUnsupportedError(\n 'unloadFile() is only supported in a Node.js environment'\n );\n }\n return require('./nodejs/file-unloader').unloadFile(file);\n};\n\n/**\n * Unloads `files` from Node's `require` cache.\n *\n * @description\n * This allows required files to be \"freshly\" reloaded, providing the ability\n * to reuse a Mocha instance programmatically.\n * Note: does not clear ESM module files from the cache\n *\n * Intended for consumers — not used internally\n *\n * @public\n * @see {@link Mocha#run}\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.unloadFiles = function () {\n if (this._state === mochaStates.DISPOSED) {\n throw createMochaInstanceAlreadyDisposedError(\n 'Mocha instance is already disposed, it cannot be used again.',\n this._cleanReferencesAfterRun,\n this\n );\n }\n\n this.files.forEach(function (file) {\n Mocha.unloadFile(file);\n });\n this._state = mochaStates.INIT;\n return this;\n};\n\n/**\n * Sets `grep` filter after escaping RegExp special characters.\n *\n * @public\n * @see {@link Mocha#grep}\n * @param {string} str - Value to be converted to a regexp.\n * @returns {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title begins with `\"foo\"` followed by a period\n * mocha.fgrep('foo.');\n */\nMocha.prototype.fgrep = function (str) {\n if (!str) {\n return this;\n }\n return this.grep(new RegExp(escapeRe(str)));\n};\n\n/**\n * @summary\n * Sets `grep` filter used to select specific tests for execution.\n *\n * @description\n * If `re` is a regexp-like string, it will be converted to regexp.\n * The regexp is tested against the full title of each test (i.e., the\n * name of the test preceded by titles of each its ancestral suites).\n * As such, using an exact-match fixed pattern against the\n * test name itself will not yield any matches.\n *
            \n * Previous filter value will be overwritten on each call!\n *\n * @public\n * @see [CLI option](../#-grep-regexp-g-regexp)\n * @see {@link Mocha#fgrep}\n * @see {@link Mocha#invert}\n * @param {RegExp|String} re - Regular expression used to select tests.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title contains `\"match\"`, ignoring case\n * mocha.grep(/match/i);\n * @example\n *\n * // Same as above but with regexp-like string argument\n * mocha.grep('/match/i');\n * @example\n *\n * // ## Anti-example\n * // Given embedded test `it('only-this-test')`...\n * mocha.grep('/^only-this-test$/'); // NO! Use `.only()` to do this!\n */\nMocha.prototype.grep = function (re) {\n if (utils.isString(re)) {\n // extract args if it's regex-like, i.e: [string, pattern, flag]\n var arg = re.match(/^\\/(.*)\\/([gimy]{0,4})$|.*/);\n this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);\n } else {\n this.options.grep = re;\n }\n return this;\n};\n\n/**\n * Inverts `grep` matches.\n *\n * @public\n * @see {@link Mocha#grep}\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Select tests whose full title does *not* contain `\"match\"`, ignoring case\n * mocha.grep(/match/i).invert();\n */\nMocha.prototype.invert = function () {\n this.options.invert = true;\n return this;\n};\n\n/**\n * Enables or disables checking for global variables leaked while running tests.\n *\n * @public\n * @see [CLI option](../#-check-leaks)\n * @param {boolean} [checkLeaks=true] - Whether to check for global variable leaks.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.checkLeaks = function (checkLeaks) {\n this.options.checkLeaks = checkLeaks !== false;\n return this;\n};\n\n/**\n * Enables or disables whether or not to dispose after each test run.\n * Disable this to ensure you can run the test suite multiple times.\n * If disabled, be sure to dispose mocha when you're done to prevent memory leaks.\n * @public\n * @see {@link Mocha#dispose}\n * @param {boolean} cleanReferencesAfterRun\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) {\n this._cleanReferencesAfterRun = cleanReferencesAfterRun !== false;\n return this;\n};\n\n/**\n * Manually dispose this mocha instance. Mark this instance as `disposed` and unable to run more tests.\n * It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector.\n * @public\n */\nMocha.prototype.dispose = function () {\n if (this._state === mochaStates.RUNNING) {\n throw createMochaInstanceAlreadyRunningError(\n 'Cannot dispose while the mocha instance is still running tests.'\n );\n }\n this.unloadFiles();\n this._previousRunner && this._previousRunner.dispose();\n this.suite.dispose();\n this._state = mochaStates.DISPOSED;\n};\n\n/**\n * Displays full stack trace upon test failure.\n *\n * @public\n * @see [CLI option](../#-full-trace)\n * @param {boolean} [fullTrace=true] - Whether to print full stacktrace upon failure.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.fullTrace = function (fullTrace) {\n this.options.fullTrace = fullTrace !== false;\n return this;\n};\n\n/**\n * Specifies whitelist of variable names to be expected in global scope.\n *\n * @public\n * @see [CLI option](../#-global-variable-name)\n * @see {@link Mocha#checkLeaks}\n * @param {String[]|String} global - Accepted global variable name(s).\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Specify variables to be expected in global scope\n * mocha.global(['jQuery', 'MyLib']);\n */\nMocha.prototype.global = function (global) {\n this.options.global = (this.options.global || [])\n .concat(global)\n .filter(Boolean)\n .filter(function (elt, idx, arr) {\n return arr.indexOf(elt) === idx;\n });\n return this;\n};\n// for backwards compatibility, 'globals' is an alias of 'global'\nMocha.prototype.globals = Mocha.prototype.global;\n\n/**\n * Enables or disables TTY color output by screen-oriented reporters.\n *\n * @public\n * @see [CLI option](../#-color-c-colors)\n * @param {boolean} [color=true] - Whether to enable color output.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.color = function (color) {\n this.options.color = color !== false;\n return this;\n};\n\n/**\n * Enables or disables reporter to use inline diffs (rather than +/-)\n * in test failure output.\n *\n * @public\n * @see [CLI option](../#-inline-diffs)\n * @param {boolean} [inlineDiffs=true] - Whether to use inline diffs.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.inlineDiffs = function (inlineDiffs) {\n this.options.inlineDiffs = inlineDiffs !== false;\n return this;\n};\n\n/**\n * Enables or disables reporter to include diff in test failure output.\n *\n * @public\n * @see [CLI option](../#-diff)\n * @param {boolean} [diff=true] - Whether to show diff on failure.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.diff = function (diff) {\n this.options.diff = diff !== false;\n return this;\n};\n\n/**\n * @summary\n * Sets timeout threshold value.\n *\n * @description\n * A string argument can use shorthand (such as \"2s\") and will be converted.\n * If the value is `0`, timeouts will be disabled.\n *\n * @public\n * @see [CLI option](../#-timeout-ms-t-ms)\n * @see [Timeouts](../#timeouts)\n * @param {number|string} msecs - Timeout threshold value.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Sets timeout to one second\n * mocha.timeout(1000);\n * @example\n *\n * // Same as above but using string argument\n * mocha.timeout('1s');\n */\nMocha.prototype.timeout = function (msecs) {\n this.suite.timeout(msecs);\n return this;\n};\n\n/**\n * Sets the number of times to retry failed tests.\n *\n * @public\n * @see [CLI option](../#-retries-n)\n * @see [Retry Tests](../#retry-tests)\n * @param {number} retry - Number of times to retry failed tests.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Allow any failed test to retry one more time\n * mocha.retries(1);\n */\nMocha.prototype.retries = function (retry) {\n this.suite.retries(retry);\n return this;\n};\n\n/**\n * Sets slowness threshold value.\n *\n * @public\n * @see [CLI option](../#-slow-ms-s-ms)\n * @param {number} msecs - Slowness threshold value.\n * @return {Mocha} this\n * @chainable\n * @example\n *\n * // Sets \"slow\" threshold to half a second\n * mocha.slow(500);\n * @example\n *\n * // Same as above but using string argument\n * mocha.slow('0.5s');\n */\nMocha.prototype.slow = function (msecs) {\n this.suite.slow(msecs);\n return this;\n};\n\n/**\n * Forces all tests to either accept a `done` callback or return a promise.\n *\n * @public\n * @see [CLI option](../#-async-only-a)\n * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.asyncOnly = function (asyncOnly) {\n this.options.asyncOnly = asyncOnly !== false;\n return this;\n};\n\n/**\n * Disables syntax highlighting (in browser).\n *\n * @public\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.noHighlighting = function () {\n this.options.noHighlighting = true;\n return this;\n};\n\n/**\n * Enables or disables uncaught errors to propagate.\n *\n * @public\n * @see [CLI option](../#-allow-uncaught)\n * @param {boolean} [allowUncaught=true] - Whether to propagate uncaught errors.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.allowUncaught = function (allowUncaught) {\n this.options.allowUncaught = allowUncaught !== false;\n return this;\n};\n\n/**\n * @summary\n * Delays root suite execution.\n *\n * @description\n * Used to perform async operations before any suites are run.\n *\n * @public\n * @see [delayed root suite](../#delayed-root-suite)\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.delay = function delay() {\n this.options.delay = true;\n return this;\n};\n\n/**\n * Enables or disables running tests in dry-run mode.\n *\n * @public\n * @see [CLI option](../#-dry-run)\n * @param {boolean} [dryRun=true] - Whether to activate dry-run mode.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.dryRun = function (dryRun) {\n this.options.dryRun = dryRun !== false;\n return this;\n};\n\n/**\n * Fails test run if no tests encountered with exit-code 1.\n *\n * @public\n * @see [CLI option](../#-fail-zero)\n * @param {boolean} [failZero=true] - Whether to fail test run.\n * @return {Mocha} this\n * @chainable\n */\nMocha.prototype.failZero = function (failZero) {\n this.options.failZero = failZero !== false;\n return this;\n};\n\n/**\n * Causes tests marked `only` to fail the suite.\n *\n * @public\n * @see [CLI option](../#-forbid-only)\n * @param {boolean} [forbidOnly=true] - Whether tests marked `only` fail the suite.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.forbidOnly = function (forbidOnly) {\n this.options.forbidOnly = forbidOnly !== false;\n return this;\n};\n\n/**\n * Causes pending tests and tests marked `skip` to fail the suite.\n *\n * @public\n * @see [CLI option](../#-forbid-pending)\n * @param {boolean} [forbidPending=true] - Whether pending tests fail the suite.\n * @returns {Mocha} this\n * @chainable\n */\nMocha.prototype.forbidPending = function (forbidPending) {\n this.options.forbidPending = forbidPending !== false;\n return this;\n};\n\n/**\n * Throws an error if mocha is in the wrong state to be able to transition to a \"running\" state.\n * @private\n */\nMocha.prototype._guardRunningStateTransition = function () {\n if (this._state === mochaStates.RUNNING) {\n throw createMochaInstanceAlreadyRunningError(\n 'Mocha instance is currently running tests, cannot start a next test run until this one is done',\n this\n );\n }\n if (\n this._state === mochaStates.DISPOSED ||\n this._state === mochaStates.REFERENCES_CLEANED\n ) {\n throw createMochaInstanceAlreadyDisposedError(\n 'Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.',\n this._cleanReferencesAfterRun,\n this\n );\n }\n};\n\n/**\n * Mocha version as specified by \"package.json\".\n *\n * @name Mocha#version\n * @type string\n * @readonly\n */\nObject.defineProperty(Mocha.prototype, 'version', {\n value: require('../package.json').version,\n configurable: false,\n enumerable: true,\n writable: false\n});\n\n/**\n * Callback to be invoked when test execution is complete.\n *\n * @private\n * @callback DoneCB\n * @param {number} failures - Number of failures that occurred.\n */\n\n/**\n * Runs root suite and invokes `fn()` when complete.\n *\n * @description\n * To run tests multiple times (or to run tests in files that are\n * already in the `require` cache), make sure to clear them from\n * the cache first!\n *\n * @public\n * @see {@link Mocha#unloadFiles}\n * @see {@link Runner#run}\n * @param {DoneCB} [fn] - Callback invoked when test execution completed.\n * @returns {Runner} runner instance\n * @example\n *\n * // exit with non-zero status if there were test failures\n * mocha.run(failures => process.exitCode = failures ? 1 : 0);\n */\nMocha.prototype.run = function (fn) {\n this._guardRunningStateTransition();\n this._state = mochaStates.RUNNING;\n if (this._previousRunner) {\n this._previousRunner.dispose();\n this.suite.reset();\n }\n if (this.files.length && !this._lazyLoadFiles) {\n this.loadFiles();\n }\n var suite = this.suite;\n var options = this.options;\n options.files = this.files;\n const runner = new this._runnerClass(suite, {\n cleanReferencesAfterRun: this._cleanReferencesAfterRun,\n delay: options.delay,\n dryRun: options.dryRun,\n failZero: options.failZero\n });\n createStatsCollector(runner);\n var reporter = new this._reporter(runner, options);\n runner.checkLeaks = options.checkLeaks === true;\n runner.fullStackTrace = options.fullTrace;\n runner.asyncOnly = options.asyncOnly;\n runner.allowUncaught = options.allowUncaught;\n runner.forbidOnly = options.forbidOnly;\n runner.forbidPending = options.forbidPending;\n if (options.grep) {\n runner.grep(options.grep, options.invert);\n }\n if (options.global) {\n runner.globals(options.global);\n }\n if (options.color !== undefined) {\n exports.reporters.Base.useColors = options.color;\n }\n exports.reporters.Base.inlineDiffs = options.inlineDiffs;\n exports.reporters.Base.hideDiff = !options.diff;\n\n const done = failures => {\n this._previousRunner = runner;\n this._state = this._cleanReferencesAfterRun\n ? mochaStates.REFERENCES_CLEANED\n : mochaStates.INIT;\n fn = fn || utils.noop;\n if (typeof reporter.done === 'function') {\n reporter.done(failures, fn);\n } else {\n fn(failures);\n }\n };\n\n const runAsync = async runner => {\n const context =\n this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()\n ? await this.runGlobalSetup(runner)\n : {};\n const failureCount = await runner.runAsync({\n files: this.files,\n options\n });\n if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {\n await this.runGlobalTeardown(runner, {context});\n }\n return failureCount;\n };\n\n // no \"catch\" here is intentional. errors coming out of\n // Runner#run are considered uncaught/unhandled and caught\n // by the `process` event listeners.\n // also: returning anything other than `runner` would be a breaking\n // change\n runAsync(runner).then(done);\n\n return runner;\n};\n\n/**\n * Assigns hooks to the root suite\n * @param {MochaRootHookObject} [hooks] - Hooks to assign to root suite\n * @chainable\n */\nMocha.prototype.rootHooks = function rootHooks({\n beforeAll = [],\n beforeEach = [],\n afterAll = [],\n afterEach = []\n} = {}) {\n beforeAll = utils.castArray(beforeAll);\n beforeEach = utils.castArray(beforeEach);\n afterAll = utils.castArray(afterAll);\n afterEach = utils.castArray(afterEach);\n beforeAll.forEach(hook => {\n this.suite.beforeAll(hook);\n });\n beforeEach.forEach(hook => {\n this.suite.beforeEach(hook);\n });\n afterAll.forEach(hook => {\n this.suite.afterAll(hook);\n });\n afterEach.forEach(hook => {\n this.suite.afterEach(hook);\n });\n return this;\n};\n\n/**\n * Toggles parallel mode.\n *\n * Must be run before calling {@link Mocha#run}. Changes the `Runner` class to\n * use; also enables lazy file loading if not already done so.\n *\n * Warning: when passed `false` and lazy loading has been enabled _via any means_ (including calling `parallelMode(true)`), this method will _not_ disable lazy loading. Lazy loading is a prerequisite for parallel\n * mode, but parallel mode is _not_ a prerequisite for lazy loading!\n * @param {boolean} [enable] - If `true`, enable; otherwise disable.\n * @throws If run in browser\n * @throws If Mocha not in `INIT` state\n * @returns {Mocha}\n * @chainable\n * @public\n */\nMocha.prototype.parallelMode = function parallelMode(enable = true) {\n if (utils.isBrowser()) {\n throw createUnsupportedError('parallel mode is only supported in Node.js');\n }\n const parallel = Boolean(enable);\n if (\n parallel === this.options.parallel &&\n this._lazyLoadFiles &&\n this._runnerClass !== exports.Runner\n ) {\n return this;\n }\n if (this._state !== mochaStates.INIT) {\n throw createUnsupportedError(\n 'cannot change parallel mode after having called run()'\n );\n }\n this.options.parallel = parallel;\n\n // swap Runner class\n this._runnerClass = parallel\n ? require('./nodejs/parallel-buffered-runner')\n : exports.Runner;\n\n // lazyLoadFiles may have been set `true` otherwise (for ESM loading),\n // so keep `true` if so.\n return this.lazyLoadFiles(this._lazyLoadFiles || parallel);\n};\n\n/**\n * Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This\n * setting is used by watch mode, parallel mode, and for loading ESM files.\n * @todo This should throw if we've already loaded files; such behavior\n * necessitates adding a new state.\n * @param {boolean} [enable] - If `true`, disable eager loading of files in\n * {@link Mocha#run}\n * @chainable\n * @public\n */\nMocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {\n this._lazyLoadFiles = enable === true;\n debug('set lazy load to %s', enable);\n return this;\n};\n\n/**\n * Configures one or more global setup fixtures.\n *\n * If given no parameters, _unsets_ any previously-set fixtures.\n * @chainable\n * @public\n * @param {MochaGlobalFixture|MochaGlobalFixture[]} [setupFns] - Global setup fixture(s)\n * @returns {Mocha}\n */\nMocha.prototype.globalSetup = function globalSetup(setupFns = []) {\n setupFns = utils.castArray(setupFns);\n this.options.globalSetup = setupFns;\n debug('configured %d global setup functions', setupFns.length);\n return this;\n};\n\n/**\n * Configures one or more global teardown fixtures.\n *\n * If given no parameters, _unsets_ any previously-set fixtures.\n * @chainable\n * @public\n * @param {MochaGlobalFixture|MochaGlobalFixture[]} [teardownFns] - Global teardown fixture(s)\n * @returns {Mocha}\n */\nMocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {\n teardownFns = utils.castArray(teardownFns);\n this.options.globalTeardown = teardownFns;\n debug('configured %d global teardown functions', teardownFns.length);\n return this;\n};\n\n/**\n * Run any global setup fixtures sequentially, if any.\n *\n * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalSetup` option is `false`; see {@link Mocha#enableGlobalSetup}.\n *\n * The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.\n * @param {object} [context] - Context object if already have one\n * @public\n * @returns {Promise} Context object\n */\nMocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {\n const {globalSetup} = this.options;\n if (globalSetup && globalSetup.length) {\n debug('run(): global setup starting');\n await this._runGlobalFixtures(globalSetup, context);\n debug('run(): global setup complete');\n }\n return context;\n};\n\n/**\n * Run any global teardown fixtures sequentially, if any.\n *\n * This is _automatically called_ by {@link Mocha#run} _unless_ the `runGlobalTeardown` option is `false`; see {@link Mocha#enableGlobalTeardown}.\n *\n * Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.\n * @param {object} [context] - Context object if already have one\n * @public\n * @returns {Promise} Context object\n */\nMocha.prototype.runGlobalTeardown = async function runGlobalTeardown(\n context = {}\n) {\n const {globalTeardown} = this.options;\n if (globalTeardown && globalTeardown.length) {\n debug('run(): global teardown starting');\n await this._runGlobalFixtures(globalTeardown, context);\n }\n debug('run(): global teardown complete');\n return context;\n};\n\n/**\n * Run global fixtures sequentially with context `context`\n * @private\n * @param {MochaGlobalFixture[]} [fixtureFns] - Fixtures to run\n * @param {object} [context] - context object\n * @returns {Promise} context object\n */\nMocha.prototype._runGlobalFixtures = async function _runGlobalFixtures(\n fixtureFns = [],\n context = {}\n) {\n for await (const fixtureFn of fixtureFns) {\n await fixtureFn.call(context);\n }\n return context;\n};\n\n/**\n * Toggle execution of any global setup fixture(s)\n *\n * @chainable\n * @public\n * @param {boolean } [enabled=true] - If `false`, do not run global setup fixture\n * @returns {Mocha}\n */\nMocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) {\n this.options.enableGlobalSetup = Boolean(enabled);\n return this;\n};\n\n/**\n * Toggle execution of any global teardown fixture(s)\n *\n * @chainable\n * @public\n * @param {boolean } [enabled=true] - If `false`, do not run global teardown fixture\n * @returns {Mocha}\n */\nMocha.prototype.enableGlobalTeardown = function enableGlobalTeardown(\n enabled = true\n) {\n this.options.enableGlobalTeardown = Boolean(enabled);\n return this;\n};\n\n/**\n * Returns `true` if one or more global setup fixtures have been supplied.\n * @public\n * @returns {boolean}\n */\nMocha.prototype.hasGlobalSetupFixtures = function hasGlobalSetupFixtures() {\n return Boolean(this.options.globalSetup.length);\n};\n\n/**\n * Returns `true` if one or more global teardown fixtures have been supplied.\n * @public\n * @returns {boolean}\n */\nMocha.prototype.hasGlobalTeardownFixtures =\n function hasGlobalTeardownFixtures() {\n return Boolean(this.options.globalTeardown.length);\n };\n\n/**\n * An alternative way to define root hooks that works with parallel runs.\n * @typedef {Object} MochaRootHookObject\n * @property {Function|Function[]} [beforeAll] - \"Before all\" hook(s)\n * @property {Function|Function[]} [beforeEach] - \"Before each\" hook(s)\n * @property {Function|Function[]} [afterAll] - \"After all\" hook(s)\n * @property {Function|Function[]} [afterEach] - \"After each\" hook(s)\n */\n\n/**\n * An function that returns a {@link MochaRootHookObject}, either sync or async.\n @callback MochaRootHookFunction\n * @returns {MochaRootHookObject|Promise}\n */\n\n/**\n * A function that's invoked _once_ which is either sync or async.\n * Can be a \"teardown\" or \"setup\". These will all share the same context.\n * @callback MochaGlobalFixture\n * @returns {void|Promise}\n */\n\n/**\n * An object making up all necessary parts of a plugin loader and aggregator\n * @typedef {Object} PluginDefinition\n * @property {string} exportName - Named export to use\n * @property {string} [optionName] - Option name for Mocha constructor (use `exportName` if omitted)\n * @property {PluginValidator} [validate] - Validator function\n * @property {PluginFinalizer} [finalize] - Finalizer/aggregator function\n */\n\n/**\n * A (sync) function to assert a user-supplied plugin implementation is valid.\n *\n * Defined in a {@link PluginDefinition}.\n\n * @callback PluginValidator\n * @param {*} value - Value to check\n * @this {PluginDefinition}\n * @returns {void}\n */\n\n/**\n * A function to finalize plugins impls of a particular ilk\n * @callback PluginFinalizer\n * @param {Array<*>} impls - User-supplied implementations\n * @returns {Promise<*>|*}\n */\n","'use strict';\n\n/* eslint no-unused-vars: off */\n/* eslint-env commonjs */\n\n/**\n * Shim process.stdout.\n */\n\nprocess.stdout = require('browser-stdout')({label: false});\n\nvar parseQuery = require('./lib/browser/parse-query');\nvar highlightTags = require('./lib/browser/highlight-tags');\nvar Mocha = require('./lib/mocha');\n\n/**\n * Create a Mocha instance.\n *\n * @return {undefined}\n */\n\nvar mocha = new Mocha({reporter: 'html'});\n\n/**\n * Save timer references to avoid Sinon interfering (see GH-237).\n */\n\nvar Date = global.Date;\nvar setTimeout = global.setTimeout;\nvar setInterval = global.setInterval;\nvar clearTimeout = global.clearTimeout;\nvar clearInterval = global.clearInterval;\n\nvar uncaughtExceptionHandlers = [];\n\nvar originalOnerrorHandler = global.onerror;\n\n/**\n * Remove uncaughtException listener.\n * Revert to original onerror handler if previously defined.\n */\n\nprocess.removeListener = function (e, fn) {\n if (e === 'uncaughtException') {\n if (originalOnerrorHandler) {\n global.onerror = originalOnerrorHandler;\n } else {\n global.onerror = function () {};\n }\n var i = uncaughtExceptionHandlers.indexOf(fn);\n if (i !== -1) {\n uncaughtExceptionHandlers.splice(i, 1);\n }\n }\n};\n\n/**\n * Implements listenerCount for 'uncaughtException'.\n */\n\nprocess.listenerCount = function (name) {\n if (name === 'uncaughtException') {\n return uncaughtExceptionHandlers.length;\n }\n return 0;\n};\n\n/**\n * Implements uncaughtException listener.\n */\n\nprocess.on = function (e, fn) {\n if (e === 'uncaughtException') {\n global.onerror = function (err, url, line) {\n fn(new Error(err + ' (' + url + ':' + line + ')'));\n return !mocha.options.allowUncaught;\n };\n uncaughtExceptionHandlers.push(fn);\n }\n};\n\nprocess.listeners = function (e) {\n if (e === 'uncaughtException') {\n return uncaughtExceptionHandlers;\n }\n return [];\n};\n\n// The BDD UI is registered by default, but no UI will be functional in the\n// browser without an explicit call to the overridden `mocha.ui` (see below).\n// Ensure that this default UI does not expose its methods to the global scope.\nmocha.suite.removeAllListeners('pre-require');\n\nvar immediateQueue = [];\nvar immediateTimeout;\n\nfunction timeslice() {\n var immediateStart = new Date().getTime();\n while (immediateQueue.length && new Date().getTime() - immediateStart < 100) {\n immediateQueue.shift()();\n }\n if (immediateQueue.length) {\n immediateTimeout = setTimeout(timeslice, 0);\n } else {\n immediateTimeout = null;\n }\n}\n\n/**\n * High-performance override of Runner.immediately.\n */\n\nMocha.Runner.immediately = function (callback) {\n immediateQueue.push(callback);\n if (!immediateTimeout) {\n immediateTimeout = setTimeout(timeslice, 0);\n }\n};\n\n/**\n * Function to allow assertion libraries to throw errors directly into mocha.\n * This is useful when running tests in a browser because window.onerror will\n * only receive the 'message' attribute of the Error.\n */\nmocha.throwError = function (err) {\n uncaughtExceptionHandlers.forEach(function (fn) {\n fn(err);\n });\n throw err;\n};\n\n/**\n * Override ui to ensure that the ui functions are initialized.\n * Normally this would happen in Mocha.prototype.loadFiles.\n */\n\nmocha.ui = function (ui) {\n Mocha.prototype.ui.call(this, ui);\n this.suite.emit('pre-require', global, null, this);\n return this;\n};\n\n/**\n * Setup mocha with the given setting options.\n */\n\nmocha.setup = function (opts) {\n if (typeof opts === 'string') {\n opts = {ui: opts};\n }\n if (opts.delay === true) {\n this.delay();\n }\n var self = this;\n Object.keys(opts)\n .filter(function (opt) {\n return opt !== 'delay';\n })\n .forEach(function (opt) {\n if (Object.prototype.hasOwnProperty.call(opts, opt)) {\n self[opt](opts[opt]);\n }\n });\n return this;\n};\n\n/**\n * Run mocha, returning the Runner.\n */\n\nmocha.run = function (fn) {\n var options = mocha.options;\n mocha.globals('location');\n\n var query = parseQuery(global.location.search || '');\n if (query.grep) {\n mocha.grep(query.grep);\n }\n if (query.fgrep) {\n mocha.fgrep(query.fgrep);\n }\n if (query.invert) {\n mocha.invert();\n }\n\n return Mocha.prototype.run.call(mocha, function (err) {\n // The DOM Document is not available in Web Workers.\n var document = global.document;\n if (\n document &&\n document.getElementById('mocha') &&\n options.noHighlighting !== true\n ) {\n highlightTags('code');\n }\n if (fn) {\n fn(err);\n }\n });\n};\n\n/**\n * Expose the process shim.\n * https://github.com/mochajs/mocha/pull/916\n */\n\nMocha.process = process;\n\n/**\n * Expose mocha.\n */\nglobal.Mocha = Mocha;\nglobal.mocha = mocha;\n\n// for bundlers: enable `import {describe, it} from 'mocha'`\n// `bdd` interface only\n// prettier-ignore\n[ \n 'describe', 'context', 'it', 'specify',\n 'xdescribe', 'xcontext', 'xit', 'xspecify',\n 'before', 'beforeEach', 'afterEach', 'after'\n].forEach(function(key) {\n mocha[key] = global[key];\n});\n\nmodule.exports = mocha;\n"],"names":["global","defaultSetTimout","defaultClearTimeout","cachedSetTimeout","cachedClearTimeout","runTimeout","runClearTimeout","queue","draining","currentQueue","queueIndex","cleanUpNextTick","drainQueue","nextTick","Item","title","platform","browser","env","argv","version","versions","release","config","noop","on","addListener","once","off","removeListener","removeAllListeners","emit","binding","cwd","chdir","umask","performance","performanceNow","hrtime","startTime","uptime","require$$0","inherits","require$$1","process.nextTick","parseQuery","highlightTags","_base","_interopRequireDefault","_params","json","_line","array","parse","_parse","_toConsumableArray","_arrayWithoutHoles","_iterableToArray","_unsupportedIterableToArray","_nonIterableSpread","_arrayLikeToArray","merge_1","require$$2","require$$3","require$$4","require$$5","require$$6","require$$7","require$$8","require$$9","require$$10","require$$11","require$$12","require$$13","s","m","h","d","w","y","ms","fmtLong","fmtShort","plural","toString","base64.fromByteArray","ieee754.read","ieee754.write","base64.toByteArray","this","he","Buffer.isBuffer","process.browser","Pending","common","constants","createUnsupportedError","createMissingArgumentError","createInvalidArgumentTypeError","createInvalidExceptionError","createFatalError","createMultipleDoneError","createForbiddenExclusivityError","createTimeoutError","isMochaError","errors","EventEmitter","debug","utils","Date","setTimeout","clearTimeout","Runnable","MOCHA_ID_PROP_NAME","Suite","progress","require$$14","Test","EVENT_FILE_PRE_REQUIRE","bddModule","bdd","tddModule","tdd","qunitModule","qunit","exportsModule","exports","require$$15","require","require$$16"],"mappings":";;;;;;;;;;;AAAA,iBAAe,CAAC,OAAOA,QAAM,KAAK,WAAW,GAAGA,QAAM;EACtD,YAAY,OAAO,IAAI,KAAK,WAAW,GAAG,IAAI;EAC9C,YAAY,OAAO,MAAM,KAAK,WAAW,GAAG,MAAM,GAAG,EAAE;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ansion/.github/FUNDING.yml b/node_modules/mocha/node_modules/brace-expansion/.github/FUNDING.yml new file mode 100644 index 0000000..79d1eaf --- /dev/null +++ b/node_modules/mocha/node_modules/brace-expansion/.github/FUNDING.yml @@ -0,0 +1,2 @@ +tidelift: "npm/brace-expansion" +patreon: juliangruber diff --git a/node_modules/path-is-absolute/license b/node_modules/mocha/node_modules/brace-expansion/LICENSE similarity index 83% rename from node_modules/path-is-absolute/license rename to node_modules/mocha/node_modules/brace-expansion/LICENSE index 654d0bf..de32266 100644 --- a/node_modules/path-is-absolute/license +++ b/node_modules/mocha/node_modules/brace-expansion/LICENSE @@ -1,6 +1,6 @@ -The MIT License (MIT) +MIT License -Copyright (c) Sindre Sorhus (sindresorhus.com) +Copyright (c) 2013 Julian Gruber Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -9,13 +9,13 @@ 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 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. +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/mocha/node_modules/brace-expansion/README.md b/node_modules/mocha/node_modules/brace-expansion/README.md new file mode 100644 index 0000000..e55c583 --- /dev/null +++ b/node_modules/mocha/node_modules/brace-expansion/README.md @@ -0,0 +1,135 @@ +# brace-expansion + +[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html), +as known from sh/bash, in JavaScript. + +[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion) +[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion) +[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/) + +[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion) + +## Example + +```js +var expand = require('brace-expansion'); + +expand('file-{a,b,c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('-v{,,}') +// => ['-v', '-v', '-v'] + +expand('file{0..2}.jpg') +// => ['file0.jpg', 'file1.jpg', 'file2.jpg'] + +expand('file-{a..c}.jpg') +// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg'] + +expand('file{2..0}.jpg') +// => ['file2.jpg', 'file1.jpg', 'file0.jpg'] + +expand('file{0..4..2}.jpg') +// => ['file0.jpg', 'file2.jpg', 'file4.jpg'] + +expand('file-{a..e..2}.jpg') +// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg'] + +expand('file{00..10..5}.jpg') +// => ['file00.jpg', 'file05.jpg', 'file10.jpg'] + +expand('{{A..C},{a..c}}') +// => ['A', 'B', 'C', 'a', 'b', 'c'] + +expand('ppp{,config,oe{,conf}}') +// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf'] +``` + +## API + +```js +var expand = require('brace-expansion'); +``` + +### var expanded = expand(str) + +Return an array of all possible and valid expansions of `str`. If none are +found, `[str]` is returned. + +Valid expansions are: + +```js +/^(.*,)+(.+)?$/ +// {a,b,...} +``` + +A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +A numeric sequence from `x` to `y` inclusive, with optional increment. +If `x` or `y` start with a leading `0`, all the numbers will be padded +to have equal length. Negative numbers and backwards iteration work too. + +```js +/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/ +// {x..y[..incr]} +``` + +An alphabetic sequence from `x` to `y` inclusive, with optional increment. +`x` and `y` must be exactly one character, and if given, `incr` must be a +number. + +For compatibility reasons, the string `${` is not eligible for brace expansion. + +## Installation + +With [npm](https://npmjs.org) do: + +```bash +npm install brace-expansion +``` + +## Contributors + +- [Julian Gruber](https://github.com/juliangruber) +- [Isaac Z. Schlueter](https://github.com/isaacs) + +## Sponsors + +This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)! + +Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)! + +## Security contact information + +To report a security vulnerability, please use the +[Tidelift security contact](https://tidelift.com/security). +Tidelift will coordinate the fix and disclosure. + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +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. diff --git a/node_modules/mocha/node_modules/brace-expansion/index.js b/node_modules/mocha/node_modules/brace-expansion/index.js new file mode 100644 index 0000000..4af9dde --- /dev/null +++ b/node_modules/mocha/node_modules/brace-expansion/index.js @@ -0,0 +1,203 @@ +var balanced = require('balanced-match'); + +module.exports = expandTop; + +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; + +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} + +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} + +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} + + +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + + var parts = []; + var m = balanced('{', '}', str); + + if (!m) + return str.split(','); + + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); + + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } + + parts.push.apply(parts, p); + + return parts; +} + +function expandTop(str) { + if (!str) + return []; + + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); + } + + return expand(escapeBraces(str), true).map(unescapeBraces); +} + +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} + +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} + +function expand(str, isTop) { + var expansions = []; + + var m = balanced('{', '}', str); + if (!m) return [str]; + + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; + + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; + } + + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } + + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; + + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); + + N = []; + + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; + + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } + + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } + } + + return expansions; +} + diff --git a/node_modules/mocha/node_modules/brace-expansion/package.json b/node_modules/mocha/node_modules/brace-expansion/package.json new file mode 100644 index 0000000..7097d41 --- /dev/null +++ b/node_modules/mocha/node_modules/brace-expansion/package.json @@ -0,0 +1,46 @@ +{ + "name": "brace-expansion", + "description": "Brace expansion as known from sh/bash", + "version": "2.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/brace-expansion.git" + }, + "homepage": "https://github.com/juliangruber/brace-expansion", + "main": "index.js", + "scripts": { + "test": "tape test/*.js", + "gentest": "bash test/generate.sh", + "bench": "matcha test/perf/bench.js" + }, + "dependencies": { + "balanced-match": "^1.0.0" + }, + "devDependencies": { + "@c4312/matcha": "^1.3.1", + "tape": "^4.6.0" + }, + "keywords": [], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "testling": { + "files": "test/*.js", + "browsers": [ + "ie/8..latest", + "firefox/20..latest", + "firefox/nightly", + "chrome/25..latest", + "chrome/canary", + "opera/12..latest", + "opera/next", + "safari/5.1..latest", + "ipad/6.0..latest", + "iphone/6.0..latest", + "android-browser/4.2..latest" + ] + } +} diff --git a/node_modules/mocha/node_modules/minimatch/LICENSE b/node_modules/mocha/node_modules/minimatch/LICENSE index 19129e3..9517b7d 100644 --- a/node_modules/mocha/node_modules/minimatch/LICENSE +++ b/node_modules/mocha/node_modules/minimatch/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) Isaac Z. Schlueter and Contributors +Copyright (c) 2011-2022 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above diff --git a/node_modules/mocha/node_modules/minimatch/README.md b/node_modules/mocha/node_modules/minimatch/README.md index ad72b81..7c55391 100644 --- a/node_modules/mocha/node_modules/minimatch/README.md +++ b/node_modules/mocha/node_modules/minimatch/README.md @@ -2,7 +2,7 @@ A minimal matching utility. -[![Build Status](https://secure.travis-ci.org/isaacs/minimatch.svg)](http://travis-ci.org/isaacs/minimatch) +[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch) This is the matching library used internally by npm. @@ -35,6 +35,20 @@ See: * `man 3 fnmatch` * `man 5 gitignore` +## Windows + +**Please only use forward-slashes in glob expressions.** + +Though windows uses either `/` or `\` as its path separator, only `/` +characters are used by this glob implementation. You must use +forward-slashes **only** in glob expressions. Back-slashes in patterns +will always be interpreted as escape characters, not path separators. + +Note that `\` or `/` _will_ be interpreted as path separators in paths on +Windows, and will match against `/` in glob expressions. + +So just always use `/` in patterns. + ## Minimatch Class Create a minimatch object by instantiating the `minimatch.Minimatch` class. @@ -171,6 +185,21 @@ Suppress the behavior of treating a leading `!` character as negation. Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) +### partial + +Compare a partial path to a pattern. As long as the parts of the path that +are present are not contradicted by the pattern, it will be treated as a +match. This is useful in applications where you're walking through a +folder structure, and don't yet have the full path, but want to ensure that +you do not walk down paths that can never be a match. + +For example, + +```js +minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d +minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d +minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a +``` ## Comparisons to other fnmatch/glob implementations @@ -207,3 +236,9 @@ other interpretation of the glob pattern. Thus, a pattern like `+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded **first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are checked for validity. Since those two are valid, matching proceeds. + +Note that `fnmatch(3)` in libc is an extremely naive string comparison +matcher, which does not do anything special for slashes. This library is +designed to be used in glob searching and file walkers, and so it does do +special things with `/`. Thus, `foo*` will not match `foo/bar` in this +library, even though it would in `fnmatch(3)`. diff --git a/node_modules/mocha/node_modules/minimatch/lib/path.js b/node_modules/mocha/node_modules/minimatch/lib/path.js new file mode 100644 index 0000000..ffe453d --- /dev/null +++ b/node_modules/mocha/node_modules/minimatch/lib/path.js @@ -0,0 +1,4 @@ +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } diff --git a/node_modules/mocha/node_modules/minimatch/minimatch.js b/node_modules/mocha/node_modules/minimatch/minimatch.js index 5b5f8cf..f3b491d 100644 --- a/node_modules/mocha/node_modules/minimatch/minimatch.js +++ b/node_modules/mocha/node_modules/minimatch/minimatch.js @@ -1,15 +1,24 @@ +const minimatch = module.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern) + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) +} + module.exports = minimatch -minimatch.Minimatch = Minimatch -var path = { sep: '/' } -try { - path = require('path') -} catch (er) {} +const path = require('./lib/path.js') +minimatch.sep = path.sep -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = require('brace-expansion') +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = require('brace-expansion') -var plTypes = { +const plTypes = { '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, '?': { open: '(?:', close: ')?' }, '+': { open: '(?:', close: ')+' }, @@ -19,442 +28,579 @@ var plTypes = { // any single thing other than / // don't need to escape / when using new RegExp() -var qmark = '[^/]' +const qmark = '[^/]' // * => any number of characters -var star = qmark + '*?' +const star = qmark + '*?' // ** when dots are allowed. Anything goes, except .. and . // not (^ or / followed by one or two dots followed by $ or /), // followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' // not a ^ or / followed by a dot, // followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' + +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) // characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') +const reSpecials = charSet('().*{}+?[]^$\\!') -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') // normalizes slashes. -var slashSplit = /\/+/ +const slashSplit = /\/+/ -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} +minimatch.filter = (pattern, options = {}) => + (p, i, list) => minimatch(p, pattern, options) -function ext (a, b) { - a = a || {} - b = b || {} - var t = {} - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) +const ext = (a, b = {}) => { + const t = {} + Object.keys(a).forEach(k => t[k] = a[k]) + Object.keys(b).forEach(k => t[k] = b[k]) return t } -minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return minimatch - - var orig = minimatch - - var m = function minimatch (p, pattern, options) { - return orig.minimatch(p, pattern, ext(def, options)) +minimatch.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) + const orig = minimatch + + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)) + } } + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) + m.defaults = options => orig.defaults(ext(def, options)) + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) return m } -Minimatch.defaults = function (def) { - if (!def || !Object.keys(def).length) return Minimatch - return minimatch.defaults(def).Minimatch -} -function minimatch (p, pattern, options) { - if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') - } - if (!options) options = {} - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } - // "" only matches "" - if (pattern.trim() === '') return p === '' +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) - return new Minimatch(pattern, options).match(p) -} +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern) -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] } + return expand(pattern) +} + +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { if (typeof pattern !== 'string') { - throw new TypeError('glob pattern string required') + throw new TypeError('invalid pattern') } - if (!options) options = {} - pattern = pattern.trim() - - // windows support: need to use /, not \ - if (path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') } +} - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse') - // make the set of regexps etc. - this.make() +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() + +minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options) + list = list.filter(f => mm.match(f)) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list } -Minimatch.prototype.debug = function () {} +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -Minimatch.prototype.make = make -function make () { - // don't do it more than once. - if (this._made) return +class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern) - var pattern = this.pattern - var options = this.options + if (!options) options = {} - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return + this.options = options + this.set = [] + this.pattern = pattern + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial + + // make the set of regexps etc. + this.make() } - // step 1: figure out negation, etc. - this.parseNegate() + debug () {} - // step 2: expand braces - var set = this.globSet = this.braceExpand() + make () { + const pattern = this.pattern + const options = this.options - if (options.debug) this.debug = console.error + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } - this.debug(this.pattern, set) + // step 1: figure out negation, etc. + this.parseNegate() - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) + // step 2: expand braces + let set = this.globSet = this.braceExpand() - this.debug(this.pattern, set) + if (options.debug) this.debug = (...args) => console.error(...args) - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + this.debug(this.pattern, set) - this.debug(this.pattern, set) + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)) - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + this.debug(this.pattern, set) - this.debug(this.pattern, set) + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) - this.set = set -} + this.debug(this.pattern, set) -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) - if (options.nonegate) return + this.debug(this.pattern, set) - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ + this.set = set } - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} - -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + parseNegate () { + if (this.options.nonegate) return -Minimatch.prototype.braceExpand = braceExpand + const pattern = this.pattern + let negate = false + let negateOffset = 0 -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ } - } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + if (negateOffset) this.pattern = pattern.substr(negateOffset) + this.negate = negate + } + + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options + + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) + + this.debug('matchOne', file.length, pattern.length) + + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] + + this.debug(pattern, p, f) + + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false + + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) + + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } - if (typeof pattern === 'undefined') { - throw new TypeError('undefined pattern') - } + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] + + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } + + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } - if (options.nobrace || - !pattern.match(/\{.*\}/)) { - // shortcut. no need to expand. - return [pattern] - } + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } - return expand(pattern) -} + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - if (pattern.length > 1024 * 64) { - throw new TypeError('pattern is too long') - } + if (!hit) return false + } - var options = this.options - - // shortcuts - if (!options.noglobstar && pattern === '**') return GLOBSTAR - if (pattern === '') return '' - - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this - - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* + + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') } + + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } + + braceExpand () { + return braceExpand(this.pattern, this.options) } - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) + parse (pattern, isSub) { + assertValidPattern(pattern) + + const options = this.options - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' + + let re = '' + let hasMagic = !!options.nocase + let escaping = false + // ? => one single character + const patternListStack = [] + const negativeLists = [] + let stateChar + let inClass = false + let reClassStart = -1 + let classStart = -1 + let cs + let pl + let sp + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. + const patternStart = pattern.charAt(0) === '.' ? '' // anything + // not (start or / followed by . or .. followed by / or end) + : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' + : '(?!\\.)' + + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + this.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } } - switch (c) { - case '/': - // completely not allowed, even escaped. - // Should already be path-split by now. - return false + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) - case '\\': - clearStateChar() - escaping = true - continue - - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) - - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false } - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue - - case '(': - if (inClass) { - re += '(' - continue + if (reSpecials[c]) { + re += '\\' } + re += c + escaping = false + continue + } - if (!stateChar) { - re += '\\(' - continue + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue + case '\\': + clearStateChar() + escaping = true + continue - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue - - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + + case '(': + if (inClass) { + re += '(' + continue + } - clearStateChar() - re += '|' - continue + if (!stateChar) { + re += '\\(' + continue + } - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + patternListStack.push({ + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close + }) + // negation is (?:(?!js)[^/]*) + re += stateChar === '!' ? '(?:(?!(?:' : '(?:' + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + + case ')': + if (inClass || !patternListStack.length) { + re += '\\)' + continue + } - if (inClass) { - re += '\\' + c - continue - } + clearStateChar() + hasMagic = true + pl = patternListStack.pop() + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(pl) + } + pl.reEnd = re.length + continue - inClass = true - classStart = i - reClassStart = re.length - re += c - continue - - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue - } + case '|': + if (inClass || !patternListStack.length) { + re += '\\|' + continue + } + + clearStateChar() + re += '|' + continue + + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() + + if (inClass) { + re += '\\' + c + continue + } - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - if (inClass) { + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + continue + } + + // handle the case where we left a class open. + // "[z-a]" is valid, equivalent to "\[z-a\]" // split where the last [ was, make sure we don't have // an invalid re. if so, re-walk the contents of the // would-be class to re-translate any characters that @@ -462,462 +608,294 @@ function parse (pattern, isSub) { // TODO: It would probably be faster to determine this // without a try/catch and a new RegExp, but it's tricky // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) + cs = pattern.substring(classStart + 1, i) try { RegExp('[' + cs + ']') } catch (er) { // not a valid class! - var sp = this.parse(cs, SUBPARSE) + sp = this.parse(cs, SUBPARSE) re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' hasMagic = hasMagic || sp[1] inClass = false continue } - } - - // finish up the class. - hasMagic = true - inClass = false - re += c - continue - default: - // swallow any state char that wasn't consumed - clearStateChar() + // finish up the class. + hasMagic = true + inClass = false + re += c + continue - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' - } + default: + // swallow any state char that wasn't consumed + clearStateChar() - re += c + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } + re += c + break + + } // switch + } // for + + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.substr(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substr(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] + } - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail + tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) + + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type + + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '.': - case '[': - case '(': addPatternStart = true - } + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)] + + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n] + + const nlBefore = re.slice(0, nl.reStart) + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + let nlAfter = re.slice(nl.reEnd) + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter + + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const openParensBefore = nlBefore.split('(').length - 1 + let cleanAfter = nlAfter + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] - - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) - - nlLast += nlAfter - - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : '' + re = nlBefore + nlFirst + nlAfter + dollar + nlLast } - nlAfter = cleanAfter - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } + if (addPatternStart) { + re = patternStart + re + } - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') + const flags = options.nocase ? 'i' : '' + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') + } } - regExp._glob = pattern - regExp._src = re + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp - return regExp -} + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + if (!set.length) { + this.regexp = false + return this.regexp + } + const options = this.options + + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' + + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set.push(p) + } + return set + }, []) + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] + } else { + pattern[i] = twoStar + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?' + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] + pattern[i+1] = GLOBSTAR + } + }) + return pattern.filter(p => p !== GLOBSTAR).join('/') + }).join('|') -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' - if (!set.length) { - this.regexp = false + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } return this.regexp } - var options = this.options - - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' - - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') - - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' - - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' - - try { - this.regexp = new RegExp(re, flags) - } catch (ex) { - this.regexp = false - } - return this.regexp -} - -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} - -Minimatch.prototype.match = match -function match (f, partial) { - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' - - if (f === '/' && partial) return true - - var options = this.options - - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } - - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + match (f, partial = this.partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' - var set = this.set - this.debug(this.pattern, 'set', set) + if (f === '/' && partial) return true - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + const options = this.options - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') } - } - - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} - -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options - - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) - - this.debug('matchOne', file.length, pattern.length) - - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - if (p === false) return false - - if (p === GLOBSTAR) { - this.debug('GLOBSTAR', [pattern, p, f]) - - // "**" - // a/**/b/**/c would match the following: - // a/b/x/y/z/c - // a/x/y/z/b/c - // a/b/x/b/x/c - // a/b/c - // To do this, take the rest of the pattern after - // the **, and see if it would match the file remainder. - // If so, return success. - // If not, the ** "swallows" a segment, and try again. - // This is recursively awful. - // - // a/**/b/**/c matching a/b/x/y/z/c - // - a matches a - // - doublestar - // - matchOne(b/x/y/z/c, b/**/c) - // - b matches b - // - doublestar - // - matchOne(x/y/z/c, c) -> no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } - - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + const set = this.set + this.debug(this.pattern, 'set', set) - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false + // Find the basename of the path by looking for the last non-empty segment + let filename + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break } - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - if (options.nocase) { - hit = f.toLowerCase() === p.toLowerCase() - } else { - hit = f === p + for (let i = 0; i < set.length; i++) { + const pattern = set[i] + let file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + const hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate } - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) } - if (!hit) return false + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate } - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* - - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - var emptyFileEnd = (fi === fl - 1) && (file[fi] === '') - return emptyFileEnd + static defaults (def) { + return minimatch.defaults(def).Minimatch } - - // should be unreachable. - throw new Error('wtf?') } -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} +minimatch.Minimatch = Minimatch diff --git a/node_modules/mocha/node_modules/minimatch/package.json b/node_modules/mocha/node_modules/minimatch/package.json index c4514c8..2cc8569 100644 --- a/node_modules/mocha/node_modules/minimatch/package.json +++ b/node_modules/mocha/node_modules/minimatch/package.json @@ -2,29 +2,31 @@ "author": "Isaac Z. Schlueter (http://blog.izs.me)", "name": "minimatch", "description": "a glob matcher in javascript", - "version": "3.0.4", + "version": "5.0.1", "repository": { "type": "git", "url": "git://github.com/isaacs/minimatch.git" }, "main": "minimatch.js", "scripts": { - "test": "tap test/*.js --cov", + "test": "tap", + "snap": "tap", "preversion": "npm test", "postversion": "npm publish", - "postpublish": "git push origin --all; git push origin --tags" + "prepublishOnly": "git push origin --follow-tags" }, "engines": { - "node": "*" + "node": ">=10" }, "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^2.0.1" }, "devDependencies": { - "tap": "^10.3.2" + "tap": "^15.1.6" }, "license": "ISC", "files": [ - "minimatch.js" + "minimatch.js", + "lib" ] } diff --git a/node_modules/mocha/package.json b/node_modules/mocha/package.json index d29216f..ed5d6ea 100644 --- a/node_modules/mocha/package.json +++ b/node_modules/mocha/package.json @@ -1,6 +1,7 @@ { "name": "mocha", - "version": "8.4.0", + "version": "10.4.0", + "type": "commonjs", "description": "simple, flexible, fun test framework", "keywords": [ "mocha", @@ -17,10 +18,6 @@ "jasmine", "karma" ], - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/mochajs" - }, "author": "TJ Holowaychuk ", "license": "MIT", "repository": { @@ -30,11 +27,12 @@ "bugs": { "url": "https://github.com/mochajs/mocha/issues/" }, + "discord": "https://discord.gg/KeDn2uXhER", "homepage": "https://mochajs.org/", "logo": "https://cldup.com/S9uQ-cOLYz.svg", "notifyLogo": "https://ibin.co/4QuRuGjXvl36.png", "bin": { - "mocha": "./bin/mocha", + "mocha": "./bin/mocha.js", "_mocha": "./bin/_mocha" }, "directories": { @@ -42,9 +40,10 @@ "test": "./test" }, "engines": { - "node": ">= 10.12.0" + "node": ">= 14.0.0" }, "scripts": { + "lint": "npx eslint . --max-warnings 0", "prepublishOnly": "nps test clean build", "start": "nps", "test": "nps test", @@ -52,103 +51,81 @@ "test:smoke": "node ./bin/mocha --no-config test/smoke/smoke.spec.js" }, "dependencies": { - "@ungap/promise-all-settled": "1.1.2", "ansi-colors": "4.1.1", "browser-stdout": "1.3.1", - "chokidar": "3.5.1", - "debug": "4.3.1", + "chokidar": "3.5.3", + "debug": "4.3.4", "diff": "5.0.0", "escape-string-regexp": "4.0.0", "find-up": "5.0.0", - "glob": "7.1.6", - "growl": "1.10.5", + "glob": "8.1.0", "he": "1.2.0", - "js-yaml": "4.0.0", - "log-symbols": "4.0.0", - "minimatch": "3.0.4", + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "5.0.1", "ms": "2.1.3", - "nanoid": "3.1.20", - "serialize-javascript": "5.0.1", + "serialize-javascript": "6.0.0", "strip-json-comments": "3.1.1", "supports-color": "8.1.1", - "which": "2.0.2", - "wide-align": "1.1.3", - "workerpool": "6.1.0", + "workerpool": "6.2.1", "yargs": "16.2.0", "yargs-parser": "20.2.4", "yargs-unparser": "2.0.0" }, "devDependencies": { - "@11ty/eleventy": "^0.11.0", - "@11ty/eleventy-plugin-inclusive-language": "^1.0.0", - "@babel/preset-env": "^7.12.17", - "@mocha/docdash": "^3.0.1", - "@rollup/plugin-babel": "^5.1.0", - "@rollup/plugin-commonjs": "^14.0.0", + "@11ty/eleventy": "^1.0.0", + "@11ty/eleventy-plugin-inclusive-language": "^1.0.3", + "@eslint/js": "^8.56.0", + "@mocha/docdash": "^4.0.1", + "@rollup/plugin-commonjs": "^21.0.2", "@rollup/plugin-json": "^4.1.0", - "@rollup/plugin-multi-entry": "^3.0.1", - "@rollup/plugin-node-resolve": "^8.4.0", - "assetgraph-builder": "^8.1.0", + "@rollup/plugin-multi-entry": "^4.0.1", + "@rollup/plugin-node-resolve": "^13.1.3", + "assetgraph-builder": "^9.0.0", "autoprefixer": "^9.8.6", - "babel-eslint": "^10.1.0", - "canvas": "^2.6.1", - "chai": "^4.2.0", - "coffee-script": "^1.12.7", - "configstore": "^5.0.1", - "core-js": "^3.6.5", - "coveralls": "^3.1.0", + "canvas": "^2.11.2", + "chai": "^4.3.4", + "coffeescript": "^2.6.1", + "coveralls": "^3.1.1", "cross-env": "^7.0.2", - "cross-spawn": "^7.0.3", - "eslint": "^7.8.1", - "eslint-config-prettier": "^6.11.0", - "eslint-config-semistandard": "^15.0.1", - "eslint-config-standard": "^14.1.1", - "eslint-plugin-import": "^2.22.0", - "eslint-plugin-node": "^11.0.0", - "eslint-plugin-prettier": "^3.1.4", - "eslint-plugin-promise": "^4.2.1", - "eslint-plugin-standard": "^4.0.1", + "eslint": "^8.56.0", "fail-on-errors-webpack-plugin": "^3.0.0", - "fs-extra": "^9.0.1", + "fs-extra": "^10.0.0", + "globals": "^13.24.0", "husky": "^4.2.5", - "hyperlink": "^4.5.2", - "jsdoc": "^3.6.5", - "jsdoc-ts-utils": "^1.1.2", - "karma": "^5.1.1", - "karma-chrome-launcher": "^3.1.0", + "hyperlink": "^5.0.4", + "jsdoc": "^3.6.7", + "jsdoc-ts-utils": "^2.0.1", + "karma": "^6.4.2", + "karma-chrome-launcher": "^3.2.0", "karma-mocha": "^2.0.1", "karma-mocha-reporter": "^2.2.5", - "karma-requirejs": "^1.1.0", - "karma-sauce-launcher": "^4.3.4", + "karma-sauce-launcher": "^4.3.6", "lint-staged": "^10.2.11", - "markdown-it": "^11.0.0", - "markdown-it-anchor": "^5.3.0", - "markdown-it-attrs": "^3.0.3", - "markdown-it-emoji": "^1.4.0", - "markdown-it-prism": "^2.1.1", + "markdown-it": "^12.3.2", + "markdown-it-anchor": "^8.4.1", + "markdown-it-attrs": "^4.1.3", + "markdown-it-emoji": "^2.0.0", + "markdown-it-prism": "^2.2.2", "markdown-toc": "^1.2.0", - "markdownlint-cli": "^0.23.2", + "markdownlint-cli": "^0.30.0", "needle": "^2.5.0", "nps": "^5.10.0", "nyc": "^15.1.0", "pidtree": "^0.5.0", - "prettier": "^1.19.1", - "remark": "^12.0.1", - "remark-github": "^9.0.1", - "remark-inline-links": "^4.0.0", - "requirejs": "^2.3.6", + "prettier": "^2.4.1", + "remark": "^14.0.2", + "remark-github": "^11.2.2", + "remark-inline-links": "^6.0.1", "rewiremock": "^3.14.3", "rimraf": "^3.0.2", - "rollup": "^2.23.1", + "rollup": "^2.70.1", "rollup-plugin-node-globals": "^1.4.0", - "rollup-plugin-node-polyfills": "^0.2.1", - "rollup-plugin-visualizer": "^4.1.0", + "rollup-plugin-polyfill-node": "^0.8.0", + "rollup-plugin-visualizer": "^5.6.0", "sinon": "^9.0.3", "strip-ansi": "^6.0.0", "svgo": "^1.3.2", - "through2": "^4.0.2", - "to-vfile": "^6.1.0", - "touch": "^3.1.0", "unexpected": "^11.14.0", "unexpected-eventemitter": "^2.2.0", "unexpected-map": "^2.0.0", @@ -156,14 +133,11 @@ "unexpected-sinon": "^10.11.2", "update-notifier": "^4.1.0", "uslug": "^1.0.4", - "uuid": "^8.3.0", - "watchify": "^3.11.1", - "webpack": "^4.44.1", - "webpack-cli": "^3.3.12" + "webpack": "^5.67.0", + "webpack-cli": "^4.9.1" }, "files": [ - "bin/*mocha", - "assets/growl/*.png", + "bin/*mocha*", "lib/**/*.{js,html,json}", "index.js", "mocha.css", @@ -173,25 +147,28 @@ ], "browser": { "./index.js": "./browser-entry.js", - "./lib/nodejs/growl.js": "./lib/browser/growl.js", - "./lib/esm-utils.js": false, "fs": false, "path": false, "supports-color": false, - "./lib/nodejs/serializer.js": false, - "./lib/nodejs/worker.js": false, "./lib/nodejs/buffered-worker-pool.js": false, + "./lib/nodejs/esm-utils.js": false, + "./lib/nodejs/file-unloader.js": false, "./lib/nodejs/parallel-buffered-runner.js": false, + "./lib/nodejs/serializer.js": false, + "./lib/nodejs/worker.js": false, "./lib/nodejs/reporters/parallel-buffered.js": false, - "./lib/nodejs/file-unloader.js": false, "./lib/cli/index.js": false }, "prettier": { - "singleQuote": true, + "arrowParens": "avoid", "bracketSpacing": false, - "endOfLine": "auto" + "endOfLine": "auto", + "singleQuote": true, + "trailingComma": "none" + }, + "overrides": { + "webdriverio": "^7.33.0" }, - "gitter": "https://gitter.im/mochajs/mocha", "husky": { "hooks": { "pre-commit": "lint-staged" diff --git a/node_modules/nanoid/CHANGELOG.md b/node_modules/nanoid/CHANGELOG.md deleted file mode 100644 index 8d460e3..0000000 --- a/node_modules/nanoid/CHANGELOG.md +++ /dev/null @@ -1,241 +0,0 @@ -# Change Log -This project adheres to [Semantic Versioning](http://semver.org/). - -## 3.1.20 -* Fix ES modules support. - -## 3.1.19 -* Reduced `customAlphabet` size (by Enrico Scherlies). - -## 3.1.18 -* Fixed `package.exports`. - -## 3.1.17 -* Added files without `process`. - -## 3.1.16 -* Speeded up Nano ID 4 times (by Peter Boyer). - -## 3.1.15 -* Fixed `package.types` path. - -## 3.1.14 -* Added `package.types`. - -## 3.1.13 -* Removed Node.js 15.0.0 with `randomFillSync` regression from `engines.node`. - -## 3.1.12 -* Improved IE 11 docs. - -## 3.1.11 -* Fixed asynchronous `customAlphabet` in browser (by @LoneRifle). - -## 3.1.10 -* Fix ES modules support. - -## 3.1.9 -* Try to fix React Native Expo support. - -## 3.1.8 -* Add React Native Expo support. - -## 3.1.7 -* Clean up code. - -## 3.1.6 -* Avoid `self` using. - -## 3.1.5 -* Improve IE docs and warning. - -## 3.1.4 -* Restrict old Node.js 13 by `engines.node` (by Cansin Yildiz). - -## 3.1.3 -* Fix ES modules issue with CLI. - -## 3.1.2 -* Add shebang to CLI. - -## 3.1.1 -* Fix CLI. - -## 3.1 -* Add `npx nanoid` CLI. - -## 3.0.2 -* Fix docs (by Dylan Irlbeck ). - -## 3.0.1 -* Fix React Native warning on `non-secure` import (by Jia Huang). - -## 3.0 -**Migration guide:** -* Move to ES2016 syntax. You need to use Babel for IE 11. -* Move to named exports `import { nanoid } from 'nanoid'`. -* Move `import url from 'nanoid/url'` to `import { urlAlphabet } from 'nanoid'`. -* Replace `format()` to `customRandom()`. -* Replace `generate()` to `customAlphabet()`. -* Remove `async/format`. -* Remove React Native support for `nanoid/async`. -* Add `nanoid.js` to use directly in browser from CDN. -* Add TypeScript type definitions. -* Add ES modules support for bundlers, Node.js, and React Native. -* Fix React Native support. -* Reduce size. -* Improve docs (by Dair Aidarkhanov). - -## 2.1.11 -* Reduce size (by Anton Evzhakov). - -## 2.1.10 -* Reduce size by 10% (by Anton Khlynovskiy). - -## 2.1.9 -* Reduce `format` and `async/format` size (by Dair Aidarkhanov). - -## 2.1.8 -* Improve React docs (by Nahum Zsilva). - -## 2.1.7 -* Reduce `index`, `async` and `non-secure` size (by @polemius). - -## 2.1.6 -* Reduce size (by Stas Lashmanov). -* Return fast mask for Node.js. - -## 2.1.5 -* Reduce size (by Max Graey). -* Fix IE support. - -## 2.1.4 -* Reduce `generate` size (by Vsevolod Rodionov). -* Reduce `format` and `format` size (by Victor). -* Reduce `async`, `non-secure` and `non-secure/generate` size. -* Speed up `format` and `async/format` (by Max Graey). -* Improve development process on Windows (by Stanislav Lashmanov). - -## 2.1.3 -* Improve performance (by Stephen Richardson). -* Reduce size (by Stephen Richardson). - -## 2.1.2 -* Improve docs. - -## 2.1.1 -* Fix React Native support (by Shawn Hwei). - -## 2.1 -* Improve React Native support (by Sebastian Werner). - -## 2.0.4 -* Improve error text for React Native (by Sebastian Werner). - -## 2.0.3 -* Fix freeze on string in ID length. - -## 2.0.2 -* Improve docs (by Sylvanus Kateile and Mark Stosberg). - -## 2.0.1 -* Reduce npm package size. -* Mark package as not having side effects (by @xiaody). - -## 2.0 -* Use `-` instead of `~` in default alphabet to by file name safe. -* Add `nanoid/non-secure/generate`. - -## 1.3.4 -* Reduce `non-secure` size. -* Add `async` callback type check. - -## 1.3.3 -* Fix `nanoid/async` performance regression. -* Fix old Node.js `not seeded` issue in synchronous version too. - -## 1.3.2 -* Fix random generator `not seeded` issue of old Node.js. - -## 1.3.1 -* Reduce library size. - -## 1.3 -* Add `nanoid/async/format` and `nanoid/async/generate`. -* Improve synchronous API performance. -* Reduce `url` size (by Daniil Poroshin). -* Improve React Native docs (by joelgetaction). - -## 1.2.6 -* Reduce library size (by rqrqrqrq). - -## 1.2.5 -* Fix Node.js 6.11.1 support (by Andrey Belym). - -## 1.2.4 -* Speed up Node.js secure generators (by Dmitriy Tsvettsikh). - -## 1.2.3 -* Fix JSDoc (by Hendry Sadrak). - -## 1.2.2 -* Fix distribution in `nanoid/non-secure` (by Eatall). - -## 1.2.1 -* Fix old Node.js support. - -## 1.2 -* Add `nanoid/async`. -* Fix `nanoid/non-secure` JSDoc. -* Add Chinese documentation (by Wenliang Dai). -* Speed up and reduce size of `nanoid/non-secure` (by Ori Livni). - -## 1.1.1 -* Improve performance and reduce size of non-secure ID generator. - -## 1.1 -* Add non-secure ID generator. -* Suggest to use non-secure ID generator for React Native developers. -* Reduce size. - -## 1.0.7 -* Fix documentation. - -## 1.0.6 -* Fix documentation. - -## 1.0.5 -* Reduce `nanoid/index` size (by Anton Khlynovskiy). - -## 1.0.4 -* Reduce npm package size. - -## 1.0.3 -* Reduce npm package size. - -## 1.0.2 -* Fix Web Workers support (by Zachary Golba). - -## 1.0.1 -* Reduce `nanoid/index` size (by Anton Khlynovskiy). - -## 1.0 -* Use 21 symbols by default (by David Klebanoff). - -## 0.2.2 -* Reduce `nanoid/generate` size (by Anton Khlynovskiy). -* Speed up Node.js random generator. - -## 0.2.1 -* Fix documentation (by Piper Chester). - -## 0.2 -* Add `size` argument to `nanoid()`. -* Improve performance by 50%. -* Reduce library size by 26% (by Vsevolod Rodionov and Oleg Mokhov). - -## 0.1.1 -* Reduce library size by 5%. - -## 0.1 -* Initial release. diff --git a/node_modules/nanoid/LICENSE b/node_modules/nanoid/LICENSE deleted file mode 100644 index 37f56aa..0000000 --- a/node_modules/nanoid/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright 2017 Andrey Sitnik - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of -the Software, and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS -FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR -COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/nanoid/README.md b/node_modules/nanoid/README.md deleted file mode 100644 index 68eafd4..0000000 --- a/node_modules/nanoid/README.md +++ /dev/null @@ -1,503 +0,0 @@ -# Nano ID - -Nano ID logo by Anton Lovchikov - -A tiny, secure, URL-friendly, unique string ID generator for JavaScript. - -> “An amazing level of senseless perfectionism, -> which is simply impossible not to respect.” - -* **Small.** 108 bytes (minified and gzipped). No dependencies. - [Size Limit] controls the size. -* **Fast.** It is 60% faster than UUID. -* **Safe.** It uses cryptographically strong random APIs. - Can be used in clusters. -* **Compact.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`). - So ID size was reduced from 36 to 21 symbols. -* **Portable.** Nano ID was ported - to [14 programming languages](#other-programming-languages). - -```js -import { nanoid } from 'nanoid' -model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" -``` - -Supports modern browsers, IE [with Babel], Node.js and React Native. - -[online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ -[with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ -[Size Limit]: https://github.com/ai/size-limit - - - Sponsored by Evil Martians - - -## Table of Contents - -* [Comparison with UUID](#comparison-with-uuid) -* [Benchmark](#benchmark) -* [Tools](#tools) -* [Security](#security) -* [Usage](#usage) - * [JS](#js) - * [IE](#ie) - * [React](#react) - * [Create React App](#create-react-app) - * [React Native](#react-native) - * [Rollup](#rollup) - * [Expo](#expo) - * [PouchDB and CouchDB](#pouchdb-and-couchdb) - * [Mongoose](#mongoose) - * [ES Modules](#es-modules) - * [Web Workers](#web-workers) - * [CLI](#cli) - * [Other Programming Languages](#other-programming-languages) -* [API](#api) - * [Async](#async) - * [Non-Secure](#non-secure) - * [Custom Alphabet or Size](#custom-alphabet-or-size) - * [Custom Random Bytes Generator](#custom-random-bytes-generator) - - -## Comparison with UUID - -Nano ID is quite comparable to UUID v4 (random-based). -It has a similar number of random bits in the ID -(126 in Nano ID and 122 in UUID), so it has a similar collision probability: - -> For there to be a one in a billion chance of duplication, -> 103 trillion version 4 IDs must be generated. - -There are three main differences between Nano ID and UUID v4: - -1. Nano ID uses a bigger alphabet, so a similar number of random bits - are packed in just 21 symbols instead of 36. -2. Nano ID code is **4.5 times less** than `uuid/v4` package: - 108 bytes instead of 483. -3. Because of memory allocation tricks, Nano ID is **60%** faster than UUID. - - -## Benchmark - -```rust -$ node ./test/benchmark.js -nanoid 2,280,683 ops/sec -customAlphabet 1,851,117 ops/sec -uuid v4 1,348,425 ops/sec -uid.sync 313,306 ops/sec -secure-random-string 294,161 ops/sec -cuid 158,988 ops/sec -shortid 37,222 ops/sec - -Async: -async nanoid 95,500 ops/sec -async customAlphabet 93,800 ops/sec -async secure-random-string 90,316 ops/sec -uid 85,583 ops/sec - -Non-secure: -non-secure nanoid 2,641,654 ops/sec -rndm 2,447,086 ops/sec -``` - -Test configuration: Dell XPS 2-in-1 7390, Fedora 32, Node.js 15.1. - - -## Tools - -* [ID size calculator] shows collision probability when adjusting - the ID alphabet or size. -* [`nanoid-dictionary`] with popular alphabets to use with `customAlphabet`. -* [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words. - -[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary -[ID size calculator]: https://zelark.github.io/nano-id-cc/ -[`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good - - -## Security - -*See a good article about random generators theory: -[Secure random values (in Node.js)]* - -* **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID - uses the `crypto` module in Node.js and the Web Crypto API in browsers. - These modules use unpredictable hardware random generator. -* **Uniformity.** `random % alphabet` is a popular mistake to make when coding - an ID generator. The distribution will not be even; there will be a lower - chance for some symbols to appear compared to others. So, it will reduce - the number of tries when brute-forcing. Nano ID uses a [better algorithm] - and is tested for uniformity. - - Nano ID uniformity - -* **Vulnerabilities:** to report a security vulnerability, please use - the [Tidelift security contact](https://tidelift.com/security). - Tidelift will coordinate the fix and disclosure. - -[Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba -[better algorithm]: https://github.com/ai/nanoid/blob/master/index.js - - -## Usage - -### JS - -The main module uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID -with 21 characters (to have a collision probability similar to UUID v4). - -```js -import { nanoid } from 'nanoid' -model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" -``` - -If you want to reduce the ID size (and increase collisions probability), -you can pass the size as an argument. - -```js -nanoid(10) //=> "IRFa-VaY2b" -``` - -Don’t forget to check the safety of your ID size -in our [ID collision probability] calculator. - -You can also use a [custom alphabet](#custom-alphabet-or-size) -or a [random generator](#custom-random-bytes-generator). - -[ID collision probability]: https://zelark.github.io/nano-id-cc/ - - -### IE - -If you support IE, you need to [transpile `node_modules`] by Babel -and add `crypto` alias: - -```js -// polyfills.js -if (!window.crypto) { - window.crypto = window.msCrypto -} -``` - -```js -import './polyfills.js' -import { nanoid } from 'nanoid' -``` - -[transpile `node_modules`]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ - - -### React - -**Do not** call `nanoid` in the `key` prop. In React, `key` should be consistent -among renders. - -This is the bad example: - -```jsx - /* DON’T DO IT */ -``` - -This is the good example (`id` will be generated only once): - -```jsx -const Element = () => { - const [id] = React.useState(nanoid) - return -} -``` - -If you want to use Nano ID in the `id` prop, you must set some string prefix -(it is invalid for the HTML ID to start with a number). - -```jsx - -``` - - -### Create React App - -Create React App has [a problem](https://github.com/ai/nanoid/issues/205) -with ES modules packages. - -``` -TypeError: (0 , _nanoid.nanoid) is not a function -``` - -[Pull request](https://github.com/facebook/create-react-app/pull/8768) was sent, -but it was still not released. - -Use Nano ID 2 `npm i nanoid@^2.0.0` until Create React App 4.0 release. - - -### React Native - -React Native does not have built-in random generator. - -1. Check [`react-native-get-random-values`] docs and install it. -2. Import it before Nano ID. - -```js -import 'react-native-get-random-values' -import { nanoid } from 'nanoid' -``` - -For Expo framework see the next section. - -[`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values - - -### Rollup - -For Rollup you will need [`@rollup/plugin-replace`] to replace -`process.env.NODE_ENV`: - -```js - plugins: [ - replace({ - 'process.env.NODE_ENV': JSON.stringify(process.env.NODE) - }) - ] -``` - -[`@rollup/plugin-replace`]: https://github.com/rollup/plugins/tree/master/packages/replace - - -### Expo - -If you use Expo in React Native, you need a different workaround. - -1. Install [`expo-random`](https://www.npmjs.com/package/expo-random). -2. Use `nanoid/async` instead of `nanoid`. -3. Import `index.native.js` file directly. - -```js -import { nanoid } from 'nanoid/async/index.native' - -async function createUser () { - user.id = await nanoid() -} -``` - -[`expo-random`]: https://www.npmjs.com/package/expo-random - - -### PouchDB and CouchDB - -In PouchDB and CouchDB, IDs can’t start with an underscore `_`. -A prefix is required to prevent this issue, as Nano ID might use a `_` -at the start of the ID by default. - -Override the default ID with the following option: - -```js -db.put({ - _id: 'id' + nanoid(), - … -}) -``` - - -### Mongoose - -```js -const mySchema = new Schema({ - _id: { - type: String, - default: () => nanoid() - } -}) -``` - - -### ES Modules - -Nano ID provides ES modules. You do not need to do anything to use Nano ID -as ESM in webpack, Rollup, Parcel, or Node.js. - -```js -import { nanoid } from 'nanoid' -``` - -For quick hacks, you can load Nano ID from CDN. Special minified -`nanoid.js` module is available on jsDelivr. - -Though, it is not recommended to be used in production -because of the lower loading performance. - -```js -import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js' -``` - - -### Web Workers - -Web Workers do not have access to a secure random generator. - -Security is important in IDs when IDs should be unpredictable. -For instance, in "access by URL" link generation. -If you do not need unpredictable IDs, but you need to use Web Workers, -you can use the non‑secure ID generator. - -```js -import { nanoid } from 'nanoid/non-secure' -nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" -``` - -Note: non-secure IDs are more prone to collision attacks. - - -### CLI - -You can get unique ID in terminal by calling `npx nanoid`. You need only -Node.js in the system. You do not need Nano ID to be installed anywhere. - -```sh -$ npx nanoid -npx: installed 1 in 0.63s -LZfXLFzPPR4NNrgjlWDxn -``` - -If you want to change alphabet or ID size, you should use [`nanoid-cli`]. - -[`nanoid-cli`]: https://github.com/twhitbeck/nanoid-cli - - -### Other Programming Languages - -Nano ID was ported to many languages. You can use these ports to have -the same ID generator on the client and server side. - -* [C#](https://github.com/codeyu/nanoid-net) -* [C++](https://github.com/mcmikecreations/nanoid_cpp) -* [Clojure and ClojureScript](https://github.com/zelark/nano-id) -* [Crystal](https://github.com/mamantoha/nanoid.cr) -* [Dart](https://github.com/pd4d10/nanoid-dart) -* [Deno](https://github.com/ianfabs/nanoid) -* [Go](https://github.com/matoous/go-nanoid) -* [Elixir](https://github.com/railsmechanic/nanoid) -* [Haskell](https://github.com/4e6/nanoid-hs) -* [Janet](https://sr.ht/~statianzo/janet-nanoid/) -* [Java](https://github.com/aventrix/jnanoid) -* [Nim](https://github.com/icyphox/nanoid.nim) -* [PHP](https://github.com/hidehalo/nanoid-php) -* [Python](https://github.com/puyuan/py-nanoid) - with [dictionaries](https://pypi.org/project/nanoid-dictionary) -* [Ruby](https://github.com/radeno/nanoid.rb) -* [Rust](https://github.com/nikolay-govorov/nanoid) -* [Swift](https://github.com/antiflasher/NanoID) - -Also, [CLI] is available to generate IDs from a command line. - -[CLI]: #cli - - -## API - -### Async - -To generate hardware random bytes, CPU collects electromagnetic noise. -In the synchronous API during the noise collection, the CPU is busy and -cannot do anything useful in parallel. - -Using the asynchronous API of Nano ID, another code can run during -the entropy collection. - -```js -import { nanoid } from 'nanoid/async' - -async function createUser () { - user.id = await nanoid() -} -``` - -Unfortunately, you will lose Web Crypto API advantages in a browser -if you use the asynchronous API. So, currently, in the browser, you are limited -with either security or asynchronous behavior. - - -### Non-Secure - -By default, Nano ID uses hardware random bytes generation for security -and low collision probability. If you are not so concerned with security -and more concerned with performance, you can use the faster non-secure generator. - -```js -import { nanoid } from 'nanoid/non-secure' -const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" -``` - -Note: your IDs will be more predictable and prone to collision attacks. - - -### Custom Alphabet or Size - -`customAlphabet` allows you to create `nanoid` with your own alphabet -and ID size. - -```js -import { customAlphabet } from 'nanoid' -const nanoid = customAlphabet('1234567890abcdef', 10) -model.id = nanoid() //=> "4f90d13a42" -``` - -Check the safety of your custom alphabet and ID size in our -[ID collision probability] calculator. For more alphabets, check out the options -in [`nanoid-dictionary`]. - -Alphabet must contain 256 symbols or less. -Otherwise, the security of the internal generator algorithm is not guaranteed. - -Customizable asynchronous and non-secure APIs are also available: - -```js -import { customAlphabet } from 'nanoid/async' -const nanoid = customAlphabet('1234567890abcdef', 10) -async function createUser () { - user.id = await nanoid() -} -``` - -```js -import { customAlphabet } from 'nanoid/non-secure' -const nanoid = customAlphabet('1234567890abcdef', 10) -user.id = nanoid() -``` - -[ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/ -[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary - - -### Custom Random Bytes Generator - -`customRandom` allows you to create a `nanoid` and replace alphabet -and the default random bytes generator. - -In this example, a seed-based generator is used: - -```js -import { customRandom } from 'nanoid' - -const rng = seedrandom(seed) -const nanoid = customRandom('abcdef', 10, size => { - return (new Uint8Array(size)).map(() => 256 * rng()) -}) - -nanoid() //=> "fbaefaadeb" -``` - -`random` callback must accept the array size and return an array -with random numbers. - -If you want to use the same URL-friendly symbols with `customRandom`, -you can get the default alphabet using the `urlAlphabet`. - -```js -const { customRandom, urlAlphabet } = require('nanoid') -const nanoid = customRandom(urlAlphabet, 10, random) -``` - -Asynchronous and non-secure APIs are not available for `customRandom`. diff --git a/node_modules/nanoid/async/index.browser.js b/node_modules/nanoid/async/index.browser.js deleted file mode 100644 index 0195030..0000000 --- a/node_modules/nanoid/async/index.browser.js +++ /dev/null @@ -1,70 +0,0 @@ -let random = bytes => - Promise.resolve(crypto.getRandomValues(new Uint8Array(bytes))) - -let customAlphabet = (alphabet, size) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = crypto.getRandomValues(new Uint8Array(step)) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return Promise.resolve(id) - } - } - } -} - -let nanoid = (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array(size)) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return Promise.resolve(id) -} - -export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.cjs b/node_modules/nanoid/async/index.cjs deleted file mode 100644 index 4a26407..0000000 --- a/node_modules/nanoid/async/index.cjs +++ /dev/null @@ -1,71 +0,0 @@ -let crypto = require('crypto') - -let { urlAlphabet } = require('../url-alphabet/index.cjs') - -// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, -// because it is possible to use in combination with `Buffer.allocUnsafe()`. -let random = bytes => - new Promise((resolve, reject) => { - // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. - // Memory flushing is unnecessary since the buffer allocation itself resets - // the memory with the new bytes. - crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { - if (err) { - reject(err) - } else { - resolve(buf) - } - }) - }) - -let customAlphabet = (alphabet, size) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * size) / alphabet.length) - - let tick = id => - random(step).then(bytes => { - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - return tick(id) - }) - - return () => tick('') -} - -let nanoid = (size = 21) => - random(size).then(bytes => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id - }) - -module.exports = { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.d.ts b/node_modules/nanoid/async/index.d.ts deleted file mode 100644 index 64f95d4..0000000 --- a/node_modules/nanoid/async/index.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** - * Generate secure URL-friendly unique ID. The non-blocking version. - * - * By default, the ID will have 21 symbols to have a collision probability - * similar to UUID v4. - * - * ```js - * import { nanoid } from 'nanoid/async' - * nanoid().then(id => { - * model.id = id - * }) - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A promise with a random string. - */ -export function nanoid (size?: number): Promise - -/** - * A low-level function. - * Generate secure unique ID with custom alphabet. The non-blocking version. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * @param alphabet Alphabet used to generate the ID. - * @param size Size of the ID. - * @returns A promise with a random string. - * - * ```js - * import { customAlphabet } from 'nanoid/async' - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * nanoid().then(id => { - * model.id = id //=> "8ё56а" - * }) - * ``` - */ -export function customAlphabet ( - alphabet: string, - size: number -): () => Promise - -/** - * Generate an array of random bytes collected from hardware noise. - * - * ```js - * import { random } from 'nanoid/async' - * random(5).then(bytes => { - * bytes //=> [10, 67, 212, 67, 89] - * }) - * ``` - * - * @param bytes Size of the array. - * @returns A promise with a random bytes array. - */ -export function random (bytes: number): Promise diff --git a/node_modules/nanoid/async/index.js b/node_modules/nanoid/async/index.js deleted file mode 100644 index 00199ba..0000000 --- a/node_modules/nanoid/async/index.js +++ /dev/null @@ -1,71 +0,0 @@ -import crypto from 'crypto' - -import { urlAlphabet } from '../url-alphabet/index.js' - -// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, -// because it is possible to use in combination with `Buffer.allocUnsafe()`. -let random = bytes => - new Promise((resolve, reject) => { - // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. - // Memory flushing is unnecessary since the buffer allocation itself resets - // the memory with the new bytes. - crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { - if (err) { - reject(err) - } else { - resolve(buf) - } - }) - }) - -let customAlphabet = (alphabet, size) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * size) / alphabet.length) - - let tick = id => - random(step).then(bytes => { - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - return tick(id) - }) - - return () => tick('') -} - -let nanoid = (size = 21) => - random(size).then(bytes => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id - }) - -export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/index.native.js b/node_modules/nanoid/async/index.native.js deleted file mode 100644 index 010ae40..0000000 --- a/node_modules/nanoid/async/index.native.js +++ /dev/null @@ -1,57 +0,0 @@ -import { getRandomBytesAsync } from 'expo-random' - -import { urlAlphabet } from '../url-alphabet/index.js' - -let random = getRandomBytesAsync - -let customAlphabet = (alphabet, size) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * size) / alphabet.length) - - let tick = id => - random(step).then(bytes => { - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - return tick(id) - }) - - return () => tick('') -} - -let nanoid = (size = 21) => - random(size).then(bytes => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id - }) - -export { nanoid, customAlphabet, random } diff --git a/node_modules/nanoid/async/package.json b/node_modules/nanoid/async/package.json deleted file mode 100644 index d2a4664..0000000 --- a/node_modules/nanoid/async/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": { - "./index.js": "./index.native.js" - }, - "browser": { - "./index.js": "./index.browser.js" - } -} \ No newline at end of file diff --git a/node_modules/nanoid/bin/nanoid.cjs b/node_modules/nanoid/bin/nanoid.cjs deleted file mode 100755 index e14116f..0000000 --- a/node_modules/nanoid/bin/nanoid.cjs +++ /dev/null @@ -1,5 +0,0 @@ -#!/usr/bin/env node - -let { nanoid } = require('..') - -process.stdout.write(nanoid() + '\n') diff --git a/node_modules/nanoid/index.browser.js b/node_modules/nanoid/index.browser.js deleted file mode 100644 index f8aa4c2..0000000 --- a/node_modules/nanoid/index.browser.js +++ /dev/null @@ -1,105 +0,0 @@ -// This file replaces `index.js` in bundlers like webpack or Rollup, -// according to `browser` config in `package.json`. - -import { urlAlphabet } from './url-alphabet/index.js' - -if (process.env.NODE_ENV !== 'production') { - // All bundlers will remove this block in the production bundle. - if ( - typeof navigator !== 'undefined' && - navigator.product === 'ReactNative' && - typeof crypto === 'undefined' - ) { - throw new Error( - 'React Native does not have a built-in secure random generator. ' + - 'If you don’t need unpredictable IDs use `nanoid/non-secure`. ' + - 'For secure IDs, import `react-native-get-random-values` ' + - 'before Nano ID. If you use Expo, install `expo-random` ' + - 'and use `nanoid/async`.' - ) - } - if (typeof msCrypto !== 'undefined' && typeof crypto === 'undefined') { - throw new Error( - 'Import file with `if (!window.crypto) window.crypto = window.msCrypto`' + - ' before importing Nano ID to fix IE 11 support' - ) - } - if (typeof crypto === 'undefined') { - throw new Error( - 'Your browser does not have secure random generator. ' + - 'If you don’t need unpredictable IDs, you can use nanoid/non-secure.' - ) - } -} - -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let j = step - while (j--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[j] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array(size)) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} - -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.cjs b/node_modules/nanoid/index.cjs deleted file mode 100644 index 43df60b..0000000 --- a/node_modules/nanoid/index.cjs +++ /dev/null @@ -1,80 +0,0 @@ -let crypto = require('crypto') - -let { urlAlphabet } = require('./url-alphabet/index.cjs') - -// It is best to make fewer, larger requests to the crypto module to -// avoid system call overhead. So, random numbers are generated in a -// pool. The pool is a Buffer that is larger than the initial random -// request size by this multiplier. The pool is enlarged if subsequent -// requests exceed the maximum buffer size. -const POOL_SIZE_MULTIPLIER = 32 -let pool, poolOffset - -let random = bytes => { - if (!pool || pool.length < bytes) { - pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) - crypto.randomFillSync(pool) - poolOffset = 0 - } else if (poolOffset + bytes > pool.length) { - crypto.randomFillSync(pool) - poolOffset = 0 - } - - let res = pool.subarray(poolOffset, poolOffset + bytes) - poolOffset += bytes - return res -} - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let bytes = random(size) - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id -} - -module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.d.ts b/node_modules/nanoid/index.d.ts deleted file mode 100644 index 4378771..0000000 --- a/node_modules/nanoid/index.d.ts +++ /dev/null @@ -1,88 +0,0 @@ -/** - * Generate secure URL-friendly unique ID. - * - * By default, the ID will have 21 symbols to have a collision probability - * similar to UUID v4. - * - * ```js - * import { nanoid } from 'nanoid' - * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A random string. - */ -export function nanoid (size?: number): string - -/** - * Generate secure unique ID with custom alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * @param alphabet Alphabet used to generate the ID. - * @param size Size of the ID. - * @returns A random string generator. - * - * ```js - * const { customAlphabet } = require('nanoid') - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * nanoid() //=> "8ё56а" - * ``` - */ -export function customAlphabet (alphabet: string, size: number): () => string - -/** - * Generate unique ID with custom random generator and alphabet. - * - * Alphabet must contain 256 symbols or less. Otherwise, the generator - * will not be secure. - * - * ```js - * import { customRandom } from 'nanoid/format' - * - * const nanoid = customRandom('abcdef', 5, size => { - * const random = [] - * for (let i = 0; i < size; i++) { - * random.push(randomByte()) - * } - * return random - * }) - * - * nanoid() //=> "fbaef" - * ``` - * - * @param alphabet Alphabet used to generate a random string. - * @param size Size of the random string. - * @param random A random bytes generator. - * @returns A random string generator. - */ -export function customRandom ( - alphabet: string, - size: number, - random: (bytes: number) => Uint8Array -): () => string - -/** - * URL safe symbols. - * - * ```js - * import { urlAlphabet } from 'nanoid' - * const nanoid = customRandom(urlAlphabet, 10) - * nanoid() //=> "Uakgb_J5m9" - * ``` - */ -export const urlAlphabet: string - -/** - * Generate an array of random bytes collected from hardware noise. - * - * ```js - * import { customRandom, random } from 'nanoid' - * const nanoid = customRandom("abcdef", 5, random) - * ``` - * - * @param bytes Size of the array. - * @returns An array of random bytes. - */ -export function random (bytes: number): Uint8Array diff --git a/node_modules/nanoid/index.dev.js b/node_modules/nanoid/index.dev.js deleted file mode 100644 index fe2ef72..0000000 --- a/node_modules/nanoid/index.dev.js +++ /dev/null @@ -1,105 +0,0 @@ -// This file replaces `index.js` in bundlers like webpack or Rollup, -// according to `browser` config in `package.json`. - -import { urlAlphabet } from './url-alphabet/index.js' - -if (true) { - // All bundlers will remove this block in the production bundle. - if ( - typeof navigator !== 'undefined' && - navigator.product === 'ReactNative' && - typeof crypto === 'undefined' - ) { - throw new Error( - 'React Native does not have a built-in secure random generator. ' + - 'If you don’t need unpredictable IDs use `nanoid/non-secure`. ' + - 'For secure IDs, import `react-native-get-random-values` ' + - 'before Nano ID. If you use Expo, install `expo-random` ' + - 'and use `nanoid/async`.' - ) - } - if (typeof msCrypto !== 'undefined' && typeof crypto === 'undefined') { - throw new Error( - 'Import file with `if (!window.crypto) window.crypto = window.msCrypto`' + - ' before importing Nano ID to fix IE 11 support' - ) - } - if (typeof crypto === 'undefined') { - throw new Error( - 'Your browser does not have secure random generator. ' + - 'If you don’t need unpredictable IDs, you can use nanoid/non-secure.' - ) - } -} - -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let j = step - while (j--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[j] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array(size)) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} - -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.js b/node_modules/nanoid/index.js deleted file mode 100644 index 9abe01a..0000000 --- a/node_modules/nanoid/index.js +++ /dev/null @@ -1,80 +0,0 @@ -import crypto from 'crypto' - -import { urlAlphabet } from './url-alphabet/index.js' - -// It is best to make fewer, larger requests to the crypto module to -// avoid system call overhead. So, random numbers are generated in a -// pool. The pool is a Buffer that is larger than the initial random -// request size by this multiplier. The pool is enlarged if subsequent -// requests exceed the maximum buffer size. -const POOL_SIZE_MULTIPLIER = 32 -let pool, poolOffset - -let random = bytes => { - if (!pool || pool.length < bytes) { - pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) - crypto.randomFillSync(pool) - poolOffset = 0 - } else if (poolOffset + bytes > pool.length) { - crypto.randomFillSync(pool) - poolOffset = 0 - } - - let res = pool.subarray(poolOffset, poolOffset + bytes) - poolOffset += bytes - return res -} - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - let step = Math.ceil((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = step - while (i--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[i] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let bytes = random(size) - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - id += urlAlphabet[bytes[size] & 63] - } - return id -} - -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/index.prod.js b/node_modules/nanoid/index.prod.js deleted file mode 100644 index ffd9fb5..0000000 --- a/node_modules/nanoid/index.prod.js +++ /dev/null @@ -1,105 +0,0 @@ -// This file replaces `index.js` in bundlers like webpack or Rollup, -// according to `browser` config in `package.json`. - -import { urlAlphabet } from './url-alphabet/index.js' - -if (false) { - // All bundlers will remove this block in the production bundle. - if ( - typeof navigator !== 'undefined' && - navigator.product === 'ReactNative' && - typeof crypto === 'undefined' - ) { - throw new Error( - 'React Native does not have a built-in secure random generator. ' + - 'If you don’t need unpredictable IDs use `nanoid/non-secure`. ' + - 'For secure IDs, import `react-native-get-random-values` ' + - 'before Nano ID. If you use Expo, install `expo-random` ' + - 'and use `nanoid/async`.' - ) - } - if (typeof msCrypto !== 'undefined' && typeof crypto === 'undefined') { - throw new Error( - 'Import file with `if (!window.crypto) window.crypto = window.msCrypto`' + - ' before importing Nano ID to fix IE 11 support' - ) - } - if (typeof crypto === 'undefined') { - throw new Error( - 'Your browser does not have secure random generator. ' + - 'If you don’t need unpredictable IDs, you can use nanoid/non-secure.' - ) - } -} - -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) - -let customRandom = (alphabet, size, getRandom) => { - // First, a bitmask is necessary to generate the ID. The bitmask makes bytes - // values closer to the alphabet size. The bitmask calculates the closest - // `2^31 - 1` number, which exceeds the alphabet size. - // For example, the bitmask for the alphabet size 30 is 31 (00011111). - // `Math.clz32` is not used, because it is not available in browsers. - let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 - // Though, the bitmask solution is not perfect since the bytes exceeding - // the alphabet size are refused. Therefore, to reliably generate the ID, - // the random bytes redundancy has to be satisfied. - - // Note: every hardware random generator call is performance expensive, - // because the system call for entropy collection takes a lot of time. - // So, to avoid additional system calls, extra bytes are requested in advance. - - // Next, a step determines how many random bytes to generate. - // The number of random bytes gets decided upon the ID size, mask, - // alphabet size, and magic number 1.6 (using 1.6 peaks at performance - // according to benchmarks). - - // `-~f => Math.ceil(f)` if f is a float - // `-~i => i + 1` if i is an integer - let step = -~((1.6 * mask * size) / alphabet.length) - - return () => { - let id = '' - while (true) { - let bytes = getRandom(step) - // A compact alternative for `for (var i = 0; i < step; i++)`. - let j = step - while (j--) { - // Adding `|| ''` refuses a random byte that exceeds the alphabet size. - id += alphabet[bytes[j] & mask] || '' - if (id.length === size) return id - } - } - } -} - -let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random) - -let nanoid = (size = 21) => { - let id = '' - let bytes = crypto.getRandomValues(new Uint8Array(size)) - - // A compact alternative for `for (var i = 0; i < step; i++)`. - while (size--) { - // It is incorrect to use bytes exceeding the alphabet size. - // The following mask reduces the random byte in the 0-255 value - // range to the 0-63 value range. Therefore, adding hacks, such - // as empty string fallback or magic numbers, is unneccessary because - // the bitmask trims bytes down to the alphabet size. - let byte = bytes[size] & 63 - if (byte < 36) { - // `0-9a-z` - id += byte.toString(36) - } else if (byte < 62) { - // `A-Z` - id += (byte - 26).toString(36).toUpperCase() - } else if (byte < 63) { - id += '_' - } else { - id += '-' - } - } - return id -} - -export { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/node_modules/nanoid/nanoid.js b/node_modules/nanoid/nanoid.js deleted file mode 100644 index 5bbc489..0000000 --- a/node_modules/nanoid/nanoid.js +++ /dev/null @@ -1 +0,0 @@ -export let nanoid=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=63&r[t];e+=n<36?n.toString(36):n<62?(n-26).toString(36).toUpperCase():n<63?"_":"-"}return e}; \ No newline at end of file diff --git a/node_modules/nanoid/non-secure/index.cjs b/node_modules/nanoid/non-secure/index.cjs deleted file mode 100644 index 69e08c2..0000000 --- a/node_modules/nanoid/non-secure/index.cjs +++ /dev/null @@ -1,30 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped -// optimize the gzip compression for this alphabet. -let urlAlphabet = - 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW' - -let customAlphabet = (alphabet, size) => { - return () => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += alphabet[(Math.random() * alphabet.length) | 0] - } - return id - } -} - -let nanoid = (size = 21) => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += urlAlphabet[(Math.random() * 64) | 0] - } - return id -} - -module.exports = { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/index.d.ts b/node_modules/nanoid/non-secure/index.d.ts deleted file mode 100644 index 9ea97ea..0000000 --- a/node_modules/nanoid/non-secure/index.d.ts +++ /dev/null @@ -1,30 +0,0 @@ -/** - * Generate URL-friendly unique ID. This method uses the non-secure - * predictable random generator with bigger collision probability. - * - * ```js - * import { nanoid } from 'nanoid/non-secure' - * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" - * ``` - * - * @param size Size of the ID. The default size is 21. - * @returns A random string. - */ -export function nanoid (size?: number): string - -/** - * Generate URL-friendly unique ID based on the custom alphabet. - * This method uses the non-secure predictable random generator - * with bigger collision probability. - * - * @param alphabet Alphabet used to generate the ID. - * @param size Size of the ID. - * @returns A random string. - * - * ```js - * import { customAlphabet } from 'nanoid/non-secure' - * const nanoid = customAlphabet('0123456789абвгдеё', 5) - * model.id = //=> "8ё56а" - * ``` - */ -export function customAlphabet (alphabet: string, size: number): () => string diff --git a/node_modules/nanoid/non-secure/index.js b/node_modules/nanoid/non-secure/index.js deleted file mode 100644 index c724c14..0000000 --- a/node_modules/nanoid/non-secure/index.js +++ /dev/null @@ -1,30 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped -// optimize the gzip compression for this alphabet. -let urlAlphabet = - 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW' - -let customAlphabet = (alphabet, size) => { - return () => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += alphabet[(Math.random() * alphabet.length) | 0] - } - return id - } -} - -let nanoid = (size = 21) => { - let id = '' - // A compact alternative for `for (var i = 0; i < step; i++)`. - let i = size - while (i--) { - // `| 0` is more compact and faster than `Math.floor()`. - id += urlAlphabet[(Math.random() * 64) | 0] - } - return id -} - -export { nanoid, customAlphabet } diff --git a/node_modules/nanoid/non-secure/package.json b/node_modules/nanoid/non-secure/package.json deleted file mode 100644 index 9930d6a..0000000 --- a/node_modules/nanoid/non-secure/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": "index.js" -} \ No newline at end of file diff --git a/node_modules/nanoid/package.json b/node_modules/nanoid/package.json deleted file mode 100644 index f11fe71..0000000 --- a/node_modules/nanoid/package.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "name": "nanoid", - "version": "3.1.20", - "description": "A tiny (108 bytes), secure URL-friendly unique string ID generator", - "keywords": [ - "uuid", - "random", - "id", - "url" - ], - "engines": { - "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" - }, - "author": "Andrey Sitnik ", - "license": "MIT", - "repository": "ai/nanoid", - "browser": { - "./index.js": "./index.browser.js" - }, - "react-native": "index.js", - "bin": "./bin/nanoid.cjs", - "sideEffects": false, - "types": "./index.d.ts", - "type": "module", - "main": "index.cjs", - "module": "index.js", - "exports": { - ".": { - "browser": { - "development": "./index.dev.js", - "production": "./index.prod.js" - }, - "require": "./index.cjs", - "import": "./index.js", - "types": "./index.d.ts" - }, - "./package.json": "./package.json", - "./async/package.json": "./async/package.json", - "./async": { - "browser": "./async/index.browser.js", - "require": "./async/index.cjs", - "import": "./async/index.js" - }, - "./non-secure/package.json": "./non-secure/package.json", - "./non-secure": { - "require": "./non-secure/index.cjs", - "import": "./non-secure/index.js" - }, - "./url-alphabet/package.json": "./url-alphabet/package.json", - "./url-alphabet": { - "require": "./url-alphabet/index.cjs", - "import": "./url-alphabet/index.js" - }, - "./index.d.ts": "./index.d.ts" - } -} \ No newline at end of file diff --git a/node_modules/nanoid/url-alphabet/index.cjs b/node_modules/nanoid/url-alphabet/index.cjs deleted file mode 100644 index 8c9d70d..0000000 --- a/node_modules/nanoid/url-alphabet/index.cjs +++ /dev/null @@ -1,6 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped -// optimize the gzip compression for this alphabet. -let urlAlphabet = - 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW' - -module.exports = { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/index.js b/node_modules/nanoid/url-alphabet/index.js deleted file mode 100644 index 9e4ccb4..0000000 --- a/node_modules/nanoid/url-alphabet/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped -// optimize the gzip compression for this alphabet. -let urlAlphabet = - 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW' - -export { urlAlphabet } diff --git a/node_modules/nanoid/url-alphabet/package.json b/node_modules/nanoid/url-alphabet/package.json deleted file mode 100644 index 9930d6a..0000000 --- a/node_modules/nanoid/url-alphabet/package.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "type": "module", - "main": "index.cjs", - "module": "index.js", - "react-native": "index.js" -} \ No newline at end of file diff --git a/node_modules/node-fetch/README.md b/node_modules/node-fetch/README.md index 2dde742..55f09b7 100644 --- a/node_modules/node-fetch/README.md +++ b/node_modules/node-fetch/README.md @@ -188,6 +188,49 @@ fetch('https://assets-cdn.github.com/images/modules/logos_page/Octocat.png') }); ``` +In Node.js 14 you can also use async iterators to read `body`; however, be careful to catch +errors -- the longer a response runs, the more likely it is to encounter an error. + +```js +const fetch = require('node-fetch'); +const response = await fetch('https://httpbin.org/stream/3'); +try { + for await (const chunk of response.body) { + console.dir(JSON.parse(chunk.toString())); + } +} catch (err) { + console.error(err.stack); +} +``` + +In Node.js 12 you can also use async iterators to read `body`; however, async iterators with streams +did not mature until Node.js 14, so you need to do some extra work to ensure you handle errors +directly from the stream and wait on it response to fully close. + +```js +const fetch = require('node-fetch'); +const read = async body => { + let error; + body.on('error', err => { + error = err; + }); + for await (const chunk of body) { + console.dir(JSON.parse(chunk.toString())); + } + return new Promise((resolve, reject) => { + body.on('close', () => { + error ? reject(error) : resolve(); + }); + }); +}; +try { + const response = await fetch('https://httpbin.org/stream/3'); + await read(response.body); +} catch (err) { + console.error(err.stack); +} +``` + #### Buffer If you prefer to cache binary data in full, use buffer(). (NOTE: `buffer()` is a `node-fetch`-only API) @@ -344,7 +387,6 @@ Header | Value ------------------- | -------------------------------------------------------- `Accept-Encoding` | `gzip,deflate` _(when `options.compress === true`)_ `Accept` | `*/*` -`Connection` | `close` _(when no `options.agent` is present)_ `Content-Length` | _(automatically calculated, if possible)_ `Transfer-Encoding` | `chunked` _(when `req.body` is a stream)_ `User-Agent` | `node-fetch/1.0 (+https://github.com/bitinn/node-fetch)` @@ -361,6 +403,8 @@ The `agent` option allows you to specify networking related options which are ou See [`http.Agent`](https://nodejs.org/api/http.html#http_new_agent_options) for more information. +If no agent is specified, the default agent provided by Node.js is used. Note that [this changed in Node.js 19](https://github.com/nodejs/node/blob/4267b92604ad78584244488e7f7508a690cb80d0/lib/_http_agent.js#L564) to have `keepalive` true by default. If you wish to enable `keepalive` in an earlier version of Node.js, you can override the agent as per the following code sample. + In addition, the `agent` option accepts a function that returns `http`(s)`.Agent` instance given current [URL](https://nodejs.org/api/url.html), this is useful during a redirection chain across HTTP and HTTPS protocol. ```js diff --git a/node_modules/node-fetch/browser.js b/node_modules/node-fetch/browser.js index 83c54c5..ee86265 100644 --- a/node_modules/node-fetch/browser.js +++ b/node_modules/node-fetch/browser.js @@ -11,15 +11,15 @@ var getGlobal = function () { throw new Error('unable to locate global object'); } -var global = getGlobal(); +var globalObject = getGlobal(); -module.exports = exports = global.fetch; +module.exports = exports = globalObject.fetch; // Needed for TypeScript and Webpack. -if (global.fetch) { - exports.default = global.fetch.bind(global); +if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); } -exports.Headers = global.Headers; -exports.Request = global.Request; -exports.Response = global.Response; \ No newline at end of file +exports.Headers = globalObject.Headers; +exports.Request = globalObject.Request; +exports.Response = globalObject.Response; diff --git a/node_modules/node-fetch/lib/index.es.js b/node_modules/node-fetch/lib/index.es.js index 4852f7c..aae9799 100644 --- a/node_modules/node-fetch/lib/index.es.js +++ b/node_modules/node-fetch/lib/index.es.js @@ -1361,10 +1361,6 @@ function getNodeRequestOptions(request) { agent = agent(parsedURL); } - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js @@ -1413,6 +1409,20 @@ const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + /** * Fetch function * @@ -1444,7 +1454,7 @@ function fetch(url, opts) { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); + destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); @@ -1485,9 +1495,43 @@ function fetch(url, opts) { req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + finalize(); }); + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + req.on('response', function (res) { clearTimeout(reqTimeout); @@ -1559,7 +1603,7 @@ function fetch(url, opts) { size: request.size }; - if (!isDomainOrSubdomain(request.url, locationURL)) { + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } @@ -1652,6 +1696,13 @@ function fetch(url, opts) { response = new Response(body, response_options); resolve(response); }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); return; } @@ -1671,6 +1722,44 @@ function fetch(url, opts) { writeToStream(req, request); }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + /** * Redirect code matching * @@ -1685,4 +1774,4 @@ fetch.isRedirect = function (code) { fetch.Promise = global.Promise; export default fetch; -export { Headers, Request, Response, FetchError }; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/lib/index.js b/node_modules/node-fetch/lib/index.js index e5b04f1..567ff5d 100644 --- a/node_modules/node-fetch/lib/index.js +++ b/node_modules/node-fetch/lib/index.js @@ -1365,10 +1365,6 @@ function getNodeRequestOptions(request) { agent = agent(parsedURL); } - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js @@ -1417,6 +1413,20 @@ const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + /** * Fetch function * @@ -1448,7 +1458,7 @@ function fetch(url, opts) { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); + destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); @@ -1489,9 +1499,43 @@ function fetch(url, opts) { req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + finalize(); }); + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + req.on('response', function (res) { clearTimeout(reqTimeout); @@ -1563,7 +1607,7 @@ function fetch(url, opts) { size: request.size }; - if (!isDomainOrSubdomain(request.url, locationURL)) { + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } @@ -1656,6 +1700,13 @@ function fetch(url, opts) { response = new Response(body, response_options); resolve(response); }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); return; } @@ -1675,6 +1726,44 @@ function fetch(url, opts) { writeToStream(req, request); }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + /** * Redirect code matching * @@ -1695,3 +1784,4 @@ exports.Headers = Headers; exports.Request = Request; exports.Response = Response; exports.FetchError = FetchError; +exports.AbortError = AbortError; diff --git a/node_modules/node-fetch/lib/index.mjs b/node_modules/node-fetch/lib/index.mjs index 49ee05e..2863dd9 100644 --- a/node_modules/node-fetch/lib/index.mjs +++ b/node_modules/node-fetch/lib/index.mjs @@ -1359,10 +1359,6 @@ function getNodeRequestOptions(request) { agent = agent(parsedURL); } - if (!headers.has('Connection') && !agent) { - headers.set('Connection', 'close'); - } - // HTTP-network fetch step 4.2 // chunked encoding is handled by Node.js @@ -1411,6 +1407,20 @@ const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); }; +/** + * isSameProtocol reports whether the two provided URLs use the same protocol. + * + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination + */ +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; + /** * Fetch function * @@ -1442,7 +1452,7 @@ function fetch(url, opts) { let error = new AbortError('The user aborted a request.'); reject(error); if (request.body && request.body instanceof Stream.Readable) { - request.body.destroy(error); + destroyStream(request.body, error); } if (!response || !response.body) return; response.body.emit('error', error); @@ -1483,9 +1493,43 @@ function fetch(url, opts) { req.on('error', function (err) { reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + + if (response && response.body) { + destroyStream(response.body, err); + } + finalize(); }); + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } + + if (response && response.body) { + destroyStream(response.body, err); + } + }); + + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; + + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } + req.on('response', function (res) { clearTimeout(reqTimeout); @@ -1557,7 +1601,7 @@ function fetch(url, opts) { size: request.size }; - if (!isDomainOrSubdomain(request.url, locationURL)) { + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { requestOpts.headers.delete(name); } @@ -1650,6 +1694,13 @@ function fetch(url, opts) { response = new Response(body, response_options); resolve(response); }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); return; } @@ -1669,6 +1720,44 @@ function fetch(url, opts) { writeToStream(req, request); }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; + + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); +} + +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } +} + /** * Redirect code matching * @@ -1683,4 +1772,4 @@ fetch.isRedirect = function (code) { fetch.Promise = global.Promise; export default fetch; -export { Headers, Request, Response, FetchError }; +export { Headers, Request, Response, FetchError, AbortError }; diff --git a/node_modules/node-fetch/package.json b/node_modules/node-fetch/package.json index 3c1bd8d..e0be176 100644 --- a/node_modules/node-fetch/package.json +++ b/node_modules/node-fetch/package.json @@ -1,6 +1,6 @@ { "name": "node-fetch", - "version": "2.6.7", + "version": "2.7.0", "description": "A light-weight module that brings window.fetch to node.js", "main": "lib/index.js", "browser": "./browser.js", @@ -39,7 +39,7 @@ "dependencies": { "whatwg-url": "^5.0.0" }, - "peerDependencies": { + "peerDependencies": { "encoding": "^0.1.0" }, "peerDependenciesMeta": { @@ -53,7 +53,9 @@ "abortcontroller-polyfill": "^1.3.0", "babel-core": "^6.26.3", "babel-plugin-istanbul": "^4.1.6", - "babel-preset-env": "^1.6.1", + "babel-plugin-transform-async-generator-functions": "^6.24.1", + "babel-polyfill": "^6.26.0", + "babel-preset-env": "1.4.0", "babel-register": "^6.16.3", "chai": "^3.5.0", "chai-as-promised": "^7.1.1", @@ -72,5 +74,16 @@ "rollup-plugin-babel": "^3.0.7", "string-to-arraybuffer": "^1.0.2", "teeny-request": "3.7.0" + }, + "release": { + "branches": [ + "+([0-9]).x", + "main", + "next", + { + "name": "beta", + "prerelease": true + } + ] } } diff --git a/node_modules/path-is-absolute/index.js b/node_modules/path-is-absolute/index.js deleted file mode 100644 index 22aa6c3..0000000 --- a/node_modules/path-is-absolute/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'use strict'; - -function posix(path) { - return path.charAt(0) === '/'; -} - -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); - - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} - -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; diff --git a/node_modules/path-is-absolute/package.json b/node_modules/path-is-absolute/package.json deleted file mode 100644 index 91196d5..0000000 --- a/node_modules/path-is-absolute/package.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "path-is-absolute", - "version": "1.0.1", - "description": "Node.js 0.12 path.isAbsolute() ponyfill", - "license": "MIT", - "repository": "sindresorhus/path-is-absolute", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=0.10.0" - }, - "scripts": { - "test": "xo && node test.js" - }, - "files": [ - "index.js" - ], - "keywords": [ - "path", - "paths", - "file", - "dir", - "absolute", - "isabsolute", - "is-absolute", - "built-in", - "util", - "utils", - "core", - "ponyfill", - "polyfill", - "shim", - "is", - "detect", - "check" - ], - "devDependencies": { - "xo": "^0.16.0" - } -} diff --git a/node_modules/path-is-absolute/readme.md b/node_modules/path-is-absolute/readme.md deleted file mode 100644 index 8dbdf5f..0000000 --- a/node_modules/path-is-absolute/readme.md +++ /dev/null @@ -1,59 +0,0 @@ -# path-is-absolute [![Build Status](https://travis-ci.org/sindresorhus/path-is-absolute.svg?branch=master)](https://travis-ci.org/sindresorhus/path-is-absolute) - -> Node.js 0.12 [`path.isAbsolute()`](http://nodejs.org/api/path.html#path_path_isabsolute_path) [ponyfill](https://ponyfill.com) - - -## Install - -``` -$ npm install --save path-is-absolute -``` - - -## Usage - -```js -const pathIsAbsolute = require('path-is-absolute'); - -// Running on Linux -pathIsAbsolute('/home/foo'); -//=> true -pathIsAbsolute('C:/Users/foo'); -//=> false - -// Running on Windows -pathIsAbsolute('C:/Users/foo'); -//=> true -pathIsAbsolute('/home/foo'); -//=> false - -// Running on any OS -pathIsAbsolute.posix('/home/foo'); -//=> true -pathIsAbsolute.posix('C:/Users/foo'); -//=> false -pathIsAbsolute.win32('C:/Users/foo'); -//=> true -pathIsAbsolute.win32('/home/foo'); -//=> false -``` - - -## API - -See the [`path.isAbsolute()` docs](http://nodejs.org/api/path.html#path_path_isabsolute_path). - -### pathIsAbsolute(path) - -### pathIsAbsolute.posix(path) - -POSIX specific version. - -### pathIsAbsolute.win32(path) - -Windows specific version. - - -## License - -MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/picomatch/CHANGELOG.md b/node_modules/picomatch/CHANGELOG.md old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/LICENSE b/node_modules/picomatch/LICENSE old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/README.md b/node_modules/picomatch/README.md old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/index.js b/node_modules/picomatch/index.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/lib/constants.js b/node_modules/picomatch/lib/constants.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/lib/parse.js b/node_modules/picomatch/lib/parse.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/lib/picomatch.js b/node_modules/picomatch/lib/picomatch.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/lib/scan.js b/node_modules/picomatch/lib/scan.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/lib/utils.js b/node_modules/picomatch/lib/utils.js old mode 100755 new mode 100644 diff --git a/node_modules/picomatch/package.json b/node_modules/picomatch/package.json old mode 100755 new mode 100644 diff --git a/node_modules/readdirp/index.js b/node_modules/readdirp/index.js index 30df947..cf739b2 100644 --- a/node_modules/readdirp/index.js +++ b/node_modules/readdirp/index.js @@ -21,7 +21,8 @@ const realpath = promisify(fs.realpath); */ const BANG = '!'; -const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP']); +const RECURSIVE_ERROR_CODE = 'READDIRP_RECURSIVE_ERROR'; +const NORMAL_FLOW_ERRORS = new Set(['ENOENT', 'EPERM', 'EACCES', 'ELOOP', RECURSIVE_ERROR_CODE]); const FILE_TYPE = 'files'; const DIR_TYPE = 'directories'; const FILE_DIR_TYPE = 'files_directories'; @@ -29,6 +30,8 @@ const EVERYTHING_TYPE = 'all'; const ALL_TYPES = [FILE_TYPE, DIR_TYPE, FILE_DIR_TYPE, EVERYTHING_TYPE]; const isNormalFlowError = error => NORMAL_FLOW_ERRORS.has(error.code); +const [maj, min] = process.versions.node.split('.').slice(0, 2).map(n => Number.parseInt(n, 10)); +const wantBigintFsStats = process.platform === 'win32' && (maj > 10 || (maj === 10 && min >= 5)); const normalizeFilter = filter => { if (filter === undefined) return; @@ -91,7 +94,7 @@ class ReaddirpStream extends Readable { const statMethod = opts.lstat ? lstat : stat; // Use bigint stats if it's windows and stat() supports options (node 10+). - if (process.platform === 'win32' && stat.length === 3) { + if (wantBigintFsStats) { this._stat = path => statMethod(path, { bigint: true }); } else { this._stat = statMethod; @@ -166,7 +169,7 @@ class ReaddirpStream extends Readable { } catch (error) { this._onError(error); } - return {files, depth, path}; + return { files, depth, path }; } async _formatEntry(dirent, path) { @@ -174,7 +177,7 @@ class ReaddirpStream extends Readable { try { const basename = this._isDirent ? dirent.name : dirent; const fullPath = sysPath.resolve(sysPath.join(path, basename)); - entry = {path: sysPath.relative(this._root, fullPath), fullPath, basename}; + entry = { path: sysPath.relative(this._root, fullPath), fullPath, basename }; entry[this._statsProp] = this._isDirent ? dirent : await this._stat(fullPath); } catch (err) { this._onError(err); @@ -214,9 +217,11 @@ class ReaddirpStream extends Readable { if (entryRealPathStats.isDirectory()) { const len = entryRealPath.length; if (full.startsWith(entryRealPath) && full.substr(len, 1) === sysPath.sep) { - return this._onError(new Error( + const recursiveError = new Error( `Circular symlink detected: "${full}" points to "${entryRealPath}"` - )); + ); + recursiveError.code = RECURSIVE_ERROR_CODE; + return this._onError(recursiveError); } return 'directory'; } diff --git a/node_modules/readdirp/package.json b/node_modules/readdirp/package.json index 5a35475..dba5388 100644 --- a/node_modules/readdirp/package.json +++ b/node_modules/readdirp/package.json @@ -1,7 +1,7 @@ { "name": "readdirp", "description": "Recursive version of fs.readdir with streaming API.", - "version": "3.5.0", + "version": "3.6.0", "homepage": "https://github.com/paulmillr/readdirp", "repository": { "type": "git", diff --git a/node_modules/sax/LICENSE b/node_modules/sax/LICENSE index ccffa08..6e8e4c1 100644 --- a/node_modules/sax/LICENSE +++ b/node_modules/sax/LICENSE @@ -1,6 +1,6 @@ The ISC License -Copyright (c) Isaac Z. Schlueter and Contributors +Copyright (c) 2010-2022 Isaac Z. Schlueter and Contributors Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above @@ -19,7 +19,7 @@ IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. `String.fromCodePoint` by Mathias Bynens used according to terms of MIT License, as follows: - Copyright Mathias Bynens +Copyright (c) 2010-2022 Mathias Bynens Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/node_modules/sax/lib/sax.js b/node_modules/sax/lib/sax.js index 795d607..ffd441a 100644 --- a/node_modules/sax/lib/sax.js +++ b/node_modules/sax/lib/sax.js @@ -164,6 +164,7 @@ } catch (ex) { Stream = function () {} } + if (!Stream) Stream = function () {} var streamWraps = sax.EVENTS.filter(function (ev) { return ev !== 'error' && ev !== 'end' @@ -1482,9 +1483,16 @@ } if (c === ';') { - parser[buffer] += parseEntity(parser) - parser.entity = '' - parser.state = returnState + if (parser.opt.unparsedEntities) { + var parsedEntity = parseEntity(parser) + parser.entity = '' + parser.state = returnState + parser.write(parsedEntity) + } else { + parser[buffer] += parseEntity(parser) + parser.entity = '' + parser.state = returnState + } } else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) { parser.entity += c } else { @@ -1496,8 +1504,9 @@ continue - default: + default: /* istanbul ignore next */ { throw new Error(parser, 'Unknown state: ' + parser.state) + } } } // while diff --git a/node_modules/sax/package.json b/node_modules/sax/package.json index d2039bf..ad3178a 100644 --- a/node_modules/sax/package.json +++ b/node_modules/sax/package.json @@ -2,12 +2,11 @@ "name": "sax", "description": "An evented streaming XML parser in JavaScript", "author": "Isaac Z. Schlueter (http://blog.izs.me/)", - "version": "1.2.4", + "version": "1.3.0", "main": "lib/sax.js", "license": "ISC", "scripts": { "test": "tap test/*.js --cov -j4", - "posttest": "standard -F test/*.js lib/*.js", "preversion": "npm test", "postversion": "npm publish", "postpublish": "git push origin --all; git push origin --tags" @@ -19,7 +18,12 @@ "README.md" ], "devDependencies": { - "standard": "^8.6.0", - "tap": "^10.5.1" + "tap": "^15.1.6" + }, + "tap": { + "statements": 79, + "branches": 75, + "functions": 80, + "lines": 79 } } diff --git a/node_modules/serialize-javascript/README.md b/node_modules/serialize-javascript/README.md index 1339474..8736fdb 100644 --- a/node_modules/serialize-javascript/README.md +++ b/node_modules/serialize-javascript/README.md @@ -5,7 +5,7 @@ Serialize JavaScript to a _superset_ of JSON that includes regular expressions, [![npm Version][npm-badge]][npm] [![Dependency Status][david-badge]][david] -[![Build Status][travis-badge]][travis] +![Test](https://github.com/yahoo/serialize-javascript/workflows/Test/badge.svg) ## Overview @@ -137,8 +137,6 @@ See the [LICENSE file][LICENSE] for license text and copyright information. [npm-badge]: https://img.shields.io/npm/v/serialize-javascript.svg?style=flat-square [david]: https://david-dm.org/yahoo/serialize-javascript [david-badge]: https://img.shields.io/david/yahoo/serialize-javascript.svg?style=flat-square -[travis]: https://travis-ci.org/yahoo/serialize-javascript -[travis-badge]: https://img.shields.io/travis/yahoo/serialize-javascript.svg?style=flat-square [express-state]: https://github.com/yahoo/express-state [JSON.stringify]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify -[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/master/LICENSE +[LICENSE]: https://github.com/yahoo/serialize-javascript/blob/main/LICENSE diff --git a/node_modules/serialize-javascript/index.js b/node_modules/serialize-javascript/index.js index 640db8f..ab82742 100644 --- a/node_modules/serialize-javascript/index.js +++ b/node_modules/serialize-javascript/index.js @@ -11,7 +11,7 @@ var randomBytes = require('randombytes'); // Generate an internal UID to make the regexp pattern harder to guess. var UID_LENGTH = 16; var UID = generateUID(); -var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B)-' + UID + '-(\\d+)__@"', 'g'); +var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g'); var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g; var IS_PURE_FUNCTION = /function.*?\(/; @@ -72,6 +72,7 @@ module.exports = function serialize(obj, options) { var undefs = []; var infinities= []; var bigInts = []; + var urls = []; // Returns placeholders for functions and regexps (identified by index) // which are later replaced by their string representation. @@ -114,6 +115,10 @@ module.exports = function serialize(obj, options) { return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@'; } } + + if(origValue instanceof URL) { + return '@__L-' + UID + '-' + (urls.push(origValue) - 1) + '__@'; + } } if (type === 'function') { @@ -205,7 +210,7 @@ module.exports = function serialize(obj, options) { str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars); } - if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0) { + if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) { return str; } @@ -252,6 +257,10 @@ module.exports = function serialize(obj, options) { return "BigInt(\"" + bigInts[valueIndex] + "\")"; } + if (type === 'L') { + return "new URL(\"" + urls[valueIndex].toString() + "\")"; + } + var fn = functions[valueIndex]; return serializeFunc(fn); diff --git a/node_modules/serialize-javascript/package.json b/node_modules/serialize-javascript/package.json index b6446e5..caacd5d 100644 --- a/node_modules/serialize-javascript/package.json +++ b/node_modules/serialize-javascript/package.json @@ -1,6 +1,6 @@ { "name": "serialize-javascript", - "version": "5.0.1", + "version": "6.0.0", "description": "Serialize JavaScript to a superset of JSON that includes regular expressions and functions.", "main": "index.js", "scripts": { @@ -27,7 +27,7 @@ "devDependencies": { "benchmark": "^2.1.4", "chai": "^4.1.0", - "mocha": "^8.0.1", + "mocha": "^9.0.0", "nyc": "^15.0.0" }, "dependencies": { diff --git a/node_modules/stream-transform/README.md b/node_modules/stream-transform/README.md index c539391..e0b650f 100644 --- a/node_modules/stream-transform/README.md +++ b/node_modules/stream-transform/README.md @@ -1,17 +1,24 @@ -[![Build Status](https://api.travis-ci.org/adaltas/node-stream-transform.svg)](https://travis-ci.org/#!/adaltas/node-stream-transform) [![NPM](https://img.shields.io/npm/dm/stream-transform)](https://www.npmjs.com/package/stream-transform) [![NPM](https://img.shields.io/npm/v/stream-transform)](https://www.npmjs.com/package/stream-transform) -Part of the [CSV module](https://csv.js.org/), this project is a simple object transformation framework. It implements the Node.js [`stream.Transform` API](http://nodejs.org/api/stream.html#stream_class_stream_transform). It also provides a simple callback-based API for convenience. It is both extremely easy to use and powerful. +# Stream transformation for Node.js and the web + +[![Build Status](https://img.shields.io/github/actions/workflow/status/adaltas/node-csv/nodejs.yml?branch=master)](https://github.com/adaltas/node-csv/actions) +[![NPM](https://img.shields.io/npm/dm/stream-transform)](https://www.npmjs.com/package/stream-transform) +[![NPM](https://img.shields.io/npm/v/stream-transform)](https://www.npmjs.com/package/stream-transform) + +The [`stream-transform` project](https://csv.js.org/transform/) is a simple object transformation framework. It is part of the [CSV project](https://csv.js.org/). + +The Node.js [`stream.Transform` API](http://nodejs.org/api/stream.html#stream_class_stream_transform) is implemented for scalability. The callback-based and sync APIs are also available for convenience. It is both easy to use and powerful. ## Documentation -* [Project homepage](http://csv.js.org/transform/) -* [API](http://csv.js.org/transform/api/) -* [Options](http://csv.js.org/transform/options/) -* [Handler](http://csv.js.org/transform/handler/) -* [State properties](http://csv.js.org/transform/state/) -* [Examples](http://csv.js.org/transform/examples/) +* [Project homepage](https://csv.js.org/transform/) +* [API](https://csv.js.org/transform/api/) +* [Options](https://csv.js.org/transform/options/) +* [Handler](https://csv.js.org/transform/handler/) +* [State properties](https://csv.js.org/transform/state/) +* [Examples](https://csv.js.org/transform/examples/) -## Features +## Main features * Extends the native Node.js [transform stream API](http://nodejs.org/api/stream.html#stream_class_stream_transform) * Simplicity with the optional callback and sync API @@ -26,18 +33,30 @@ Part of the [CSV module](https://csv.js.org/), this project is a simple object t ## Usage -The module is built on the Node.js Stream API. For the sake of simplify, a simple callback API is also provided. To give you a quick look, here's an example of the callback API: +Run `npm install csv` to install the full CSV module or run `npm install csv-transform` if you are only interested by the CSV stringifier. + +The module is built on the Node.js Stream API. Use the callback and sync APIs for simplicity or the stream based API for scalability. + +## Example -```javascript -var transform = require('stream-transform'); +The [API](https://csv.js.org/transform/api/) is available in multiple flavors. This example illustrates the sync API. -input = [ [ '1', '2', '3', '4' ], [ 'a', 'b', 'c', 'd' ] ]; -transform(input, function(data){ - data.push(data.shift()); - return data.join(',')+'\n'; -}, function(err, output){ - output.should.eql([ '2,3,4,1\n', 'b,c,d,a\n' ]); +```js +import { transform } from 'stream-transform/sync'; +import assert from 'assert'; + +const records = transform([ + [ 'a', 'b', 'c', 'd' ], + [ '1', '2', '3', '4' ] +], function(record){ + record.push(record.shift()); + return record; }); + +assert.deepEqual(records, [ + [ 'b', 'c', 'd', 'a' ], + [ '2', '3', '4', '1' ] +]); ``` ## Development @@ -47,3 +66,9 @@ Tests are executed with mocha. To install it, simple run `npm install` followed To generate the JavaScript files, run `npm run coffee`. The test suite is run online with [Travis](http://travis-ci.org/wdavidw/node-stream-transform). See the [Travis definition file](https://github.com/adaltas/node-stream-transform/blob/master/.travis.yml) to view the tested Node.js version. + +## Contributors + +The project is sponsored by [Adaltas](https://www.adaltas.com), an Big Data consulting firm based in Paris, France. + +* David Worms: diff --git a/node_modules/stream-transform/dist/cjs/index.cjs b/node_modules/stream-transform/dist/cjs/index.cjs new file mode 100644 index 0000000..1cc64b3 --- /dev/null +++ b/node_modules/stream-transform/dist/cjs/index.cjs @@ -0,0 +1,165 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; +const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; +}; + +exports.Transformer = Transformer; +exports.transform = transform; diff --git a/node_modules/stream-transform/dist/cjs/index.d.cts b/node_modules/stream-transform/dist/cjs/index.d.cts new file mode 100644 index 0000000..3966298 --- /dev/null +++ b/node_modules/stream-transform/dist/cjs/index.d.cts @@ -0,0 +1,40 @@ +/// + +import * as stream from "stream"; + +export type Handler = (record: T, callback: HandlerCallback, params?: any) => U +export type HandlerCallback = (err?: null | Error, record?: T) => void +export type Callback = (err?: null | Error, output?: string) => void + +export interface Options extends stream.TransformOptions { + /** + * In the absence of a consumer, like a `stream.Readable`, trigger the consumption of the stream. + */ + consume?: boolean + /** + * The number of transformation callbacks to run in parallel; only apply with asynchronous handlers; default to "100". + */ + parallel?: number + /** + * Pass user defined parameters to the user handler as last argument. + */ + params?: any +} +export interface State { + finished: number + running: number + started: number +} +export class Transformer extends stream.Transform { + constructor(options: Options) + readonly options: Options + readonly state: State +} + +declare function transform(handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, handler: Handler, callback?: Callback): Transformer +declare function transform(options: Options, handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, options: Options, handler: Handler, callback?: Callback): Transformer + +export default transform; +export { transform } diff --git a/node_modules/stream-transform/dist/cjs/sync.cjs b/node_modules/stream-transform/dist/cjs/sync.cjs new file mode 100644 index 0000000..85f1eb6 --- /dev/null +++ b/node_modules/stream-transform/dist/cjs/sync.cjs @@ -0,0 +1,145 @@ +'use strict'; + +var stream = require('stream'); +var util = require('util'); + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; + +const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; +}; + +exports.transform = transform; diff --git a/node_modules/stream-transform/dist/cjs/sync.d.cts b/node_modules/stream-transform/dist/cjs/sync.d.cts new file mode 100644 index 0000000..03f4217 --- /dev/null +++ b/node_modules/stream-transform/dist/cjs/sync.d.cts @@ -0,0 +1,10 @@ +/// + +import { Options } from './index.cjs'; + +export type Handler = (record: T) => U +// export default transform; +export function transform(records: Array, handler: Handler): Array +export function transform(records: Array, options: Options, handler: Handler): Array + +export { Options }; diff --git a/node_modules/stream-transform/dist/esm/index.d.ts b/node_modules/stream-transform/dist/esm/index.d.ts new file mode 100644 index 0000000..3966298 --- /dev/null +++ b/node_modules/stream-transform/dist/esm/index.d.ts @@ -0,0 +1,40 @@ +/// + +import * as stream from "stream"; + +export type Handler = (record: T, callback: HandlerCallback, params?: any) => U +export type HandlerCallback = (err?: null | Error, record?: T) => void +export type Callback = (err?: null | Error, output?: string) => void + +export interface Options extends stream.TransformOptions { + /** + * In the absence of a consumer, like a `stream.Readable`, trigger the consumption of the stream. + */ + consume?: boolean + /** + * The number of transformation callbacks to run in parallel; only apply with asynchronous handlers; default to "100". + */ + parallel?: number + /** + * Pass user defined parameters to the user handler as last argument. + */ + params?: any +} +export interface State { + finished: number + running: number + started: number +} +export class Transformer extends stream.Transform { + constructor(options: Options) + readonly options: Options + readonly state: State +} + +declare function transform(handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, handler: Handler, callback?: Callback): Transformer +declare function transform(options: Options, handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, options: Options, handler: Handler, callback?: Callback): Transformer + +export default transform; +export { transform } diff --git a/node_modules/stream-transform/dist/esm/index.js b/node_modules/stream-transform/dist/esm/index.js new file mode 100644 index 0000000..8395fd2 --- /dev/null +++ b/node_modules/stream-transform/dist/esm/index.js @@ -0,0 +1,5355 @@ +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, Stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; +const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; +}; + +export { Transformer, transform }; diff --git a/node_modules/stream-transform/dist/esm/sync.d.ts b/node_modules/stream-transform/dist/esm/sync.d.ts new file mode 100644 index 0000000..538c3e5 --- /dev/null +++ b/node_modules/stream-transform/dist/esm/sync.d.ts @@ -0,0 +1,10 @@ +/// + +import { Options } from './index.js'; + +export type Handler = (record: T) => U +// export default transform; +export function transform(records: Array, handler: Handler): Array +export function transform(records: Array, options: Options, handler: Handler): Array + +export { Options }; diff --git a/node_modules/stream-transform/dist/esm/sync.js b/node_modules/stream-transform/dist/esm/sync.js new file mode 100644 index 0000000..a78312e --- /dev/null +++ b/node_modules/stream-transform/dist/esm/sync.js @@ -0,0 +1,5336 @@ +var domain; + +// This constructor is used to store event handlers. Instantiating this is +// faster than explicitly calling `Object.create(null)` to get a "clean" empty +// object (tested with v8 v4.9). +function EventHandlers() {} +EventHandlers.prototype = Object.create(null); + +function EventEmitter() { + EventEmitter.init.call(this); +} + +// nodejs oddity +// require('events') === require('events').EventEmitter +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.usingDomains = false; + +EventEmitter.prototype.domain = undefined; +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; +}; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; +}; + +function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; +} + +EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); +}; + +// These standalone emit* functions are used to optimize calling of event +// handlers for fast cases because emit() itself often has a variable number of +// arguments and can be deoptimized because of that. These functions always have +// the same number of arguments and thus do not get deoptimized, so the code +// inside them can execute faster. +function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } +} +function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } +} +function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } +} +function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } +} + +function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } +} + +EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; +}; + +function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; +} +function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); +} +EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + +function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; +} + +EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; + +EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + +EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + +EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; +}; + +EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } +}; + +EventEmitter.prototype.listenerCount = listenerCount$1; +function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; +} + +EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; +}; + +// About 1.5x faster than the two-arg version of Array#splice(). +function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); +} + +function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; +} + +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} + +var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; +var inited = false; +function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; +} + +function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') +} + +function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') +} + +function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; +} + +var toString = {}.toString; + +var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +var INSPECT_MAX_BYTES = 50; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + +/* + * Export kMaxLength after typed array support is determined. + */ +kMaxLength(); + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr +}; + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +}; + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +}; + +function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +}; + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that +} + +function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that +} + +function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} +Buffer.isBuffer = isBuffer$1; +function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' +}; + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 +}; + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 +}; + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + + +function base64ToBytes (str) { + return toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + + +// the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence +// The _isBuffer check is for Safari 5-7 support, because it's missing +// Object.prototype.constructor. Remove this eventually +function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) +} + +function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) +} + +// For Node v0.10 support. Remove this eventually. +function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) +} + +// shim for using process in browser +// based off https://github.com/defunctzombie/node-process/blob/master/browser.js + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +var cachedSetTimeout = defaultSetTimout; +var cachedClearTimeout = defaultClearTimeout; +if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; +} +if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; +} + +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} +function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +} +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +var title = 'browser'; +var platform = 'browser'; +var browser = true; +var env = {}; +var argv = []; +var version = ''; // empty string to avoid regexp issues +var versions = {}; +var release = {}; +var config = {}; + +function noop() {} + +var on = noop; +var addListener = noop; +var once = noop; +var off = noop; +var removeListener = noop; +var removeAllListeners = noop; +var emit = noop; + +function binding(name) { + throw new Error('process.binding is not supported'); +} + +function cwd () { return '/' } +function chdir (dir) { + throw new Error('process.chdir is not supported'); +}function umask() { return 0; } + +// from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js +var performance = global$1.performance || {}; +var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + +// generate timestamp or delta +// see http://nodejs.org/api/process.html#process_process_hrtime +function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] +} + +var startTime = new Date(); +function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; +} + +var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime +}; + +var inherits; +if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; +} +var inherits$1 = inherits; + +var formatRegExp = /%[sdj%]/g; +function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +} + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +var debugs = {}; +var debugEnviron; +function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +} + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} + +function isNull(arg) { + return arg === null; +} + +function isNullOrUndefined(arg) { + return arg == null; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isString(arg) { + return typeof arg === 'string'; +} + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} + +function isUndefined(arg) { + return arg === void 0; +} + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} + +function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); +} + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); +} + +function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +} +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog +}; + +function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; +} + +BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; +}; + +BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; +}; + +BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; +}; + +BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; +}; + +BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; +}; + +BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; +}; + +// Copyright Joyent, Inc. and other Node 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. + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +} + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +Readable.ReadableState = ReadableState; + +var debug = debuglog('stream'); +inherits$1(Readable, EventEmitter); + +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } +} +function listenerCount (emitter, type) { + return emitter.listeners(type).length; +} +function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} +function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; +} + +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; +} + +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +Writable.WritableState = WritableState; +inherits$1(Writable, EventEmitter); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; +function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} + +inherits$1(Duplex, Readable); + +var keys = Object.keys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +inherits$1(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} + +inherits$1(PassThrough, Transform); +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; + +inherits$1(Stream, EventEmitter); +Stream.Readable = Readable; +Stream.Writable = Writable; +Stream.Duplex = Duplex; +Stream.Transform = Transform; +Stream.PassThrough = PassThrough; + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EventEmitter.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; +}; + +util.inherits(Transformer, Stream.Transform); + +Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } +}; +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } +}; +Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; + +const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; +}; + +export { transform }; diff --git a/node_modules/stream-transform/dist/iife/index.js b/node_modules/stream-transform/dist/iife/index.js new file mode 100644 index 0000000..402fe41 --- /dev/null +++ b/node_modules/stream-transform/dist/iife/index.js @@ -0,0 +1,5363 @@ +var stream_transform = (function (exports) { + 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; + }; + + exports.Transformer = Transformer; + exports.transform = transform; + + return exports; + +})({}); diff --git a/node_modules/stream-transform/dist/iife/sync.js b/node_modules/stream-transform/dist/iife/sync.js new file mode 100644 index 0000000..ba465ed --- /dev/null +++ b/node_modules/stream-transform/dist/iife/sync.js @@ -0,0 +1,5343 @@ +var stream_transform_sync = (function (exports) { + 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + + const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; + }; + + exports.transform = transform; + + return exports; + +})({}); diff --git a/node_modules/stream-transform/dist/umd/index.js b/node_modules/stream-transform/dist/umd/index.js new file mode 100644 index 0000000..26b5e91 --- /dev/null +++ b/node_modules/stream-transform/dist/umd/index.js @@ -0,0 +1,5364 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv = {})); +})(this, (function (exports) { 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else { + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); + } + return transformer; + }; + + exports.Transformer = Transformer; + exports.transform = transform; + +})); diff --git a/node_modules/stream-transform/dist/umd/sync.js b/node_modules/stream-transform/dist/umd/sync.js new file mode 100644 index 0000000..697be5d --- /dev/null +++ b/node_modules/stream-transform/dist/umd/sync.js @@ -0,0 +1,5344 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.csv = {})); +})(this, (function (exports) { 'use strict'; + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter() { + EventEmitter.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.usingDomains = false; + + EventEmitter.prototype.domain = undefined; + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter.defaultMaxListeners = 10; + + EventEmitter.init = function() { + this.domain = null; + if (EventEmitter.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var inited = false; + function init () { + inited = true; + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + } + + function toByteArray (b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xFF; + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xFF; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xFF; + arr[L++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ''; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3F]; + output += '=='; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3F]; + output += lookup[(tmp << 2) & 0x3F]; + output += '='; + } + + parts.push(output); + + return parts.join('') + } + + function read (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + } + + function write (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString = {}.toString; + + var isArray$1 = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; + }; + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined + ? global$1.TYPED_ARRAY_SUPPORT + : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff + } + + function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr + }; + + function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) ; + } + + function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative') + } + } + + function alloc (that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) + }; + + function allocUnsafe (that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) + }; + + function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that + } + + function fromArrayLike (that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that + } + + function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that + } + + function fromObject (that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len); + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + } + + function checked (length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer (b) { + return !!(b != null && b._isBuffer) + } + + Buffer.compare = function compare (a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } + }; + + Buffer.concat = function concat (list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer + }; + + function byteLength (string, encoding) { + if (internalIsBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string; + } + + var len = string.length; + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString (encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap (b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16 () { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this + }; + + Buffer.prototype.swap32 = function swap32 () { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this + }; + + Buffer.prototype.swap64 = function swap64 () { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this + }; + + Buffer.prototype.toString = function toString () { + var length = this.length | 0; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) + }; + + Buffer.prototype.equals = function equals (b) { + if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 + }; + + Buffer.prototype.inspect = function inspect () { + var str = ''; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); + if (this.length > max) str += ' ... '; + } + return '' + }; + + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && + typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') + } + + function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 + } + + Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 + }; + + Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + }; + + function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i + } + + function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + } + + function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) + } + + function latin1Write (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) + } + + function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) + } + + function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + } + + Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'latin1': + case 'binary': + return latin1Write(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } + }; + + function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf) + } else { + return fromByteArray(buf.slice(start, end)) + } + } + + function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray (codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ''; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res + } + + function asciiSlice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret + } + + function latin1Slice (buf, start, end) { + var ret = ''; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret + } + + function hexSlice (buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ''; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out + } + + function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end); + var res = ''; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res + } + + Buffer.prototype.slice = function slice (start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + } + + Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val + }; + + Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val + }; + + Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) + }; + + Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val + }; + + Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) + }; + + Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val + }; + + Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) + }; + + Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) + }; + + Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4) + }; + + Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4) + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8) + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8) + }; + + function checkInt (buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') + } + + Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = (value & 0xff); + return offset + 1 + }; + + function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8; + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength + }; + + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2 + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2 + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4 + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4 + }; + + function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') + } + + function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 + } + + Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) + }; + + function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ); + } + + return len + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str + } + + function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') + } + + function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) + } + + function utf8ToBytes (string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes + } + + function asciiToBytes (str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray + } + + function utf16leToBytes (str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray + } + + + function base64ToBytes (str) { + return toByteArray(base64clean(str)) + } + + function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i + } + + function isnan (val) { + return val !== val // eslint-disable-line no-self-compare + } + + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + } + + function isFastBuffer (obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer (obj) { + return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + } + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var process = { + nextTick: nextTick, + title: title, + browser: browser, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; + } + var inherits$1 = inherits; + + var formatRegExp = /%[sdj%]/g; + function format(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; + } + + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function() { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; + } + + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = 0; + debugs[set] = function() { + var msg = format.apply(null, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; + } + + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); + } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] + }; + + // Don't use 'blue' not visible on cmd.exe + inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' + }; + + + function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } + } + + + function stylizeNoColor(str, styleType) { + return str; + } + + + function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; + } + + + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); + } + + + function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); + } + + + function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; + } + + + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; + } + + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; + } + + + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function(prev, cur) { + if (cur.indexOf('\n') >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; + } + + + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { + return Array.isArray(ar); + } + + function isBoolean(arg) { + return typeof arg === 'boolean'; + } + + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === 'number'; + } + + function isString(arg) { + return typeof arg === 'string'; + } + + function isSymbol(arg) { + return typeof arg === 'symbol'; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; + } + + function isObject(arg) { + return typeof arg === 'object' && arg !== null; + } + + function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; + } + + function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); + } + + function isFunction(arg) { + return typeof arg === 'function'; + } + + function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; + } + + function isBuffer(maybeBuf) { + return isBuffer$1(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + + function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); + } + + + var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); + } + + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log('%s - %s', timestamp(), format.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var util = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray, + inspect: inspect, + deprecate: deprecate, + format: format, + debuglog: debuglog + }; + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // Copyright Joyent, Inc. and other Node 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. + + var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + Readable.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable, EventEmitter); + + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') { + return emitter.prependListener(event, fn); + } else { + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) + emitter.on(event, fn); + else if (Array.isArray(emitter._events[event])) + emitter._events[event].unshift(fn); + else + emitter._events[event] = [fn, emitter._events[event]]; + } + } + function listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter.call(this); + } + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // if it's past the high water mark, we can push in some more. + // Also, if we have no data yet, we can stand some + // more bytes. This is to work around cases where hwm=0, + // such as the repl. Also, if the push() triggered a + // readable event, and the user called read(largeNumber) such that + // needReadable was set, then we ought to push more, so that another + // 'readable' event will be triggered. + function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); + } + + // backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; + }; + + // Don't raise the hwm > 8MB + var MAX_HWM = 0x800000; + function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; + } + + // you can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + + if (ret !== null) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!isBuffer$1(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); + } + + // at this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + nextTick(maybeReadMore_, stream, state); + } + } + + function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; + } + + // abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (listenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; + }; + + function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable.prototype.on = function (ev, fn) { + var res = EventEmitter.prototype.on.call(this, ev, fn); + + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable.prototype.addListener = Readable.prototype.on; + + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; + }; + + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + nextTick(resume_, stream, state); + } + } + + function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; + }; + + function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} + } + + // wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); + } + + return ret; + } + + // Extracts only enough buffered data to satisfy the amount requested. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); + } else { + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); + } + return ret; + } + + // Copies a specified amount of characters from the list of buffered data + // chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + // Copies a specified amount of bytes from the list of buffered data chunks. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; + } + + function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + nextTick(endReadableNT, state, stream); + } + } + + function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + } + + function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter); + + function nop() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); + } + + WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter.call(this); + } + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); + }; + + function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; + }; + + function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // if we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; + } + + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // Must force callback to be called on nextTick, so that we don't + // emit 'drain' before the write() consumer gets the 'false' return + // value, and has a chance to attach a 'drain' listener. + function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + } + + // if there's something in the buffer waiting, then process it + function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); + }; + + Writable.prototype._writev = null; + + Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; + } + + // It seems a linked list but it is not + // there will be only 2 of these for each stream + function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex, Readable); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // the no-half-open enforcer + function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // a transform stream is a readable/writable stream where you do + // something with the data. Sometimes it's called a "filter", + // but that's not a great name for it, since that implies a thing where + // some bits pass through, and others are simply ignored. (That would + // be a valid example of a transform, of course.) + // + // While the output is causally related to the input, it's not a + // necessarily symmetric or synchronous transformation. For example, + // a zlib stream might take multiple plain-text writes(), and then + // emit a single compressed chunk some time in the future. + // + // Here's how this works: + // + // The Transform stream has all the aspects of the readable and writable + // stream classes. When you write(chunk), that calls _write(chunk,cb) + // internally, and returns false if there's a lot of pending writes + // buffered up. When you call read(), that calls _read(n) until + // there's enough pending readable data buffered up. + // + // In a transform stream, the written data is placed in a buffer. When + // _read(n) is called, it transforms the queued up data, calling the + // buffered _write cb's as it consumes chunks. If consuming a single + // written chunk would result in multiple output chunks, then the first + // outputted bit calls the readcb, and subsequent chunks just go into + // the read buffer, and will cause it to emit 'readable' if necessary. + // + // This way, back-pressure is actually determined by the reading side, + // since _read has to be called to start processing a new chunk. However, + // a pathological inflate type of transform can cause excessive buffering + // here. For example, imagine a stream where every byte of input is + // interpreted as an integer from 0-255, and then results in that many + // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in + // 1kb of data being output. In this case, you could write a very small + // amount of input, and end up with a very large amount of output. In + // such a pathological inflating mechanism, there'd be no way to tell + // the system to stop doing the transform. A single 4MB write could + // cause the system to run out of memory. + // + // However, even in such a pathological case, only a single written chunk + // would be consumed, and then the rest would wait (un-transformed) until + // the results of the previous transformed chunk were consumed. + + inherits$1(Transform, Duplex); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); + }; + + // This is the part where you do stuff! + // override this function in implementation classes. + // 'chunk' is an input chunk. + // + // Call `push(newChunk)` to pass along transformed output + // to the readable side. You may call 'push' zero or more times. + // + // Call `cb(err)` when you are done with this chunk. If you pass + // an error, then that'll put the hurt on the whole operation. If you + // never call cb(), then you'll never get another chunk. + Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } + }; + + // Doesn't matter what the args are here. + // _transform does all the work. + // That we got here means that the readable side wants more data. + Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); + } + + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter); + Stream.Readable = Readable; + Stream.Writable = Writable; + Stream.Duplex = Duplex; + Stream.Transform = Transform; + Stream.PassThrough = PassThrough; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EventEmitter.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; + }; + + const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; + } + this.options.objectMode = true; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; + } + this.handler = handler; + Stream.Transform.call(this, this.options); + this.state = { + running: 0, + started: 0, + finished: 0, + paused: false, + }; + return this; + }; + + util.inherits(Transformer, Stream.Transform); + + Transformer.prototype._transform = function(chunk, _, cb){ + this.state.started++; + this.state.running++; + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ + cb(); + cb = null; // Cancel further callback execution + } + try { + let l = this.handler.length; + if(this.options.params !== null){ + l--; + } + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); + this.handler.call(this, chunk, callback, this.options.params); + }else { + throw Error('Invalid handler arguments'); + } + return false; + } catch (err) { + this.__done(err); + } + }; + Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else { + this._ending = function(){ + cb(); + }; + } + }; + Transformer.prototype.__done = function(err, chunks, cb){ + this.state.running--; + if(err){ + return this.destroy(err); + // return this.emit('error', err); + } + this.state.finished++; + for(let chunk of chunks){ + if (typeof chunk === 'number'){ + chunk = `${chunk}`; + } + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); + } + } + // Chunk has been processed + if(cb){ + cb(); + } + if(this._ending && this.state.running === 0){ + this._ending(); + } + }; + + const transform = function(){ + // Import arguments normalization + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + handler = argument; + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + // Validate arguments + let expected_handler_length = 1; + if(options.params){ + expected_handler_length++; + } + if(handler.length > expected_handler_length){ + throw Error('Invalid Handler: only synchonous handlers are supported'); + } + // Start transformation + const chunks = []; + const transformer = new Transformer(options, handler); + transformer.push = function(chunk){ + chunks.push(chunk); + }; + for(const record of records){ + transformer._transform(record, null, function(){}); + } + return chunks; + }; + + exports.transform = transform; + +})); diff --git a/node_modules/stream-transform/lib/browser/index.js b/node_modules/stream-transform/lib/browser/index.js deleted file mode 100644 index 4fd025e..0000000 --- a/node_modules/stream-transform/lib/browser/index.js +++ /dev/null @@ -1,8765 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (name === '__proto__') { - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; -}; - -exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; - -},{}],2:[function(require,module,exports){ -(function (setImmediate){(function (){ -"use strict"; - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer -// Pass all elements of an array or a stream to transform, filter and add. Features include: -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; -stream = require('stream'); -util = require('util'); - -var _require = require('mixme'); - -clone = _require.clone; - -// ## Usage -// Callback approach, for ease of use: -// `transform(records, [options], handler, callback)` -// Stream API, for maximum of power: -// `transform([records], [options], handler, [callback])` -module.exports = function () { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = _typeof(argument); - - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error("Invalid Arguments: got ".concat(JSON.stringify(argument), " at position ").concat(i)); - } - } - - transform = new Transformer(options, handler); - error = false; - - if (records) { - setImmediate(function () { - var k, len1, record; - - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - - if (error) { - break; - } - - transform.write(record); - } - - return transform.end(); - }); - } - - if (callback || options.consume) { - result = []; - transform.on('readable', function () { - var record, results; - results = []; - - while (record = transform.read()) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - - return results; - }); - transform.on('error', function (err) { - error = true; - - if (callback) { - return callback(err); - } - }); - transform.on('end', function () { - if (callback && !error) { - return callback(null, result); - } - }); - } - - return transform; -}; // ## Transformer -// Options are documented [here](http://csv.js.org/transform/options/). - - -Transformer = function Transformer() { - var options1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var handler1 = arguments.length > 1 ? arguments[1] : undefined; - var base, base1; - this.options = options1; - this.handler = handler1; - - if ((base = this.options).consume == null) { - base.consume = false; - } - - this.options.objectMode = true; - - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; - } - - stream.Transform.call(this, this.options); - this.state = { - running: 0, - started: 0, - finished: 0 - }; - return this; -}; - -util.inherits(Transformer, stream.Transform); -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function (chunk, encoding, cb) { - var _this = this; - - var callback, err, l; - this.state.started++; - this.state.running++; - - if (this.state.running < this.options.parallel) { - cb(); - cb = null; - } - - try { - l = this.handler.length; - - if (this.options.params != null) { - l--; - } - - if (l === 1) { - // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { - // async - callback = function callback(err) { - for (var _len = arguments.length, chunks = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - chunks[_key - 1] = arguments[_key]; - } - - return _this.__done(err, chunks, cb); - }; - - this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); - } - - return false; - } catch (error1) { - err = error1; - return this.__done(err); - } -}; - -Transformer.prototype._flush = function (cb) { - this._ending = function () { - if (this.state.running === 0) { - this._ending = undefined; - return cb(); - } - }; - - return this._ending(); -}; - -Transformer.prototype.__done = function (err, chunks, cb) { - var chunk, j, len; - this.state.running--; - - if (err) { - return this.emit('error', err); - } - - this.state.finished++; - - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - - if (typeof chunk === 'number') { - chunk = "".concat(chunk); - } - - if (chunk != null && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); - } - } - - if (cb) { - cb(); - } - - if (this._ending) { - return this._ending(); - } -}; // [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test - -}).call(this)}).call(this,require("timers").setImmediate) -},{"mixme":1,"stream":25,"timers":41,"util":45}],3:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],4:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],5:[function(require,module,exports){ - -},{}],6:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":4,"buffer":6,"ieee754":18}],7:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":8,"get-intrinsic":14}],8:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":13,"get-intrinsic":14}],9:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":14}],10:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],11:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],12:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],13:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":12}],14:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":13,"has":17,"has-symbols":15}],15:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":16}],16:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],17:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":13}],18:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],19:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],20:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":7}],21:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],22:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":3,"call-bind/callBound":7,"es-abstract/helpers/getOwnPropertyDescriptor":9,"foreach":11,"has-symbols":15}],23:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],24:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":6}],25:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":10,"inherits":19,"readable-stream/lib/_stream_duplex.js":27,"readable-stream/lib/_stream_passthrough.js":28,"readable-stream/lib/_stream_readable.js":29,"readable-stream/lib/_stream_transform.js":30,"readable-stream/lib/_stream_writable.js":31,"readable-stream/lib/internal/streams/end-of-stream.js":35,"readable-stream/lib/internal/streams/pipeline.js":37}],26:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],27:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":29,"./_stream_writable":31,"_process":23,"inherits":19}],28:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":30,"inherits":19}],29:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":26,"./_stream_duplex":27,"./internal/streams/async_iterator":32,"./internal/streams/buffer_list":33,"./internal/streams/destroy":34,"./internal/streams/from":36,"./internal/streams/state":38,"./internal/streams/stream":39,"_process":23,"buffer":6,"events":10,"inherits":19,"string_decoder/":40,"util":5}],30:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":26,"./_stream_duplex":27,"inherits":19}],31:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":26,"./_stream_duplex":27,"./internal/streams/destroy":34,"./internal/streams/state":38,"./internal/streams/stream":39,"_process":23,"buffer":6,"inherits":19,"util-deprecate":42}],32:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":35,"_process":23}],33:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":6,"util":5}],34:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":23}],35:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":26}],36:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],37:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":26,"./end-of-stream":35}],38:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":26}],39:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":10}],40:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":24}],41:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":23,"timers":41}],42:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],43:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],44:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":20,"is-generator-function":21,"is-typed-array":22,"which-typed-array":46}],45:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":43,"./support/types":44,"_process":23,"inherits":19}],46:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":3,"call-bind/callBound":7,"es-abstract/helpers/getOwnPropertyDescriptor":9,"foreach":11,"has-symbols":15,"is-typed-array":22}]},{},[2])(2) -}); diff --git a/node_modules/stream-transform/lib/browser/sync.js b/node_modules/stream-transform/lib/browser/sync.js deleted file mode 100644 index 4cb1e32..0000000 --- a/node_modules/stream-transform/lib/browser/sync.js +++ /dev/null @@ -1,8855 +0,0 @@ -(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.parse = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i ref; i = 1 <= ref ? ++j : --j) { - source = arguments[i]; - - if (exports.is_object_literal(source)) { - if (!exports.is_object_literal(target)) { - target = {}; - } - - for (name in source) { - if (name === '__proto__') { - continue; - } - - target[name] = exports.mutate(target[name], source[name]); - } - } else if (Array.isArray(source)) { - target = function () { - var k, len, results; - results = []; - - for (k = 0, len = source.length; k < len; k++) { - v = source[k]; - results.push(exports.mutate(void 0, v)); - } - - return results; - }(); - } else if (source !== void 0) { - target = source; - } - } - - return target; -}; - -exports.snake_case = function snake_case(source) { - var convert = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; - var name, src, target, u; - target = {}; - - if (exports.is_object_literal(source)) { - u = typeof convert === 'number' && convert > 0 ? convert - 1 : convert; - - for (name in source) { - src = source[name]; - - if (convert) { - name = _snake_case(name); - } - - target[name] = exports.snake_case(src, u); - } - } else { - target = source; - } - - return target; -}; - -exports.compare = function compare(el1, el2) { - var i, j, k, key, keys1, keys2, len, ref; - - if (exports.is_object_literal(el1)) { - if (!exports.is_object_literal(el2)) { - return false; - } - - keys1 = Object.keys(el1).sort(); - keys2 = Object.keys(el2).sort(); - - if (keys1.length !== keys2.length) { - return false; - } - - for (i = j = 0, len = keys1.length; j < len; i = ++j) { - key = keys1[i]; - - if (key !== keys2[i]) { - return false; - } - - if (!exports.compare(el1[key], el2[key])) { - return false; - } - } - } else if (Array.isArray(el1)) { - if (!Array.isArray(el2)) { - return false; - } - - if (el1.length !== el2.length) { - return false; - } - - for (i = k = 0, ref = el1.length; 0 <= ref ? k < ref : k > ref; i = 0 <= ref ? ++k : --k) { - if (!exports.compare(el1[i], el2[i])) { - return false; - } - } - } else { - if (el1 !== el2) { - return false; - } - } - - return true; -}; - -_snake_case = function _snake_case(str) { - return str.replace(/([A-Z])/g, function (_, match, index) { - return '_' + match.toLowerCase(); - }); -}; - -exports.is_object = function is_object(obj) { - return obj && _typeof(obj) === 'object' && !Array.isArray(obj); -}; - -exports.is_object_literal = function is_object_literal(obj) { - var test; - test = obj; - - if (_typeof(obj) !== 'object' || obj === null) { - return false; - } else { - if (Object.getPrototypeOf(test) === null) { - return true; - } - - while (!false) { - if (Object.getPrototypeOf(test = Object.getPrototypeOf(test)) === null) { - break; - } - } - - return Object.getPrototypeOf(obj) === test; - } -}; - -},{}],2:[function(require,module,exports){ -(function (setImmediate){(function (){ -"use strict"; - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer -// Pass all elements of an array or a stream to transform, filter and add. Features include: -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; -stream = require('stream'); -util = require('util'); - -var _require = require('mixme'); - -clone = _require.clone; - -// ## Usage -// Callback approach, for ease of use: -// `transform(records, [options], handler, callback)` -// Stream API, for maximum of power: -// `transform([records], [options], handler, [callback])` -module.exports = function () { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = _typeof(argument); - - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error("Invalid Arguments: got ".concat(JSON.stringify(argument), " at position ").concat(i)); - } - } - - transform = new Transformer(options, handler); - error = false; - - if (records) { - setImmediate(function () { - var k, len1, record; - - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - - if (error) { - break; - } - - transform.write(record); - } - - return transform.end(); - }); - } - - if (callback || options.consume) { - result = []; - transform.on('readable', function () { - var record, results; - results = []; - - while (record = transform.read()) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - - return results; - }); - transform.on('error', function (err) { - error = true; - - if (callback) { - return callback(err); - } - }); - transform.on('end', function () { - if (callback && !error) { - return callback(null, result); - } - }); - } - - return transform; -}; // ## Transformer -// Options are documented [here](http://csv.js.org/transform/options/). - - -Transformer = function Transformer() { - var options1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var handler1 = arguments.length > 1 ? arguments[1] : undefined; - var base, base1; - this.options = options1; - this.handler = handler1; - - if ((base = this.options).consume == null) { - base.consume = false; - } - - this.options.objectMode = true; - - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; - } - - stream.Transform.call(this, this.options); - this.state = { - running: 0, - started: 0, - finished: 0 - }; - return this; -}; - -util.inherits(Transformer, stream.Transform); -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function (chunk, encoding, cb) { - var _this = this; - - var callback, err, l; - this.state.started++; - this.state.running++; - - if (this.state.running < this.options.parallel) { - cb(); - cb = null; - } - - try { - l = this.handler.length; - - if (this.options.params != null) { - l--; - } - - if (l === 1) { - // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { - // async - callback = function callback(err) { - for (var _len = arguments.length, chunks = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - chunks[_key - 1] = arguments[_key]; - } - - return _this.__done(err, chunks, cb); - }; - - this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); - } - - return false; - } catch (error1) { - err = error1; - return this.__done(err); - } -}; - -Transformer.prototype._flush = function (cb) { - this._ending = function () { - if (this.state.running === 0) { - this._ending = undefined; - return cb(); - } - }; - - return this._ending(); -}; - -Transformer.prototype.__done = function (err, chunks, cb) { - var chunk, j, len; - this.state.running--; - - if (err) { - return this.emit('error', err); - } - - this.state.finished++; - - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - - if (typeof chunk === 'number') { - chunk = "".concat(chunk); - } - - if (chunk != null && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); - } - } - - if (cb) { - cb(); - } - - if (this._ending) { - return this._ending(); - } -}; // [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test - -}).call(this)}).call(this,require("timers").setImmediate) -},{"mixme":1,"stream":26,"timers":42,"util":46}],3:[function(require,module,exports){ -"use strict"; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/* -Stream Transform - sync module - -Please look at the [project documentation](https://csv.js.org/transform/) for -additional information. -*/ -var transform = require('.'); - -var _require = require('mixme'), - clone = _require.clone; - -module.exports = function () { - // Import arguments normalization - var handler, callback; - var options = {}; - - for (i in arguments) { - var argument = arguments[i]; - - var type = _typeof(argument); - - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error("Invalid Arguments: got ".concat(JSON.stringify(argument), " at position ").concat(i)); - } - } // Validate arguments - - - var expected_handler_length = 1; - - if (options.params) { - expected_handler_length++; - } - - if (handler.length > expected_handler_length) { - throw Error('Invalid Handler: only synchonous handlers are supported'); - } // Start transformation - - - var chunks = []; - var transformer = new transform.Transformer(options, handler); - - transformer.push = function (chunk) { - chunks.push(chunk); - }; - - var _iterator = _createForOfIteratorHelper(records), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var record = _step.value; - - transformer._transform(record, null, function () {}); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return chunks; -}; - -},{".":2,"mixme":1}],4:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var possibleNames = [ - 'BigInt64Array', - 'BigUint64Array', - 'Float32Array', - 'Float64Array', - 'Int16Array', - 'Int32Array', - 'Int8Array', - 'Uint16Array', - 'Uint32Array', - 'Uint8Array', - 'Uint8ClampedArray' -]; - -module.exports = function availableTypedArrays() { - var out = []; - for (var i = 0; i < possibleNames.length; i++) { - if (typeof global[possibleNames[i]] === 'function') { - out[out.length] = possibleNames[i]; - } - } - return out; -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],5:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],6:[function(require,module,exports){ - -},{}],7:[function(require,module,exports){ -(function (Buffer){(function (){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } } - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -}).call(this)}).call(this,require("buffer").Buffer) -},{"base64-js":5,"buffer":7,"ieee754":19}],8:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var callBind = require('./'); - -var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - -module.exports = function callBoundIntrinsic(name, allowMissing) { - var intrinsic = GetIntrinsic(name, !!allowMissing); - if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { - return callBind(intrinsic); - } - return intrinsic; -}; - -},{"./":9,"get-intrinsic":15}],9:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); -var GetIntrinsic = require('get-intrinsic'); - -var $apply = GetIntrinsic('%Function.prototype.apply%'); -var $call = GetIntrinsic('%Function.prototype.call%'); -var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); -var $max = GetIntrinsic('%Math.max%'); - -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = null; - } -} - -module.exports = function callBind(originalFunction) { - var func = $reflectApply(bind, $call, arguments); - if ($gOPD && $defineProperty) { - var desc = $gOPD(func, 'length'); - if (desc.configurable) { - // original length, plus the receiver, minus any additional arguments (after the receiver) - $defineProperty( - func, - 'length', - { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } - ); - } - } - return func; -}; - -var applyBind = function applyBind() { - return $reflectApply(bind, $apply, arguments); -}; - -if ($defineProperty) { - $defineProperty(module.exports, 'apply', { value: applyBind }); -} else { - module.exports.apply = applyBind; -} - -},{"function-bind":14,"get-intrinsic":15}],10:[function(require,module,exports){ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%'); -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; - -},{"get-intrinsic":15}],11:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -var R = typeof Reflect === 'object' ? Reflect : null -var ReflectApply = R && typeof R.apply === 'function' - ? R.apply - : function ReflectApply(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); - } - -var ReflectOwnKeys -if (R && typeof R.ownKeys === 'function') { - ReflectOwnKeys = R.ownKeys -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target) - .concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys(target) { - return Object.getOwnPropertyNames(target); - }; -} - -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} - -var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { - return value !== value; -} - -function EventEmitter() { - EventEmitter.init.call(this); -} -module.exports = EventEmitter; -module.exports.once = once; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._eventsCount = 0; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -function checkListener(listener) { - if (typeof listener !== 'function') { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} - -Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); - } - defaultMaxListeners = arg; - } -}); - -EventEmitter.init = function() { - - if (this._events === undefined || - this._events === Object.getPrototypeOf(this)._events) { - this._events = Object.create(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -}; - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); - } - this._maxListeners = n; - return this; -}; - -function _getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; - -EventEmitter.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = (type === 'error'); - - var events = this._events; - if (events !== undefined) - doError = (doError && events.error === undefined); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - // Note: The comments on the `throw` lines are intentional, they show - // up in Node's output if this results in an unhandled exception. - throw er; // Unhandled 'error' event - } - // At least give some kind of context to the user - var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); - err.context = er; - throw err; // Unhandled 'error' event - } - - var handler = events[type]; - - if (handler === undefined) - return false; - - if (typeof handler === 'function') { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners[i], this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - checkListener(listener); - - events = target._events; - if (events === undefined) { - events = target._events = Object.create(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener !== undefined) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (existing === undefined) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - // If we've already got an array, just append. - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - - // Check for listener leak - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - // No error code for this since it is a Warning - // eslint-disable-next-line no-restricted-syntax - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' ' + String(type) + ' listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - checkListener(listener); - - events = this._events; - if (events === undefined) - return this; - - list = events[type]; - if (list === undefined) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener !== undefined) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (events === undefined) - return this; - - // not listening for removeListener, no need to emit - if (events.removeListener === undefined) { - if (arguments.length === 0) { - this._events = Object.create(null); - this._eventsCount = 0; - } else if (events[type] !== undefined) { - if (--this._eventsCount === 0) - this._events = Object.create(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = Object.keys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = Object.create(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners !== undefined) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (events === undefined) - return []; - - var evlistener = events[type]; - if (evlistener === undefined) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? - unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events !== undefined) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener !== undefined) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function spliceOne(list, index) { - for (; index + 1 < list.length; index++) - list[index] = list[index + 1]; - list.pop(); -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function once(emitter, name) { - return new Promise(function (resolve, reject) { - function errorListener(err) { - emitter.removeListener(name, resolver); - reject(err); - } - - function resolver() { - if (typeof emitter.removeListener === 'function') { - emitter.removeListener('error', errorListener); - } - resolve([].slice.call(arguments)); - }; - - eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); - if (name !== 'error') { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} - -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === 'function') { - eventTargetAgnosticAddListener(emitter, 'error', handler, flags); - } -} - -function eventTargetAgnosticAddListener(emitter, name, listener, flags) { - if (typeof emitter.on === 'function') { - if (flags.once) { - emitter.once(name, listener); - } else { - emitter.on(name, listener); - } - } else if (typeof emitter.addEventListener === 'function') { - // EventTarget does not have `error` event semantics like Node - // EventEmitters, we do not listen for `error` events here. - emitter.addEventListener(name, function wrapListener(arg) { - // IE does not have builtin `{ once: true }` support so we - // have to do it manually. - if (flags.once) { - emitter.removeEventListener(name, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} - -},{}],12:[function(require,module,exports){ - -var hasOwn = Object.prototype.hasOwnProperty; -var toString = Object.prototype.toString; - -module.exports = function forEach (obj, fn, ctx) { - if (toString.call(fn) !== '[object Function]') { - throw new TypeError('iterator must be a function'); - } - var l = obj.length; - if (l === +l) { - for (var i = 0; i < l; i++) { - fn.call(ctx, obj[i], i, obj); - } - } else { - for (var k in obj) { - if (hasOwn.call(obj, k)) { - fn.call(ctx, obj[k], k, obj); - } - } - } -}; - - -},{}],13:[function(require,module,exports){ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slice.call(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; - - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); - } - - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; - -},{}],14:[function(require,module,exports){ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; - -},{"./implementation":13}],15:[function(require,module,exports){ -'use strict'; - -var undefined; - -var $SyntaxError = SyntaxError; -var $Function = Function; -var $TypeError = TypeError; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = Object.getOwnPropertyDescriptor; -if ($gOPD) { - try { - $gOPD({}, ''); - } catch (e) { - $gOPD = null; // this is IE 8, which has a broken gOPD - } -} - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': EvalError, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': Object, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': RangeError, - '%ReferenceError%': ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet -}; - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('has'); -var $concat = bind.call(Function.call, Array.prototype.concat); -var $spliceApply = bind.call(Function.apply, Array.prototype.splice); -var $replace = bind.call(Function.call, String.prototype.replace); -var $strSlice = bind.call(Function.call, String.prototype.slice); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; - -},{"function-bind":14,"has":18,"has-symbols":16}],16:[function(require,module,exports){ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; - -},{"./shams":17}],17:[function(require,module,exports){ -'use strict'; - -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - var descriptor = Object.getOwnPropertyDescriptor(obj, sym); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; - -},{}],18:[function(require,module,exports){ -'use strict'; - -var bind = require('function-bind'); - -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); - -},{"function-bind":14}],19:[function(require,module,exports){ -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],20:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } - } -} - -},{}],21:[function(require,module,exports){ -'use strict'; - -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); - -var isStandardArguments = function isArguments(value) { - if (hasToStringTag && value && typeof value === 'object' && Symbol.toStringTag in value) { - return false; - } - return $toString(value) === '[object Arguments]'; -}; - -var isLegacyArguments = function isArguments(value) { - if (isStandardArguments(value)) { - return true; - } - return value !== null && - typeof value === 'object' && - typeof value.length === 'number' && - value.length >= 0 && - $toString(value) !== '[object Array]' && - $toString(value.callee) === '[object Function]'; -}; - -var supportsStandardArguments = (function () { - return isStandardArguments(arguments); -}()); - -isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests - -module.exports = supportsStandardArguments ? isStandardArguments : isLegacyArguments; - -},{"call-bind/callBound":8}],22:[function(require,module,exports){ -'use strict'; - -var toStr = Object.prototype.toString; -var fnToStr = Function.prototype.toString; -var isFnRegex = /^\s*(?:function)?\*/; -var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; -var getProto = Object.getPrototypeOf; -var getGeneratorFunc = function () { // eslint-disable-line consistent-return - if (!hasToStringTag) { - return false; - } - try { - return Function('return function*() {}')(); - } catch (e) { - } -}; -var GeneratorFunction; - -module.exports = function isGeneratorFunction(fn) { - if (typeof fn !== 'function') { - return false; - } - if (isFnRegex.test(fnToStr.call(fn))) { - return true; - } - if (!hasToStringTag) { - var str = toStr.call(fn); - return str === '[object GeneratorFunction]'; - } - if (!getProto) { - return false; - } - if (typeof GeneratorFunction === 'undefined') { - var generatorFunc = getGeneratorFunc(); - GeneratorFunction = generatorFunc ? getProto(generatorFunc) : false; - } - return getProto(fn) === GeneratorFunction; -}; - -},{}],23:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) { - for (var i = 0; i < array.length; i += 1) { - if (array[i] === value) { - return i; - } - } - return -1; -}; -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var anyTrue = false; - forEach(toStrTags, function (getter, typedArray) { - if (!anyTrue) { - try { - anyTrue = getter.call(value) === typedArray; - } catch (e) { /**/ } - } - }); - return anyTrue; -}; - -module.exports = function isTypedArray(value) { - if (!value || typeof value !== 'object') { return false; } - if (!hasToStringTag) { - var tag = $slice($toString(value), 8, -1); - return $indexOf(typedArrays, tag) > -1; - } - if (!gOPD) { return false; } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":4,"call-bind/callBound":8,"es-abstract/helpers/getOwnPropertyDescriptor":10,"foreach":12,"has-symbols":16}],24:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],25:[function(require,module,exports){ -/*! safe-buffer. MIT License. Feross Aboukhadijeh */ -/* eslint-disable node/no-deprecated-api */ -var buffer = require('buffer') -var Buffer = buffer.Buffer - -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} - -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.prototype = Object.create(Buffer.prototype) - -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) - -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} - -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} - -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} - -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} - -},{"buffer":7}],26:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/lib/_stream_readable.js'); -Stream.Writable = require('readable-stream/lib/_stream_writable.js'); -Stream.Duplex = require('readable-stream/lib/_stream_duplex.js'); -Stream.Transform = require('readable-stream/lib/_stream_transform.js'); -Stream.PassThrough = require('readable-stream/lib/_stream_passthrough.js'); -Stream.finished = require('readable-stream/lib/internal/streams/end-of-stream.js') -Stream.pipeline = require('readable-stream/lib/internal/streams/pipeline.js') - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":11,"inherits":20,"readable-stream/lib/_stream_duplex.js":28,"readable-stream/lib/_stream_passthrough.js":29,"readable-stream/lib/_stream_readable.js":30,"readable-stream/lib/_stream_transform.js":31,"readable-stream/lib/_stream_writable.js":32,"readable-stream/lib/internal/streams/end-of-stream.js":36,"readable-stream/lib/internal/streams/pipeline.js":38}],27:[function(require,module,exports){ -'use strict'; - -function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } - -var codes = {}; - -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error; - } - - function getMessage(arg1, arg2, arg3) { - if (typeof message === 'string') { - return message; - } else { - return message(arg1, arg2, arg3); - } - } - - var NodeError = - /*#__PURE__*/ - function (_Base) { - _inheritsLoose(NodeError, _Base); - - function NodeError(arg1, arg2, arg3) { - return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; - } - - return NodeError; - }(Base); - - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; - codes[code] = NodeError; -} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js - - -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - var len = expected.length; - expected = expected.map(function (i) { - return String(i); - }); - - if (len > 2) { - return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; - } else if (len === 2) { - return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); - } else { - return "of ".concat(thing, " ").concat(expected[0]); - } - } else { - return "of ".concat(thing, " ").concat(String(expected)); - } -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith - - -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith - - -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - - return str.substring(this_len - search.length, this_len) === search; -} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes - - -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } - - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} - -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"'; -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - var determiner; - - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } - - var msg; - - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } else { - var type = includes(name, '.') ? 'property' : 'argument'; - msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); - } - - msg += ". Received type ".concat(typeof actual); - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented'; -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg; -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); -module.exports.codes = codes; - -},{}],28:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. -'use strict'; -/**/ - -var objectKeys = Object.keys || function (obj) { - var keys = []; - - for (var key in obj) { - keys.push(key); - } - - return keys; -}; -/**/ - - -module.exports = Duplex; - -var Readable = require('./_stream_readable'); - -var Writable = require('./_stream_writable'); - -require('inherits')(Duplex, Readable); - -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); // the no-half-open enforcer - -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; // no more data can be written. - // But allow more writes to happen in this tick. - - process.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); -}).call(this)}).call(this,require('_process')) -},{"./_stream_readable":30,"./_stream_writable":32,"_process":24,"inherits":20}],29:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -require('inherits')(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":31,"inherits":20}],30:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -'use strict'; - -module.exports = Readable; -/**/ - -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; -/**/ - -var EE = require('events').EventEmitter; - -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ - - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} -/**/ - - -var debugUtil = require('util'); - -var debug; - -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ - - -var BufferList = require('./internal/streams/buffer_list'); - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance. - - -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; - -require('inherits')(Readable, Stream); - -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - - this.sync = true; // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish') - - this.autoDestroy = !!options.autoDestroy; // has it been destroyed - - this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s - - this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled - - this.readingMore = false; - this.decoder = null; - this.encoding = null; - - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); // legacy - - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; - -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; // Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. - - -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; // Unshift should *always* be something directly out of read() - - -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - debug('readableAddChunk', chunk); - var state = stream._readableState; - - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - - if (er) { - errorOrDestroy(stream, er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true); - } else if (state.ended) { - errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); - } else if (state.destroyed) { - return false; - } else { - state.reading = false; - - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - maybeReadMore(stream, state); - } - } // We can push more data if we are below the highWaterMark. - // Also, if we have no data yet, we can stand some more bytes. - // This is to work around cases where hwm=0, such as the repl. - - - return !state.ended && (state.length < state.highWaterMark || state.length === 0); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - state.awaitDrain = 0; - stream.emit('data', chunk); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); - } - - return er; -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; // backwards compatibility. - - -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - var decoder = new StringDecoder(enc); - this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8 - - this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers: - - var p = this._readableState.buffer.head; - var content = ''; - - while (p !== null) { - content += decoder.write(p.data); - p = p.next; - } - - this._readableState.buffer.clear(); - - if (content !== '') this._readableState.buffer.push(content); - this._readableState.length = content.length; - return this; -}; // Don't raise the hwm > 1GB - - -var MAX_HWM = 0x40000000; - -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE. - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - - return n; -} // This function is designed to be inlinable, so please take care when making -// changes to the function body. - - -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } // If we're asking for more than the current hwm, then raise the hwm. - - - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; // Don't have enough - - if (!state.ended) { - state.needReadable = true; - return 0; - } - - return state.length; -} // you can override either this method, or the async _read(n) below. - - -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - - if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. - - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - // if we need a readable event, then we need to do some reading. - - - var doRead = state.needReadable; - debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some - - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - - - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; // if the length is currently zero, then we *need* a readable event. - - if (state.length === 0) state.needReadable = true; // call internal read method - - this._read(state.highWaterMark); - - state.sync = false; // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = state.length <= state.highWaterMark; - n = 0; - } else { - state.length -= n; - state.awaitDrain = 0; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. - - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - return ret; -}; - -function onEofChunk(stream, state) { - debug('onEofChunk'); - if (state.ended) return; - - if (state.decoder) { - var chunk = state.decoder.end(); - - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - - state.ended = true; - - if (state.sync) { - // if we are sync, wait until next tick to emit the data. - // Otherwise we risk emitting data in the flow() - // the readable code triggers during a read() call - emitReadable(stream); - } else { - // emit 'readable' now to make sure it gets picked up. - state.needReadable = false; - - if (!state.emittedReadable) { - state.emittedReadable = true; - emitReadable_(stream); - } - } -} // Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. - - -function emitReadable(stream) { - var state = stream._readableState; - debug('emitReadable', state.needReadable, state.emittedReadable); - state.needReadable = false; - - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - process.nextTick(emitReadable_, stream); - } -} - -function emitReadable_(stream) { - var state = stream._readableState; - debug('emitReadable_', state.destroyed, state.length, state.ended); - - if (!state.destroyed && (state.length || state.ended)) { - stream.emit('readable'); - state.emittedReadable = false; - } // The stream needs another readable event if - // 1. It is not flowing, as the flow mechanism will take - // care of it. - // 2. It is not ended. - // 3. It is below the highWaterMark, so we can schedule - // another readable later. - - - state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; - flow(stream); -} // at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. - - -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - // Attempt to read more data if we should. - // - // The conditions for reading more data are (one of): - // - Not enough data buffered (state.length < state.highWaterMark). The loop - // is responsible for filling the buffer with enough data if such data - // is available. If highWaterMark is 0 and we are not in the flowing mode - // we should _not_ attempt to buffer any extra data. We'll get more data - // when the stream consumer calls read() instead. - // - No data in the buffer, and the stream is in flowing mode. In this mode - // the loop below is responsible for ensuring read() is called. Failing to - // call read here would abort the flow and there's no other mechanism for - // continuing the flow if the stream consumer has just subscribed to the - // 'data' event. - // - // In addition to the above conditions to keep reading data, the following - // conditions prevent the data from being read: - // - The stream has ended (state.ended). - // - There is already a pending 'read' operation (state.reading). This is a - // case where the the stream has called the implementation defined _read() - // method, but they are processing the call asynchronously and have _not_ - // called push() with new data. In this case we skip performing more - // read()s. The execution ends in this method again after the _read() ends - // up calling push() with more data. - while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) { - var len = state.length; - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) // didn't get any data, stop spinning. - break; - } - - state.readingMore = false; -} // abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. - - -Readable.prototype._read = function (n) { - errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - - case 1: - state.pipes = [state.pipes, dest]; - break; - - default: - state.pipes.push(dest); - break; - } - - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn); - dest.on('unpipe', onunpipe); - - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - - - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - var cleanedUp = false; - - function cleanup() { - debug('cleanup'); // cleanup event handlers once the pipe is broken - - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - cleanedUp = true; // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - src.on('data', ondata); - - function ondata(chunk) { - debug('ondata'); - var ret = dest.write(chunk); - debug('dest.write', ret); - - if (ret === false) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - } - - src.pause(); - } - } // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - - - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er); - } // Make sure our error handler is attached before userland ones. - - - prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. - - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - - dest.once('close', onclose); - - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } // tell the dest that it's being piped to - - - dest.emit('pipe', src); // start the flow if it hasn't been started already. - - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function pipeOnDrainFunctionResult() { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { - hasUnpiped: false - }; // if we're not piping anywhere, then do nothing. - - if (state.pipesCount === 0) return this; // just one destination. most common case. - - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - if (!dest) dest = state.pipes; // got a match. - - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } // slow case. multiple pipe destinations. - - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { - hasUnpiped: false - }); - } - - return this; - } // try to find the right one. - - - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - dest.emit('unpipe', this, unpipeInfo); - return this; -}; // set up data events if they are asked for -// Ensure readable listeners eventually get something - - -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - var state = this._readableState; - - if (ev === 'data') { - // update readableListening so that resume() may be a no-op - // a few lines down. This is needed to support once('readable'). - state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused - - if (state.flowing !== false) this.resume(); - } else if (ev === 'readable') { - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.flowing = false; - state.emittedReadable = false; - debug('on readable', state.length, state.reading); - - if (state.length) { - emitReadable(this); - } else if (!state.reading) { - process.nextTick(nReadingNextTick, this); - } - } - } - - return res; -}; - -Readable.prototype.addListener = Readable.prototype.on; - -Readable.prototype.removeListener = function (ev, fn) { - var res = Stream.prototype.removeListener.call(this, ev, fn); - - if (ev === 'readable') { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -Readable.prototype.removeAllListeners = function (ev) { - var res = Stream.prototype.removeAllListeners.apply(this, arguments); - - if (ev === 'readable' || ev === undefined) { - // We need to check if there is someone still listening to - // readable and reset the state. However this needs to happen - // after readable has been emitted but before I/O (nextTick) to - // support once('readable', fn) cycles. This means that calling - // resume within the same tick will have no - // effect. - process.nextTick(updateReadableListening, this); - } - - return res; -}; - -function updateReadableListening(self) { - var state = self._readableState; - state.readableListening = self.listenerCount('readable') > 0; - - if (state.resumeScheduled && !state.paused) { - // flowing needs to be set to true now, otherwise - // the upcoming resume will not flow. - state.flowing = true; // crude way to check if we should resume - } else if (self.listenerCount('data') > 0) { - self.resume(); - } -} - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} // pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. - - -Readable.prototype.resume = function () { - var state = this._readableState; - - if (!state.flowing) { - debug('resume'); // we flow only if there is no one listening - // for readable, but we still have to call - // resume() - - state.flowing = !state.readableListening; - resume(this, state); - } - - state.paused = false; - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - process.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - debug('resume', state.reading); - - if (!state.reading) { - stream.read(0); - } - - state.resumeScheduled = false; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - - if (this._readableState.flowing !== false) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - - this._readableState.paused = true; - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - - while (state.flowing && stream.read() !== null) { - ; - } -} // wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. - - -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode - - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - - if (!ret) { - paused = true; - stream.pause(); - } - }); // proxy all the other methods. - // important when wrapping filters and duplexes. - - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function methodWrap(method) { - return function methodWrapReturnFunction() { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } // proxy certain important events. - - - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } // when we try to consume some more bytes, simply unpause the - // underlying stream. - - - this._read = function (n) { - debug('wrapped _read', n); - - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -if (typeof Symbol === 'function') { - Readable.prototype[Symbol.asyncIterator] = function () { - if (createReadableStreamAsyncIterator === undefined) { - createReadableStreamAsyncIterator = require('./internal/streams/async_iterator'); - } - - return createReadableStreamAsyncIterator(this); - }; -} - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.highWaterMark; - } -}); -Object.defineProperty(Readable.prototype, 'readableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState && this._readableState.buffer; - } -}); -Object.defineProperty(Readable.prototype, 'readableFlowing', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.flowing; - }, - set: function set(state) { - if (this._readableState) { - this._readableState.flowing = state; - } - } -}); // exposed for testing purposes only. - -Readable._fromList = fromList; -Object.defineProperty(Readable.prototype, 'readableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._readableState.length; - } -}); // Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. - -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = state.buffer.consume(n, state.decoder); - } - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - debug('endReadable', state.endEmitted); - - if (!state.endEmitted) { - state.ended = true; - process.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift. - - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the writable side is ready for autoDestroy as well - var wState = stream._writableState; - - if (!wState || wState.autoDestroy && wState.finished) { - stream.destroy(); - } - } - } -} - -if (typeof Symbol === 'function') { - Readable.from = function (iterable, opts) { - if (from === undefined) { - from = require('./internal/streams/from'); - } - - return from(Readable, iterable, opts); - }; -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - - return -1; -} -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":27,"./_stream_duplex":28,"./internal/streams/async_iterator":33,"./internal/streams/buffer_list":34,"./internal/streams/destroy":35,"./internal/streams/from":37,"./internal/streams/state":39,"./internal/streams/stream":40,"_process":24,"buffer":7,"events":11,"inherits":20,"string_decoder/":41,"util":6}],31:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. -'use strict'; - -module.exports = Transform; - -var _require$codes = require('../errors').codes, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, - ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; - -var Duplex = require('./_stream_duplex'); - -require('inherits')(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - var cb = ts.writecb; - - if (cb === null) { - return this.emit('error', new ERR_MULTIPLE_CALLBACK()); - } - - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - cb(er); - var rs = this._readableState; - rs.reading = false; - - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; // start out asking for a readable event once data is transformed. - - this._readableState.needReadable = true; // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - if (typeof options.flush === 'function') this._flush = options.flush; - } // When the writable side finishes, then flush out anything remaining. - - - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function' && !this._readableState.destroyed) { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; // This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. - - -Transform.prototype._transform = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; // Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. - - -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && !ts.transforming) { - ts.transforming = true; - - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); // TODO(BridgeAR): Write a test for these two error cases - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - - if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); - if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); - return stream.push(null); -} -},{"../errors":27,"./_stream_duplex":28,"inherits":20}],32:[function(require,module,exports){ -(function (process,global){(function (){ -// Copyright Joyent, Inc. and other Node 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. -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. -'use strict'; - -module.exports = Writable; -/* */ - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} // It seems a linked list but it is not -// there will be only 2 of these for each stream - - -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ - - -var Duplex; -/**/ - -Writable.WritableState = WritableState; -/**/ - -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ - -var Stream = require('./internal/streams/stream'); -/**/ - - -var Buffer = require('buffer').Buffer; - -var OurUint8Array = global.Uint8Array || function () {}; - -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} - -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -var destroyImpl = require('./internal/streams/destroy'); - -var _require = require('./internal/streams/state'), - getHighWaterMark = _require.getHighWaterMark; - -var _require$codes = require('../errors').codes, - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, - ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, - ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, - ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, - ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; - -var errorOrDestroy = destroyImpl.errorOrDestroy; - -require('inherits')(Writable, Stream); - -function nop() {} - -function WritableState(options, stream, isDuplex) { - Duplex = Duplex || require('./_stream_duplex'); - options = options || {}; // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream, - // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. - - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream - // contains buffers or objects. - - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - - this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called - - this.finalCalled = false; // drain event flag. - - this.needDrain = false; // at the start of calling end() - - this.ending = false; // when end() has been called, and returned - - this.ended = false; // when 'finish' is emitted - - this.finished = false; // has it been destroyed - - this.destroyed = false; // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - - this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - - this.length = 0; // a flag to see when we're in the middle of a write. - - this.writing = false; // when true all writes will be buffered until .uncork() call - - this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - - this.sync = true; // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - - this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) - - this.onwrite = function (er) { - onwrite(stream, er); - }; // the callback that the user supplies to write(chunk,encoding,cb) - - - this.writecb = null; // the amount that is being written when _write is called. - - this.writelen = 0; - this.bufferedRequest = null; - this.lastBufferedRequest = null; // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - - this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - - this.prefinished = false; // True if the error was already emitted and should not be thrown again - - this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. - - this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') - - this.autoDestroy = !!options.autoDestroy; // count buffered requests - - this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - - while (current) { - out.push(current); - current = current.next; - } - - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function writableStateBufferGetter() { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); // Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. - - -var realHasInstance; - -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function value(object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function realHasInstance(object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - // Checking for a Stream.Duplex instance is faster here instead of inside - // the WritableState constructor, at least with V8 6.5 - - var isDuplex = this instanceof Duplex; - if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); - this._writableState = new WritableState(options, this, isDuplex); // legacy. - - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - if (typeof options.writev === 'function') this._writev = options.writev; - if (typeof options.destroy === 'function') this._destroy = options.destroy; - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} // Otherwise people can pipe Writable streams, which is just wrong. - - -Writable.prototype.pipe = function () { - errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); -}; - -function writeAfterEnd(stream, cb) { - var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb - - errorOrDestroy(stream, er); - process.nextTick(cb, er); -} // Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. - - -function validChunk(stream, state, chunk, cb) { - var er; - - if (chunk === null) { - er = new ERR_STREAM_NULL_VALUES(); - } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); - } - - if (er) { - errorOrDestroy(stream, er); - process.nextTick(cb, er); - return false; - } - - return true; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - if (typeof cb !== 'function') cb = nop; - if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - return ret; -}; - -Writable.prototype.cork = function () { - this._writableState.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); // if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. - -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - - var len = state.objectMode ? 1 : chunk.length; - state.length += len; - var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. - - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - process.nextTick(cb, er); // this can emit finish, and it will always happen - // after error - - process.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - errorOrDestroy(stream, er); // this can emit finish, but finish must - // always follow error - - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); - onwriteStateUpdate(state); - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state) || stream.destroyed; - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - process.nextTick(afterWrite, stream, state, finished, cb); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} // Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. - - -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} // if there's something in the buffer waiting, then process it - - -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - var count = 0; - var allBuffers = true; - - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - - buffer.allBuffers = allBuffers; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - - state.pendingcb++; - state.lastBufferedRequest = null; - - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks - - if (state.corked) { - state.corked = 1; - this.uncork(); - } // ignore unnecessary end() calls. - - - if (!state.ending) endWritable(this, state, cb); - return this; -}; - -Object.defineProperty(Writable.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} - -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - - if (err) { - errorOrDestroy(stream, err); - } - - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} - -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function' && !state.destroyed) { - state.pendingcb++; - state.finalCalled = true; - process.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - - if (need) { - prefinish(stream, state); - - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - - if (state.autoDestroy) { - // In case of duplex streams we need a way to detect - // if the readable side is ready for autoDestroy as well - var rState = stream._readableState; - - if (!rState || rState.autoDestroy && rState.endEmitted) { - stream.destroy(); - } - } - } - } - - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - - if (cb) { - if (state.finished) process.nextTick(cb);else stream.once('finish', cb); - } - - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } // reuse the free corkReq. - - - state.corkedRequestsFree.next = corkReq; -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._writableState === undefined) { - return false; - } - - return this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } // backward compatibility, the user is explicitly - // managing destroyed - - - this._writableState.destroyed = value; - } -}); -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; - -Writable.prototype._destroy = function (err, cb) { - cb(err); -}; -}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../errors":27,"./_stream_duplex":28,"./internal/streams/destroy":35,"./internal/streams/state":39,"./internal/streams/stream":40,"_process":24,"buffer":7,"inherits":20,"util-deprecate":43}],33:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; - -var _Object$setPrototypeO; - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -var finished = require('./end-of-stream'); - -var kLastResolve = Symbol('lastResolve'); -var kLastReject = Symbol('lastReject'); -var kError = Symbol('error'); -var kEnded = Symbol('ended'); -var kLastPromise = Symbol('lastPromise'); -var kHandlePromise = Symbol('handlePromise'); -var kStream = Symbol('stream'); - -function createIterResult(value, done) { - return { - value: value, - done: done - }; -} - -function readAndResolve(iter) { - var resolve = iter[kLastResolve]; - - if (resolve !== null) { - var data = iter[kStream].read(); // we defer if data is null - // we can be expecting either 'end' or - // 'error' - - if (data !== null) { - iter[kLastPromise] = null; - iter[kLastResolve] = null; - iter[kLastReject] = null; - resolve(createIterResult(data, false)); - } - } -} - -function onReadable(iter) { - // we wait for the next tick, because it might - // emit an error with process.nextTick - process.nextTick(readAndResolve, iter); -} - -function wrapForNext(lastPromise, iter) { - return function (resolve, reject) { - lastPromise.then(function () { - if (iter[kEnded]) { - resolve(createIterResult(undefined, true)); - return; - } - - iter[kHandlePromise](resolve, reject); - }, reject); - }; -} - -var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); -var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { - get stream() { - return this[kStream]; - }, - - next: function next() { - var _this = this; - - // if we have detected an error in the meanwhile - // reject straight away - var error = this[kError]; - - if (error !== null) { - return Promise.reject(error); - } - - if (this[kEnded]) { - return Promise.resolve(createIterResult(undefined, true)); - } - - if (this[kStream].destroyed) { - // We need to defer via nextTick because if .destroy(err) is - // called, the error will be emitted via nextTick, and - // we cannot guarantee that there is no error lingering around - // waiting to be emitted. - return new Promise(function (resolve, reject) { - process.nextTick(function () { - if (_this[kError]) { - reject(_this[kError]); - } else { - resolve(createIterResult(undefined, true)); - } - }); - }); - } // if we have multiple next() calls - // we will wait for the previous Promise to finish - // this logic is optimized to support for await loops, - // where next() is only called once at a time - - - var lastPromise = this[kLastPromise]; - var promise; - - if (lastPromise) { - promise = new Promise(wrapForNext(lastPromise, this)); - } else { - // fast path needed to support multiple this.push() - // without triggering the next() queue - var data = this[kStream].read(); - - if (data !== null) { - return Promise.resolve(createIterResult(data, false)); - } - - promise = new Promise(this[kHandlePromise]); - } - - this[kLastPromise] = promise; - return promise; - } -}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { - return this; -}), _defineProperty(_Object$setPrototypeO, "return", function _return() { - var _this2 = this; - - // destroy(err, cb) is a private API - // we can guarantee we have that here, because we control the - // Readable class this is attached to - return new Promise(function (resolve, reject) { - _this2[kStream].destroy(null, function (err) { - if (err) { - reject(err); - return; - } - - resolve(createIterResult(undefined, true)); - }); - }); -}), _Object$setPrototypeO), AsyncIteratorPrototype); - -var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { - var _Object$create; - - var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { - value: stream, - writable: true - }), _defineProperty(_Object$create, kLastResolve, { - value: null, - writable: true - }), _defineProperty(_Object$create, kLastReject, { - value: null, - writable: true - }), _defineProperty(_Object$create, kError, { - value: null, - writable: true - }), _defineProperty(_Object$create, kEnded, { - value: stream._readableState.endEmitted, - writable: true - }), _defineProperty(_Object$create, kHandlePromise, { - value: function value(resolve, reject) { - var data = iterator[kStream].read(); - - if (data) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(data, false)); - } else { - iterator[kLastResolve] = resolve; - iterator[kLastReject] = reject; - } - }, - writable: true - }), _Object$create)); - iterator[kLastPromise] = null; - finished(stream, function (err) { - if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { - var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise - // returned by next() and store the error - - if (reject !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - reject(err); - } - - iterator[kError] = err; - return; - } - - var resolve = iterator[kLastResolve]; - - if (resolve !== null) { - iterator[kLastPromise] = null; - iterator[kLastResolve] = null; - iterator[kLastReject] = null; - resolve(createIterResult(undefined, true)); - } - - iterator[kEnded] = true; - }); - stream.on('readable', onReadable.bind(null, iterator)); - return iterator; -}; - -module.exports = createReadableStreamAsyncIterator; -}).call(this)}).call(this,require('_process')) -},{"./end-of-stream":36,"_process":24}],34:[function(require,module,exports){ -'use strict'; - -function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } - -function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } - -function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } - -function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } - -var _require = require('buffer'), - Buffer = _require.Buffer; - -var _require2 = require('util'), - inspect = _require2.inspect; - -var custom = inspect && inspect.custom || 'inspect'; - -function copyBuffer(src, target, offset) { - Buffer.prototype.copy.call(src, target, offset); -} - -module.exports = -/*#__PURE__*/ -function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - _createClass(BufferList, [{ - key: "push", - value: function push(v) { - var entry = { - data: v, - next: null - }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - } - }, { - key: "unshift", - value: function unshift(v) { - var entry = { - data: v, - next: this.head - }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - } - }, { - key: "shift", - value: function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - } - }, { - key: "clear", - value: function clear() { - this.head = this.tail = null; - this.length = 0; - } - }, { - key: "join", - value: function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - - while (p = p.next) { - ret += s + p.data; - } - - return ret; - } - }, { - key: "concat", - value: function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - - return ret; - } // Consumes a specified amount of bytes or characters from the buffered data. - - }, { - key: "consume", - value: function consume(n, hasStrings) { - var ret; - - if (n < this.head.data.length) { - // `slice` is the same for buffers and strings. - ret = this.head.data.slice(0, n); - this.head.data = this.head.data.slice(n); - } else if (n === this.head.data.length) { - // First chunk is a perfect match. - ret = this.shift(); - } else { - // Result spans more than one buffer. - ret = hasStrings ? this._getString(n) : this._getBuffer(n); - } - - return ret; - } - }, { - key: "first", - value: function first() { - return this.head.data; - } // Consumes a specified amount of characters from the buffered data. - - }, { - key: "_getString", - value: function _getString(n) { - var p = this.head; - var c = 1; - var ret = p.data; - n -= ret.length; - - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = str.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Consumes a specified amount of bytes from the buffered data. - - }, { - key: "_getBuffer", - value: function _getBuffer(n) { - var ret = Buffer.allocUnsafe(n); - var p = this.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) this.head = p.next;else this.head = this.tail = null; - } else { - this.head = p; - p.data = buf.slice(nb); - } - - break; - } - - ++c; - } - - this.length -= c; - return ret; - } // Make sure the linked list only shows the minimal necessary information. - - }, { - key: custom, - value: function value(_, options) { - return inspect(this, _objectSpread({}, options, { - // Only inspect one level. - depth: 0, - // It should not recurse. - customInspect: false - })); - } - }]); - - return BufferList; -}(); -},{"buffer":7,"util":6}],35:[function(require,module,exports){ -(function (process){(function (){ -'use strict'; // undocumented cb() API, needed for core, not for public API - -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - process.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - process.nextTick(emitErrorNT, this, err); - } - } - - return this; - } // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - - if (this._readableState) { - this._readableState.destroyed = true; - } // if this is a duplex stream mark the writable part as destroyed as well - - - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - process.nextTick(emitErrorAndCloseNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - process.nextTick(emitErrorAndCloseNT, _this, err); - } else { - process.nextTick(emitCloseNT, _this); - } - } else if (cb) { - process.nextTick(emitCloseNT, _this); - cb(err); - } else { - process.nextTick(emitCloseNT, _this); - } - }); - - return this; -} - -function emitErrorAndCloseNT(self, err) { - emitErrorNT(self, err); - emitCloseNT(self); -} - -function emitCloseNT(self) { - if (self._writableState && !self._writableState.emitClose) return; - if (self._readableState && !self._readableState.emitClose) return; - self.emit('close'); -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -function errorOrDestroy(stream, err) { - // We have tests that rely on errors being emitted - // in the same tick, so changing this is semver major. - // For now when you opt-in to autoDestroy we allow - // the error to be emitted nextTick. In a future - // semver major update we should change the default to this. - var rState = stream._readableState; - var wState = stream._writableState; - if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy, - errorOrDestroy: errorOrDestroy -}; -}).call(this)}).call(this,require('_process')) -},{"_process":24}],36:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/end-of-stream with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - - callback.apply(this, args); - }; -} - -function noop() {} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function eos(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - callback = once(callback || noop); - var readable = opts.readable || opts.readable !== false && stream.readable; - var writable = opts.writable || opts.writable !== false && stream.writable; - - var onlegacyfinish = function onlegacyfinish() { - if (!stream.writable) onfinish(); - }; - - var writableEnded = stream._writableState && stream._writableState.finished; - - var onfinish = function onfinish() { - writable = false; - writableEnded = true; - if (!readable) callback.call(stream); - }; - - var readableEnded = stream._readableState && stream._readableState.endEmitted; - - var onend = function onend() { - readable = false; - readableEnded = true; - if (!writable) callback.call(stream); - }; - - var onerror = function onerror(err) { - callback.call(stream, err); - }; - - var onclose = function onclose() { - var err; - - if (readable && !readableEnded) { - if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - - if (writable && !writableEnded) { - if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); - return callback.call(stream, err); - } - }; - - var onrequest = function onrequest() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest();else stream.on('request', onrequest); - } else if (writable && !stream._writableState) { - // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - return function () { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -} - -module.exports = eos; -},{"../../../errors":27}],37:[function(require,module,exports){ -module.exports = function () { - throw new Error('Readable.from is not available in the browser') -}; - -},{}],38:[function(require,module,exports){ -// Ported from https://github.com/mafintosh/pump with -// permission from the author, Mathias Buus (@mafintosh). -'use strict'; - -var eos; - -function once(callback) { - var called = false; - return function () { - if (called) return; - called = true; - callback.apply(void 0, arguments); - }; -} - -var _require$codes = require('../../../errors').codes, - ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, - ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; - -function noop(err) { - // Rethrow the error if it exists to avoid swallowing it - if (err) throw err; -} - -function isRequest(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -} - -function destroyer(stream, reading, writing, callback) { - callback = once(callback); - var closed = false; - stream.on('close', function () { - closed = true; - }); - if (eos === undefined) eos = require('./end-of-stream'); - eos(stream, { - readable: reading, - writable: writing - }, function (err) { - if (err) return callback(err); - closed = true; - callback(); - }); - var destroyed = false; - return function (err) { - if (closed) return; - if (destroyed) return; - destroyed = true; // request.destroy just do .end - .abort is what we want - - if (isRequest(stream)) return stream.abort(); - if (typeof stream.destroy === 'function') return stream.destroy(); - callback(err || new ERR_STREAM_DESTROYED('pipe')); - }; -} - -function call(fn) { - fn(); -} - -function pipe(from, to) { - return from.pipe(to); -} - -function popCallback(streams) { - if (!streams.length) return noop; - if (typeof streams[streams.length - 1] !== 'function') return noop; - return streams.pop(); -} - -function pipeline() { - for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { - streams[_key] = arguments[_key]; - } - - var callback = popCallback(streams); - if (Array.isArray(streams[0])) streams = streams[0]; - - if (streams.length < 2) { - throw new ERR_MISSING_ARGS('streams'); - } - - var error; - var destroys = streams.map(function (stream, i) { - var reading = i < streams.length - 1; - var writing = i > 0; - return destroyer(stream, reading, writing, function (err) { - if (!error) error = err; - if (err) destroys.forEach(call); - if (reading) return; - destroys.forEach(call); - callback(error); - }); - }); - return streams.reduce(pipe); -} - -module.exports = pipeline; -},{"../../../errors":27,"./end-of-stream":36}],39:[function(require,module,exports){ -'use strict'; - -var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; - -function highWaterMarkFrom(options, isDuplex, duplexKey) { - return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; -} - -function getHighWaterMark(state, options, duplexKey, isDuplex) { - var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); - - if (hwm != null) { - if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { - var name = isDuplex ? duplexKey : 'highWaterMark'; - throw new ERR_INVALID_OPT_VALUE(name, hwm); - } - - return Math.floor(hwm); - } // Default value - - - return state.objectMode ? 16 : 16 * 1024; -} - -module.exports = { - getHighWaterMark: getHighWaterMark -}; -},{"../../../errors":27}],40:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":11}],41:[function(require,module,exports){ -// Copyright Joyent, Inc. and other Node 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. - -'use strict'; - -/**/ - -var Buffer = require('safe-buffer').Buffer; -/**/ - -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; - -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; - -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.StringDecoder = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} - -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; - -StringDecoder.prototype.end = utf8End; - -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; - -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; - -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} - -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} - -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} - -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} - -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} - -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} - -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} - -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} - -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} - -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} - -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} - -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} -},{"safe-buffer":25}],42:[function(require,module,exports){ -(function (setImmediate,clearImmediate){(function (){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":24,"timers":42}],43:[function(require,module,exports){ -(function (global){(function (){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],44:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],45:[function(require,module,exports){ -// Currently in sync with Node.js lib/internal/util/types.js -// https://github.com/nodejs/node/commit/112cc7c27551254aa2b17098fb774867f05ed0d9 - -'use strict'; - -var isArgumentsObject = require('is-arguments'); -var isGeneratorFunction = require('is-generator-function'); -var whichTypedArray = require('which-typed-array'); -var isTypedArray = require('is-typed-array'); - -function uncurryThis(f) { - return f.call.bind(f); -} - -var BigIntSupported = typeof BigInt !== 'undefined'; -var SymbolSupported = typeof Symbol !== 'undefined'; - -var ObjectToString = uncurryThis(Object.prototype.toString); - -var numberValue = uncurryThis(Number.prototype.valueOf); -var stringValue = uncurryThis(String.prototype.valueOf); -var booleanValue = uncurryThis(Boolean.prototype.valueOf); - -if (BigIntSupported) { - var bigIntValue = uncurryThis(BigInt.prototype.valueOf); -} - -if (SymbolSupported) { - var symbolValue = uncurryThis(Symbol.prototype.valueOf); -} - -function checkBoxedPrimitive(value, prototypeValueOf) { - if (typeof value !== 'object') { - return false; - } - try { - prototypeValueOf(value); - return true; - } catch(e) { - return false; - } -} - -exports.isArgumentsObject = isArgumentsObject; -exports.isGeneratorFunction = isGeneratorFunction; -exports.isTypedArray = isTypedArray; - -// Taken from here and modified for better browser support -// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js -function isPromise(input) { - return ( - ( - typeof Promise !== 'undefined' && - input instanceof Promise - ) || - ( - input !== null && - typeof input === 'object' && - typeof input.then === 'function' && - typeof input.catch === 'function' - ) - ); -} -exports.isPromise = isPromise; - -function isArrayBufferView(value) { - if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) { - return ArrayBuffer.isView(value); - } - - return ( - isTypedArray(value) || - isDataView(value) - ); -} -exports.isArrayBufferView = isArrayBufferView; - - -function isUint8Array(value) { - return whichTypedArray(value) === 'Uint8Array'; -} -exports.isUint8Array = isUint8Array; - -function isUint8ClampedArray(value) { - return whichTypedArray(value) === 'Uint8ClampedArray'; -} -exports.isUint8ClampedArray = isUint8ClampedArray; - -function isUint16Array(value) { - return whichTypedArray(value) === 'Uint16Array'; -} -exports.isUint16Array = isUint16Array; - -function isUint32Array(value) { - return whichTypedArray(value) === 'Uint32Array'; -} -exports.isUint32Array = isUint32Array; - -function isInt8Array(value) { - return whichTypedArray(value) === 'Int8Array'; -} -exports.isInt8Array = isInt8Array; - -function isInt16Array(value) { - return whichTypedArray(value) === 'Int16Array'; -} -exports.isInt16Array = isInt16Array; - -function isInt32Array(value) { - return whichTypedArray(value) === 'Int32Array'; -} -exports.isInt32Array = isInt32Array; - -function isFloat32Array(value) { - return whichTypedArray(value) === 'Float32Array'; -} -exports.isFloat32Array = isFloat32Array; - -function isFloat64Array(value) { - return whichTypedArray(value) === 'Float64Array'; -} -exports.isFloat64Array = isFloat64Array; - -function isBigInt64Array(value) { - return whichTypedArray(value) === 'BigInt64Array'; -} -exports.isBigInt64Array = isBigInt64Array; - -function isBigUint64Array(value) { - return whichTypedArray(value) === 'BigUint64Array'; -} -exports.isBigUint64Array = isBigUint64Array; - -function isMapToString(value) { - return ObjectToString(value) === '[object Map]'; -} -isMapToString.working = ( - typeof Map !== 'undefined' && - isMapToString(new Map()) -); - -function isMap(value) { - if (typeof Map === 'undefined') { - return false; - } - - return isMapToString.working - ? isMapToString(value) - : value instanceof Map; -} -exports.isMap = isMap; - -function isSetToString(value) { - return ObjectToString(value) === '[object Set]'; -} -isSetToString.working = ( - typeof Set !== 'undefined' && - isSetToString(new Set()) -); -function isSet(value) { - if (typeof Set === 'undefined') { - return false; - } - - return isSetToString.working - ? isSetToString(value) - : value instanceof Set; -} -exports.isSet = isSet; - -function isWeakMapToString(value) { - return ObjectToString(value) === '[object WeakMap]'; -} -isWeakMapToString.working = ( - typeof WeakMap !== 'undefined' && - isWeakMapToString(new WeakMap()) -); -function isWeakMap(value) { - if (typeof WeakMap === 'undefined') { - return false; - } - - return isWeakMapToString.working - ? isWeakMapToString(value) - : value instanceof WeakMap; -} -exports.isWeakMap = isWeakMap; - -function isWeakSetToString(value) { - return ObjectToString(value) === '[object WeakSet]'; -} -isWeakSetToString.working = ( - typeof WeakSet !== 'undefined' && - isWeakSetToString(new WeakSet()) -); -function isWeakSet(value) { - return isWeakSetToString(value); -} -exports.isWeakSet = isWeakSet; - -function isArrayBufferToString(value) { - return ObjectToString(value) === '[object ArrayBuffer]'; -} -isArrayBufferToString.working = ( - typeof ArrayBuffer !== 'undefined' && - isArrayBufferToString(new ArrayBuffer()) -); -function isArrayBuffer(value) { - if (typeof ArrayBuffer === 'undefined') { - return false; - } - - return isArrayBufferToString.working - ? isArrayBufferToString(value) - : value instanceof ArrayBuffer; -} -exports.isArrayBuffer = isArrayBuffer; - -function isDataViewToString(value) { - return ObjectToString(value) === '[object DataView]'; -} -isDataViewToString.working = ( - typeof ArrayBuffer !== 'undefined' && - typeof DataView !== 'undefined' && - isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1)) -); -function isDataView(value) { - if (typeof DataView === 'undefined') { - return false; - } - - return isDataViewToString.working - ? isDataViewToString(value) - : value instanceof DataView; -} -exports.isDataView = isDataView; - -// Store a copy of SharedArrayBuffer in case it's deleted elsewhere -var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined; -function isSharedArrayBufferToString(value) { - return ObjectToString(value) === '[object SharedArrayBuffer]'; -} -function isSharedArrayBuffer(value) { - if (typeof SharedArrayBufferCopy === 'undefined') { - return false; - } - - if (typeof isSharedArrayBufferToString.working === 'undefined') { - isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy()); - } - - return isSharedArrayBufferToString.working - ? isSharedArrayBufferToString(value) - : value instanceof SharedArrayBufferCopy; -} -exports.isSharedArrayBuffer = isSharedArrayBuffer; - -function isAsyncFunction(value) { - return ObjectToString(value) === '[object AsyncFunction]'; -} -exports.isAsyncFunction = isAsyncFunction; - -function isMapIterator(value) { - return ObjectToString(value) === '[object Map Iterator]'; -} -exports.isMapIterator = isMapIterator; - -function isSetIterator(value) { - return ObjectToString(value) === '[object Set Iterator]'; -} -exports.isSetIterator = isSetIterator; - -function isGeneratorObject(value) { - return ObjectToString(value) === '[object Generator]'; -} -exports.isGeneratorObject = isGeneratorObject; - -function isWebAssemblyCompiledModule(value) { - return ObjectToString(value) === '[object WebAssembly.Module]'; -} -exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule; - -function isNumberObject(value) { - return checkBoxedPrimitive(value, numberValue); -} -exports.isNumberObject = isNumberObject; - -function isStringObject(value) { - return checkBoxedPrimitive(value, stringValue); -} -exports.isStringObject = isStringObject; - -function isBooleanObject(value) { - return checkBoxedPrimitive(value, booleanValue); -} -exports.isBooleanObject = isBooleanObject; - -function isBigIntObject(value) { - return BigIntSupported && checkBoxedPrimitive(value, bigIntValue); -} -exports.isBigIntObject = isBigIntObject; - -function isSymbolObject(value) { - return SymbolSupported && checkBoxedPrimitive(value, symbolValue); -} -exports.isSymbolObject = isSymbolObject; - -function isBoxedPrimitive(value) { - return ( - isNumberObject(value) || - isStringObject(value) || - isBooleanObject(value) || - isBigIntObject(value) || - isSymbolObject(value) - ); -} -exports.isBoxedPrimitive = isBoxedPrimitive; - -function isAnyArrayBuffer(value) { - return typeof Uint8Array !== 'undefined' && ( - isArrayBuffer(value) || - isSharedArrayBuffer(value) - ); -} -exports.isAnyArrayBuffer = isAnyArrayBuffer; - -['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) { - Object.defineProperty(exports, method, { - enumerable: false, - value: function() { - throw new Error(method + ' is not supported in userland'); - } - }); -}); - -},{"is-arguments":21,"is-generator-function":22,"is-typed-array":23,"which-typed-array":47}],46:[function(require,module,exports){ -(function (process){(function (){ -// Copyright Joyent, Inc. and other Node 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. - -var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - if (typeof process !== 'undefined' && process.noDeprecation === true) { - return fn; - } - - // Allow for deprecating things in the process of starting up. - if (typeof process === 'undefined') { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnvRegex = /^$/; - -if (process.env.NODE_DEBUG) { - var debugEnv = process.env.NODE_DEBUG; - debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^') - .toUpperCase(); - debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i'); -} -exports.debuglog = function(set) { - set = set.toUpperCase(); - if (!debugs[set]) { - if (debugEnvRegex.test(set)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -exports.types = require('./support/types'); - -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -exports.types.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; -exports.types.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; -exports.types.isNativeError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; - -exports.promisify = function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); - - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); - - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } - - return promise; - } - - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); -} - -exports.promisify.custom = kCustomPromisifiedSymbol - -function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); -} - -function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } - - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, - function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, - getOwnPropertyDescriptors(original)); - return callbackified; -} -exports.callbackify = callbackify; - -}).call(this)}).call(this,require('_process')) -},{"./support/isBuffer":44,"./support/types":45,"_process":24,"inherits":20}],47:[function(require,module,exports){ -(function (global){(function (){ -'use strict'; - -var forEach = require('foreach'); -var availableTypedArrays = require('available-typed-arrays'); -var callBound = require('call-bind/callBound'); - -var $toString = callBound('Object.prototype.toString'); -var hasSymbols = require('has-symbols')(); -var hasToStringTag = hasSymbols && typeof Symbol.toStringTag === 'symbol'; - -var typedArrays = availableTypedArrays(); - -var $slice = callBound('String.prototype.slice'); -var toStrTags = {}; -var gOPD = require('es-abstract/helpers/getOwnPropertyDescriptor'); -var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof'); -if (hasToStringTag && gOPD && getPrototypeOf) { - forEach(typedArrays, function (typedArray) { - if (typeof global[typedArray] === 'function') { - var arr = new global[typedArray](); - if (!(Symbol.toStringTag in arr)) { - throw new EvalError('this engine has support for Symbol.toStringTag, but ' + typedArray + ' does not have the property! Please report this.'); - } - var proto = getPrototypeOf(arr); - var descriptor = gOPD(proto, Symbol.toStringTag); - if (!descriptor) { - var superProto = getPrototypeOf(proto); - descriptor = gOPD(superProto, Symbol.toStringTag); - } - toStrTags[typedArray] = descriptor.get; - } - }); -} - -var tryTypedArrays = function tryAllTypedArrays(value) { - var foundName = false; - forEach(toStrTags, function (getter, typedArray) { - if (!foundName) { - try { - var name = getter.call(value); - if (name === typedArray) { - foundName = name; - } - } catch (e) {} - } - }); - return foundName; -}; - -var isTypedArray = require('is-typed-array'); - -module.exports = function whichTypedArray(value) { - if (!isTypedArray(value)) { return false; } - if (!hasToStringTag) { return $slice($toString(value), 8, -1); } - return tryTypedArrays(value); -}; - -}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"available-typed-arrays":4,"call-bind/callBound":8,"es-abstract/helpers/getOwnPropertyDescriptor":10,"foreach":12,"has-symbols":16,"is-typed-array":23}]},{},[3])(3) -}); diff --git a/node_modules/stream-transform/lib/es5/index.d.ts b/node_modules/stream-transform/lib/es5/index.d.ts deleted file mode 100644 index 2db108d..0000000 --- a/node_modules/stream-transform/lib/es5/index.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/// - -import * as stream from "stream"; -export = transform - -// transform([records], [options], handler, [callback]) - -declare function transform(handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(records: Array, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(options: transform.Options, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(records: Array, options: transform.Options, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare namespace transform { - type Handler = (record: T, callback: HandlerCallback, params?: any) => U - type HandlerCallback = (err?: null | Error, record?: T) => void - type Callback = (err?: null | Error, output?: string) => void - interface Options { - /** - * In the absence of a consumer, like a `stream.Readable`, trigger the consumption of the stream. - */ - consume?: boolean - /** - * The number of transformation callbacks to run in parallel; only apply with asynchronous handlers; default to "100". - */ - parallel?: number - /** - * Pass user defined parameters to the user handler as last argument. - */ - params?: any - } - interface State { - finished: number - running: number - started: number - } - class Transformer extends stream.Transform { - constructor(options: Options) - readonly options: Options - readonly state: State - } -} diff --git a/node_modules/stream-transform/lib/es5/index.js b/node_modules/stream-transform/lib/es5/index.js deleted file mode 100644 index cbe3e7e..0000000 --- a/node_modules/stream-transform/lib/es5/index.js +++ /dev/null @@ -1,230 +0,0 @@ -"use strict"; - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer -// Pass all elements of an array or a stream to transform, filter and add. Features include: -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; -stream = require('stream'); -util = require('util'); - -var _require = require('mixme'); - -clone = _require.clone; - -// ## Usage -// Callback approach, for ease of use: -// `transform(records, [options], handler, callback)` -// Stream API, for maximum of power: -// `transform([records], [options], handler, [callback])` -module.exports = function () { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = _typeof(argument); - - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error("Invalid Arguments: got ".concat(JSON.stringify(argument), " at position ").concat(i)); - } - } - - transform = new Transformer(options, handler); - error = false; - - if (records) { - setImmediate(function () { - var k, len1, record; - - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - - if (error) { - break; - } - - transform.write(record); - } - - return transform.end(); - }); - } - - if (callback || options.consume) { - result = []; - transform.on('readable', function () { - var record, results; - results = []; - - while (record = transform.read()) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - - return results; - }); - transform.on('error', function (err) { - error = true; - - if (callback) { - return callback(err); - } - }); - transform.on('end', function () { - if (callback && !error) { - return callback(null, result); - } - }); - } - - return transform; -}; // ## Transformer -// Options are documented [here](http://csv.js.org/transform/options/). - - -Transformer = function Transformer() { - var options1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - var handler1 = arguments.length > 1 ? arguments[1] : undefined; - var base, base1; - this.options = options1; - this.handler = handler1; - - if ((base = this.options).consume == null) { - base.consume = false; - } - - this.options.objectMode = true; - - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; - } - - stream.Transform.call(this, this.options); - this.state = { - running: 0, - started: 0, - finished: 0 - }; - return this; -}; - -util.inherits(Transformer, stream.Transform); -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function (chunk, encoding, cb) { - var _this = this; - - var callback, err, l; - this.state.started++; - this.state.running++; - - if (this.state.running < this.options.parallel) { - cb(); - cb = null; - } - - try { - l = this.handler.length; - - if (this.options.params != null) { - l--; - } - - if (l === 1) { - // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { - // async - callback = function callback(err) { - for (var _len = arguments.length, chunks = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - chunks[_key - 1] = arguments[_key]; - } - - return _this.__done(err, chunks, cb); - }; - - this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); - } - - return false; - } catch (error1) { - err = error1; - return this.__done(err); - } -}; - -Transformer.prototype._flush = function (cb) { - this._ending = function () { - if (this.state.running === 0) { - this._ending = undefined; - return cb(); - } - }; - - return this._ending(); -}; - -Transformer.prototype.__done = function (err, chunks, cb) { - var chunk, j, len; - this.state.running--; - - if (err) { - return this.emit('error', err); - } - - this.state.finished++; - - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - - if (typeof chunk === 'number') { - chunk = "".concat(chunk); - } - - if (chunk != null && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); - } - } - - if (cb) { - cb(); - } - - if (this._ending) { - return this._ending(); - } -}; // [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test \ No newline at end of file diff --git a/node_modules/stream-transform/lib/es5/sync.d.ts b/node_modules/stream-transform/lib/es5/sync.d.ts deleted file mode 100644 index 2101927..0000000 --- a/node_modules/stream-transform/lib/es5/sync.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -/// - -import * as streamTransform from './index'; -export = transform - -// transform(records, [options], handler) - -type Handler = (record: T) => U -declare function transform(records: Array, handler: Handler): Array -declare function transform(records: Array, options: streamTransform.Options, handler: Handler): Array -declare namespace transform { } diff --git a/node_modules/stream-transform/lib/es5/sync.js b/node_modules/stream-transform/lib/es5/sync.js deleted file mode 100644 index 7e74bfe..0000000 --- a/node_modules/stream-transform/lib/es5/sync.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; - -function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; } - -function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } - -function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } - -function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } - -/* -Stream Transform - sync module - -Please look at the [project documentation](https://csv.js.org/transform/) for -additional information. -*/ -var transform = require('.'); - -var _require = require('mixme'), - clone = _require.clone; - -module.exports = function () { - // Import arguments normalization - var handler, callback; - var options = {}; - - for (i in arguments) { - var argument = arguments[i]; - - var type = _typeof(argument); - - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error("Invalid Arguments: got ".concat(JSON.stringify(argument), " at position ").concat(i)); - } - } // Validate arguments - - - var expected_handler_length = 1; - - if (options.params) { - expected_handler_length++; - } - - if (handler.length > expected_handler_length) { - throw Error('Invalid Handler: only synchonous handlers are supported'); - } // Start transformation - - - var chunks = []; - var transformer = new transform.Transformer(options, handler); - - transformer.push = function (chunk) { - chunks.push(chunk); - }; - - var _iterator = _createForOfIteratorHelper(records), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var record = _step.value; - - transformer._transform(record, null, function () {}); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } - - return chunks; -}; \ No newline at end of file diff --git a/node_modules/stream-transform/lib/index.d.ts b/node_modules/stream-transform/lib/index.d.ts index 2db108d..3966298 100644 --- a/node_modules/stream-transform/lib/index.d.ts +++ b/node_modules/stream-transform/lib/index.d.ts @@ -1,40 +1,40 @@ /// import * as stream from "stream"; -export = transform -// transform([records], [options], handler, [callback]) +export type Handler = (record: T, callback: HandlerCallback, params?: any) => U +export type HandlerCallback = (err?: null | Error, record?: T) => void +export type Callback = (err?: null | Error, output?: string) => void -declare function transform(handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(records: Array, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(options: transform.Options, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare function transform(records: Array, options: transform.Options, handler: transform.Handler, callback?: transform.Callback): transform.Transformer -declare namespace transform { - type Handler = (record: T, callback: HandlerCallback, params?: any) => U - type HandlerCallback = (err?: null | Error, record?: T) => void - type Callback = (err?: null | Error, output?: string) => void - interface Options { - /** - * In the absence of a consumer, like a `stream.Readable`, trigger the consumption of the stream. - */ - consume?: boolean - /** - * The number of transformation callbacks to run in parallel; only apply with asynchronous handlers; default to "100". - */ - parallel?: number - /** - * Pass user defined parameters to the user handler as last argument. - */ - params?: any - } - interface State { - finished: number - running: number - started: number - } - class Transformer extends stream.Transform { - constructor(options: Options) - readonly options: Options - readonly state: State - } +export interface Options extends stream.TransformOptions { + /** + * In the absence of a consumer, like a `stream.Readable`, trigger the consumption of the stream. + */ + consume?: boolean + /** + * The number of transformation callbacks to run in parallel; only apply with asynchronous handlers; default to "100". + */ + parallel?: number + /** + * Pass user defined parameters to the user handler as last argument. + */ + params?: any } +export interface State { + finished: number + running: number + started: number +} +export class Transformer extends stream.Transform { + constructor(options: Options) + readonly options: Options + readonly state: State +} + +declare function transform(handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, handler: Handler, callback?: Callback): Transformer +declare function transform(options: Options, handler: Handler, callback?: Callback): Transformer +declare function transform(records: Array, options: Options, handler: Handler, callback?: Callback): Transformer + +export default transform; +export { transform } diff --git a/node_modules/stream-transform/lib/index.js b/node_modules/stream-transform/lib/index.js index d1598d0..b05fad6 100644 --- a/node_modules/stream-transform/lib/index.js +++ b/node_modules/stream-transform/lib/index.js @@ -1,195 +1,171 @@ -// Generated by CoffeeScript 2.5.1 -// # Stream Transformer -// Pass all elements of an array or a stream to transform, filter and add. Features include: +/* +Stream Transform -// * Extends the Node.js "stream.Transform" API. -// * Both synchrounous and asynchronous support based and user callback -// arguments signature. -// * Ability to skip records. -// * Sequential and concurrent execution using the "parallel" options. +Please look at the [project documentation](https://csv.js.org/transform/) for +additional information. +*/ -// Please look at the [README], the [samples] and the [tests] for additional -// information. -var Transformer, clone, stream, util; +import stream from 'stream'; +import util from 'util'; -stream = require('stream'); - -util = require('util'); - -({clone} = require('mixme')); - -// ## Usage - -// Callback approach, for ease of use: - -// `transform(records, [options], handler, callback)` - -// Stream API, for maximum of power: - -// `transform([records], [options], handler, [callback])` -module.exports = function() { - var argument, callback, error, handler, i, j, len, options, records, result, transform, type; - options = {}; - for (i = j = 0, len = arguments.length; j < len; i = ++j) { - argument = arguments[i]; - type = typeof argument; - if (argument === null) { - type = 'null'; - } else if (type === 'object' && Array.isArray(argument)) { - type = 'array'; - } - if (type === 'array') { - records = argument; - } else if (type === 'object') { - options = clone(argument); - } else if (type === 'function') { - if (handler && i === arguments.length - 1) { - callback = argument; - } else { - handler = argument; - } - } else if (type !== 'null') { - throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); - } - } - transform = new Transformer(options, handler); - error = false; - if (records) { - setImmediate(function() { - var k, len1, record; - for (k = 0, len1 = records.length; k < len1; k++) { - record = records[k]; - if (error) { - break; - } - transform.write(record); - } - return transform.end(); - }); - } - if (callback || options.consume) { - result = []; - transform.on('readable', function() { - var record, results; - results = []; - while ((record = transform.read())) { - if (callback) { - results.push(result.push(record)); - } else { - results.push(void 0); - } - } - return results; - }); - transform.on('error', function(err) { - error = true; - if (callback) { - return callback(err); - } - }); - transform.on('end', function() { - if (callback && !error) { - return callback(null, result); - } - }); - } - return transform; -}; - -// ## Transformer - -// Options are documented [here](http://csv.js.org/transform/options/). -Transformer = function(options1 = {}, handler1) { - var base, base1; - this.options = options1; - this.handler = handler1; - if ((base = this.options).consume == null) { - base.consume = false; +const Transformer = function(options = {}, handler){ + this.options = options; + if(options.consume === undefined || options.consume === null){ + this.options.consume = false; } this.options.objectMode = true; - if ((base1 = this.options).parallel == null) { - base1.parallel = 100; + if(options.parallel === undefined || options.parallel === null){ + this.options.parallel = 100; + } + if(options.params === undefined || options.params === null){ + options.params = null; } + this.handler = handler; stream.Transform.call(this, this.options); this.state = { running: 0, started: 0, - finished: 0 + finished: 0, + paused: false, }; return this; }; util.inherits(Transformer, stream.Transform); -module.exports.Transformer = Transformer; - -Transformer.prototype._transform = function(chunk, encoding, cb) { - var callback, err, l; +Transformer.prototype._transform = function(chunk, _, cb){ this.state.started++; this.state.running++; - if (this.state.running < this.options.parallel) { + // Accept additionnal chunks to be processed in parallel + if(!this.state.paused && this.state.running < this.options.parallel){ cb(); - cb = null; + cb = null; // Cancel further callback execution } try { - l = this.handler.length; - if (this.options.params != null) { + let l = this.handler.length; + if(this.options.params !== null){ l--; } - if (l === 1) { // sync - this.__done(null, [this.handler.call(this, chunk, this.options.params)], cb); - } else if (l === 2) { // async - callback = (err, ...chunks) => { - return this.__done(err, chunks, cb); - }; + if(l === 1){ // sync + const result = this.handler.call(this, chunk, this.options.params); + if (result && result.then) { + result.then((result) => { + this.__done(null, [result], cb); + }); + result.catch((err) => { + this.__done(err); + }); + } else { + this.__done(null, [result], cb); + } + }else if(l === 2){ // async + const callback = (err, ...chunks) => + this.__done(err, chunks, cb); this.handler.call(this, chunk, callback, this.options.params); - } else { - throw Error("Invalid handler arguments"); + }else{ + throw Error('Invalid handler arguments'); } return false; - } catch (error1) { - err = error1; - return this.__done(err); + } catch (err) { + this.__done(err); } }; - -Transformer.prototype._flush = function(cb) { - this._ending = function() { - if (this.state.running === 0) { - this._ending = undefined - return cb(); - } - }; - return this._ending(); +Transformer.prototype._flush = function(cb){ + if(this.state.running === 0){ + cb(); + }else{ + this._ending = function(){ + cb(); + }; + } }; - -Transformer.prototype.__done = function(err, chunks, cb) { - var chunk, j, len; +Transformer.prototype.__done = function(err, chunks, cb){ this.state.running--; - if (err) { - return this.emit('error', err); + if(err){ + return this.destroy(err); + // return this.emit('error', err); } this.state.finished++; - for (j = 0, len = chunks.length; j < len; j++) { - chunk = chunks[j]; - if (typeof chunk === 'number') { + for(let chunk of chunks){ + if (typeof chunk === 'number'){ chunk = `${chunk}`; } - if ((chunk != null) && chunk !== '') { - // We dont push empty string - // See https://nodejs.org/api/stream.html#stream_readable_push - this.push(chunk); + // We dont push empty string + // See https://nodejs.org/api/stream.html#stream_readable_push + if(chunk !== undefined && chunk !== null && chunk !== ''){ + this.state.paused = !this.push(chunk); } } - if (cb) { + // Chunk has been processed + if(cb){ cb(); } - if (this._ending) { - return this._ending(); + if(this._ending && this.state.running === 0){ + this._ending(); + } +}; +const transform = function(){ + let options = {}; + let callback, handler, records; + for(let i = 0; i< arguments.length; i++){ + const argument = arguments[i]; + let type = typeof argument; + if(argument === null){ + type = 'null'; + }else if(type === 'object' && Array.isArray(argument)){ + type = 'array'; + } + if(type === 'array'){ + records = argument; + }else if(type === 'object'){ + options = {...argument}; + }else if(type === 'function'){ + if (handler && i === arguments.length - 1) { + callback = argument; + } else { + handler = argument; + } + }else if(type !== 'null'){ + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); + } + } + const transformer = new Transformer(options, handler); + let error = false; + if (records) { + const writer = function(){ + for(const record of records){ + if(error) break; + transformer.write(record); + } + transformer.end(); + }; + // Support Deno, Rollup doesnt provide a shim for setImmediate + if(typeof setImmediate === 'function'){ + setImmediate(writer); + }else{ + setTimeout(writer, 0); + } + } + if(callback || options.consume) { + const result = []; + transformer.on('readable', function(){ + let record; while((record = transformer.read()) !== null){ + if(callback){ + result.push(record); + } + } + }); + transformer.on('error', function(err){ + error = true; + if (callback) callback(err); + }); + transformer.on('end', function(){ + if (callback && !error) callback(null, result); + }); } + return transformer; }; -// [readme]: https://github.com/wdavidw/node-stream-transform -// [samples]: https://github.com/wdavidw/node-stream-transform/tree/master/samples -// [tests]: https://github.com/wdavidw/node-stream-transform/tree/master/test +// export default transform +export { transform, Transformer }; diff --git a/node_modules/stream-transform/lib/sync.d.ts b/node_modules/stream-transform/lib/sync.d.ts index 2101927..538c3e5 100644 --- a/node_modules/stream-transform/lib/sync.d.ts +++ b/node_modules/stream-transform/lib/sync.d.ts @@ -1,11 +1,10 @@ /// -import * as streamTransform from './index'; -export = transform +import { Options } from './index.js'; -// transform(records, [options], handler) +export type Handler = (record: T) => U +// export default transform; +export function transform(records: Array, handler: Handler): Array +export function transform(records: Array, options: Options, handler: Handler): Array -type Handler = (record: T) => U -declare function transform(records: Array, handler: Handler): Array -declare function transform(records: Array, options: streamTransform.Options, handler: Handler): Array -declare namespace transform { } +export { Options }; diff --git a/node_modules/stream-transform/lib/sync.js b/node_modules/stream-transform/lib/sync.js index 3f704b0..3212129 100644 --- a/node_modules/stream-transform/lib/sync.js +++ b/node_modules/stream-transform/lib/sync.js @@ -6,51 +6,49 @@ Please look at the [project documentation](https://csv.js.org/transform/) for additional information. */ -const transform = require('.') -const {clone} = require('mixme') +import {Transformer} from './index.js'; -module.exports = function(){ +const transform = function(){ // Import arguments normalization - let handler, callback - let options = {} - for(i in arguments){ - const argument = arguments[i] - let type = typeof argument + let handler, records; + let options = {}; + for(const i in arguments){ + const argument = arguments[i]; + let type = typeof argument; if(argument === null){ - type = 'null' + type = 'null'; }else if(type === 'object' && Array.isArray(argument)){ - type = 'array' + type = 'array'; } if(type === 'array'){ - records = argument + records = argument; }else if(type === 'object'){ - options = clone(argument) + options = {...argument}; }else if(type === 'function'){ - if(handler && i === arguments.length - 1){ - callback = argument - }else{ - handler = argument - } + handler = argument; }else if(type !== 'null'){ - throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`) + throw new Error(`Invalid Arguments: got ${JSON.stringify(argument)} at position ${i}`); } } // Validate arguments - let expected_handler_length = 1 + let expected_handler_length = 1; if(options.params){ - expected_handler_length++ + expected_handler_length++; } if(handler.length > expected_handler_length){ - throw Error('Invalid Handler: only synchonous handlers are supported') + throw Error('Invalid Handler: only synchonous handlers are supported'); } // Start transformation - const chunks = [] - const transformer = new transform.Transformer(options, handler) + const chunks = []; + const transformer = new Transformer(options, handler); transformer.push = function(chunk){ - chunks.push(chunk) - } + chunks.push(chunk); + }; for(const record of records){ - transformer._transform(record, null, function(){}) + transformer._transform(record, null, function(){}); } - return chunks -} + return chunks; +}; + +// export default transform +export { transform }; diff --git a/node_modules/stream-transform/package.json b/node_modules/stream-transform/package.json index 1214462..c37a786 100644 --- a/node_modules/stream-transform/package.json +++ b/node_modules/stream-transform/package.json @@ -1,82 +1,119 @@ { - "version": "2.1.3", + "version": "3.3.1", "name": "stream-transform", "description": "Object transformations implementing the Node.js `stream.Transform` API", "keywords": [ "stream", "transform", "csv", - "object" + "object", + "backend", + "frontend" ], - "license": "MIT", - "repository": { - "type": "git", - "url": "http://www.github.com/adaltas/node-stream-transform" - }, "author": "David Worms (https://www.adaltas.com)", - "homepage": "https://csv.js.org/transform/", - "coffeelintConfig": { - "indentation": { - "level": "error", - "value": 2 - }, - "line_endings": { - "level": "error", - "value": "unix" - }, - "max_line_length": { - "level": "ignore" - } - }, "devDependencies": { - "@babel/cli": "^7.14.8", - "@babel/core": "^7.15.0", - "@babel/preset-env": "^7.15.0", - "@types/mocha": "^9.0.0", - "@types/node": "^16.7.8", - "babelify": "^10.0.0", - "browserify": "^17.0.0", - "coffeescript": "~2.5.1", - "csv-generate": "^3.4.3", - "each": "^1.2.2", - "mocha": "~9.1.1", + "@rollup/plugin-eslint": "^9.0.4", + "@rollup/plugin-node-resolve": "^15.2.1", + "@types/mocha": "^10.0.1", + "@types/node": "^20.5.6", + "coffeescript": "~2.7.0", + "csv-generate": "^4.4.0", + "each": "^2.4.0", + "eslint": "^8.47.0", + "mocha": "~10.2.0", "pad": "~3.2.0", + "rollup": "^3.28.1", + "rollup-plugin-node-builtins": "^2.1.2", + "rollup-plugin-node-globals": "^1.4.0", "should": "~13.2.3", - "ts-node": "^10.2.1", - "typescript": "^4.4.2" + "ts-node": "^10.9.1", + "typescript": "^5.2.2" + }, + "exports": { + ".": { + "import": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + } + }, + "./sync": { + "import": { + "types": "./lib/sync.d.ts", + "default": "./lib/sync.js" + }, + "require": { + "types": "./dist/cjs/sync.d.cts", + "default": "./dist/cjs/sync.cjs" + } + }, + "./browser/esm": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + }, + "./browser/esm/sync": { + "types": "./dist/esm/sync.d.ts", + "default": "./dist/esm/sync.js" + } }, "files": [ - "/lib" + "dist", + "lib" ], - "main": "./lib", + "homepage": "https://csv.js.org/transform", + "license": "MIT", + "main": "./dist/cjs/index.cjs", "mocha": { - "throw-deprecation": true, - "require": [ - "should", - "coffeescript/register", - "ts-node/register" - ], "inline-diffs": true, - "timeout": 40000, + "loader": "./test/loaders/all.js", + "recursive": true, "reporter": "spec", - "recursive": true + "require": [ + "should" + ], + "throw-deprecation": true, + "timeout": 40000 + }, + "repository": { + "type": "git", + "url": "https://github.com/adaltas/node-csv.git", + "directory": "packages/stream-transform" }, "scripts": { - "build:babel": "cd lib && babel *.js -d es5 && cd ..", - "build:browserify": "browserify lib/index.js --transform babelify --standalone parse > lib/browser/index.js && browserify lib/sync.js --transform babelify --standalone parse > lib/browser/sync.js", - "build": "npm run build:babel && npm run build:browserify", - "preversion": "cp lib/*.ts lib/es5 && git add lib/es5/*.ts", + "build": "npm run build:rollup && npm run build:ts", + "build:rollup": "npx rollup -c", + "build:ts": "cp lib/index.d.ts dist/cjs/index.d.cts && cp lib/sync.d.ts dist/cjs/sync.d.cts && cp lib/*.ts dist/esm", + "postbuild:ts": "find dist/cjs -name '*.d.cts' -exec sh -c \"sed -i \"s/\\.js'/\\.cjs'/g\" {} || sed -i '' \"s/\\.js'/\\.cjs'/g\" {}\" \\;", + "lint": "npm run lint:lib && npm run lint:samples && npm run lint:test", + "postlint": "tsc --noEmit true", + "lint:lib": "eslint --fix lib/*.js", + "lint:samples": "eslint --fix samples/*.js", + "lint:test": "coffeelint --fix test/*.coffee", + "preversion": "npm run build && git add dist", "pretest": "npm run build", - "test": "mocha test/**/*.{coffee,ts}" + "test": "mocha 'test/**/*.{coffee,ts}'", + "test:legacy": "mocha --loader=./test/loaders/legacy/all.js --ignore test/handler.mode.callback.coffee --ignore test/handler.mode.callback.error.coffee 'test/**/*.{coffee,ts}'" }, - "types": [ - "./lib/es5/index.d.ts", - "./lib/es5/sync.d.ts", - "./lib/index.d.ts", - "./lib/sync.d.ts" - ], - "dependencies": { - "mixme": "^0.5.1" + "type": "module", + "types": "dist/esm/index.d.ts", + "typesVersions": { + "*": { + ".": [ + "dist/esm/index.d.ts" + ], + "sync": [ + "dist/esm/sync.d.ts" + ], + "browser/esm": [ + "dist/esm/index.d.ts" + ], + "browser/esm/sync": [ + "dist/esm/sync.d.ts" + ] + } }, - "gitHead": "0fd5209b6862655c384cda052abf38019b959e70" + "gitHead": "6575fc60ef848fb7fd3acbf5ff32130345fe1524" } diff --git a/node_modules/cliui/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts similarity index 100% rename from node_modules/cliui/node_modules/string-width/index.d.ts rename to node_modules/string-width/index.d.ts diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js index bbc49d2..f4d261a 100644 --- a/node_modules/string-width/index.js +++ b/node_modules/string-width/index.js @@ -1,18 +1,25 @@ 'use strict'; const stripAnsi = require('strip-ansi'); const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); -module.exports = str => { - if (typeof str !== 'string' || str.length === 0) { +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { return 0; } - str = stripAnsi(str); + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); let width = 0; - for (let i = 0; i < str.length; i++) { - const code = str.codePointAt(i); + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); // Ignore control characters if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { @@ -34,3 +41,7 @@ module.exports = str => { return width; }; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json index 89f0b6a..28ba7b4 100644 --- a/node_modules/string-width/package.json +++ b/node_modules/string-width/package.json @@ -1,6 +1,6 @@ { "name": "string-width", - "version": "2.1.1", + "version": "4.2.3", "description": "Get the visual width of a string - the number of columns required to display it", "license": "MIT", "repository": "sindresorhus/string-width", @@ -10,19 +10,18 @@ "url": "sindresorhus.com" }, "engines": { - "node": ">=4" + "node": ">=8" }, "scripts": { - "test": "xo && ava" + "test": "xo && ava && tsd" }, "files": [ - "index.js" + "index.js", + "index.d.ts" ], "keywords": [ "string", - "str", "character", - "char", "unicode", "width", "visual", @@ -45,11 +44,13 @@ "fixed-width" ], "dependencies": { - "is-fullwidth-code-point": "^2.0.0", - "strip-ansi": "^4.0.0" + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" }, "devDependencies": { - "ava": "*", - "xo": "*" + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" } } diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md index df5b719..bdd3141 100644 --- a/node_modules/string-width/readme.md +++ b/node_modules/string-width/readme.md @@ -1,4 +1,4 @@ -# string-width [![Build Status](https://travis-ci.org/sindresorhus/string-width.svg?branch=master)](https://travis-ci.org/sindresorhus/string-width) +# string-width > Get the visual width of a string - the number of columns required to display it @@ -19,14 +19,14 @@ $ npm install string-width ```js const stringWidth = require('string-width'); +stringWidth('a'); +//=> 1 + stringWidth('古'); //=> 2 -stringWidth('\u001b[1m古\u001b[22m'); +stringWidth('\u001B[1m古\u001B[22m'); //=> 2 - -stringWidth('a'); -//=> 1 ``` @@ -37,6 +37,14 @@ stringWidth('a'); - [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string -## License +--- -MIT © [Sindre Sorhus](https://sindresorhus.com) +
            + + Get professional support for this package with a Tidelift subscription + +
            + + Tidelift helps make open source sustainable for maintainers while giving companies
            assurances about security, maintenance, and licensing for their dependencies. +
            +
            diff --git a/node_modules/cliui/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts similarity index 100% rename from node_modules/cliui/node_modules/strip-ansi/index.d.ts rename to node_modules/strip-ansi/index.d.ts diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js index 96e0292..9a593df 100644 --- a/node_modules/strip-ansi/index.js +++ b/node_modules/strip-ansi/index.js @@ -1,4 +1,4 @@ 'use strict'; const ansiRegex = require('ansi-regex'); -module.exports = input => typeof input === 'string' ? input.replace(ansiRegex(), '') : input; +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json index 555f194..1a41108 100644 --- a/node_modules/strip-ansi/package.json +++ b/node_modules/strip-ansi/package.json @@ -1,52 +1,54 @@ { - "name": "strip-ansi", - "version": "4.0.0", - "description": "Strip ANSI escape codes", - "license": "MIT", - "repository": "chalk/strip-ansi", - "author": { - "name": "Sindre Sorhus", - "email": "sindresorhus@gmail.com", - "url": "sindresorhus.com" - }, - "engines": { - "node": ">=4" - }, - "scripts": { - "test": "xo && ava" - }, - "files": [ - "index.js" - ], - "keywords": [ - "strip", - "trim", - "remove", - "ansi", - "styles", - "color", - "colour", - "colors", - "terminal", - "console", - "string", - "tty", - "escape", - "formatting", - "rgb", - "256", - "shell", - "xterm", - "log", - "logging", - "command-line", - "text" - ], - "dependencies": { - "ansi-regex": "^3.0.0" - }, - "devDependencies": { - "ava": "*", - "xo": "*" - } + "name": "strip-ansi", + "version": "6.0.1", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + } } diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md index dc76f0c..7c4b56d 100644 --- a/node_modules/strip-ansi/readme.md +++ b/node_modules/strip-ansi/readme.md @@ -1,6 +1,6 @@ # strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) -> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string ## Install @@ -17,12 +17,23 @@ const stripAnsi = require('strip-ansi'); stripAnsi('\u001B[4mUnicorn\u001B[0m'); //=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' ``` +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + ## Related - [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module - [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes - [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes - [chalk](https://github.com/chalk/chalk) - Terminal string styling done right @@ -33,7 +44,3 @@ stripAnsi('\u001B[4mUnicorn\u001B[0m'); - [Sindre Sorhus](https://github.com/sindresorhus) - [Josh Junon](https://github.com/qix-) - -## License - -MIT diff --git a/node_modules/undici/LICENSE b/node_modules/undici/LICENSE new file mode 100644 index 0000000..e7323bb --- /dev/null +++ b/node_modules/undici/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Matteo Collina and Undici 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. diff --git a/node_modules/undici/README.md b/node_modules/undici/README.md new file mode 100644 index 0000000..3ba8989 --- /dev/null +++ b/node_modules/undici/README.md @@ -0,0 +1,443 @@ +# undici + +[![Node CI](https://github.com/nodejs/undici/actions/workflows/nodejs.yml/badge.svg)](https://github.com/nodejs/undici/actions/workflows/nodejs.yml) [![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) [![npm version](https://badge.fury.io/js/undici.svg)](https://badge.fury.io/js/undici) [![codecov](https://codecov.io/gh/nodejs/undici/branch/main/graph/badge.svg?token=yZL6LtXkOA)](https://codecov.io/gh/nodejs/undici) + +An HTTP/1.1 client, written from scratch for Node.js. + +> Undici means eleven in Italian. 1.1 -> 11 -> Eleven -> Undici. +It is also a Stranger Things reference. + +Have a question about using Undici? Open a [Q&A Discussion](https://github.com/nodejs/undici/discussions/new) or join our official OpenJS [Slack](https://openjs-foundation.slack.com/archives/C01QF9Q31QD) channel. + +## Install + +``` +npm i undici +``` + +## Benchmarks + +The benchmark is a simple `hello world` [example](benchmarks/benchmark.js) using a +number of unix sockets (connections) with a pipelining depth of 10 running on Node 20.6.0. + +### Connections 1 + + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|---------------|-----------|-------------------------| +| http - no keepalive | 15 | 5.32 req/sec | ± 2.61 % | - | +| http - keepalive | 10 | 5.35 req/sec | ± 2.47 % | + 0.44 % | +| undici - fetch | 15 | 41.85 req/sec | ± 2.49 % | + 686.04 % | +| undici - pipeline | 40 | 50.36 req/sec | ± 2.77 % | + 845.92 % | +| undici - stream | 15 | 60.58 req/sec | ± 2.75 % | + 1037.72 % | +| undici - request | 10 | 61.19 req/sec | ± 2.60 % | + 1049.24 % | +| undici - dispatch | 20 | 64.84 req/sec | ± 2.81 % | + 1117.81 % | + + +### Connections 50 + +| Tests | Samples | Result | Tolerance | Difference with slowest | +|---------------------|---------|------------------|-----------|-------------------------| +| undici - fetch | 30 | 2107.19 req/sec | ± 2.69 % | - | +| http - no keepalive | 10 | 2698.90 req/sec | ± 2.68 % | + 28.08 % | +| http - keepalive | 10 | 4639.49 req/sec | ± 2.55 % | + 120.17 % | +| undici - pipeline | 40 | 6123.33 req/sec | ± 2.97 % | + 190.59 % | +| undici - stream | 50 | 9426.51 req/sec | ± 2.92 % | + 347.35 % | +| undici - request | 10 | 10162.88 req/sec | ± 2.13 % | + 382.29 % | +| undici - dispatch | 50 | 11191.11 req/sec | ± 2.98 % | + 431.09 % | + + +## Quick Start + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) + +for await (const data of body) { + console.log('data', data) +} + +console.log('trailers', trailers) +``` + +## Body Mixins + +The `body` mixins are the most common way to format the request/response body. Mixins include: + +- [`.formData()`](https://fetch.spec.whatwg.org/#dom-body-formdata) +- [`.json()`](https://fetch.spec.whatwg.org/#dom-body-json) +- [`.text()`](https://fetch.spec.whatwg.org/#dom-body-text) + +Example usage: + +```js +import { request } from 'undici' + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) +console.log('headers', headers) +console.log('data', await body.json()) +console.log('trailers', trailers) +``` + +_Note: Once a mixin has been called then the body cannot be reused, thus calling additional mixins on `.body`, e.g. `.body.json(); .body.text()` will result in an error `TypeError: unusable` being thrown and returned through the `Promise` rejection._ + +Should you need to access the `body` in plain-text after using a mixin, the best practice is to use the `.text()` mixin first and then manually parse the text to the desired format. + +For more information about their behavior, please reference the body mixin from the [Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). + +## Common API Methods + +This section documents our most commonly used API methods. Additional APIs are documented in their own files within the [docs](./docs/) folder and are accessible via the navigation list on the left side of the docs site. + +### `undici.request([url, options]): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`RequestOptions`](./docs/api/Dispatcher.md#parameter-requestoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` + +Returns a promise with the result of the `Dispatcher.request` method. + +Calls `options.dispatcher.request(options)`. + +See [Dispatcher.request](./docs/api/Dispatcher.md#dispatcherrequestoptions-callback) for more details. + +### `undici.stream([url, options, ]factory): Promise` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`StreamOptions`](./docs/api/Dispatcher.md#parameter-streamoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **factory** `Dispatcher.stream.factory` + +Returns a promise with the result of the `Dispatcher.stream` method. + +Calls `options.dispatcher.stream(options, factory)`. + +See [Dispatcher.stream](docs/api/Dispatcher.md#dispatcherstreamoptions-factory-callback) for more details. + +### `undici.pipeline([url, options, ]handler): Duplex` + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`PipelineOptions`](docs/api/Dispatcher.md#parameter-pipelineoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **method** `String` - Default: `PUT` if `options.body`, otherwise `GET` + * **maxRedirections** `Integer` - Default: `0` +* **handler** `Dispatcher.pipeline.handler` + +Returns: `stream.Duplex` + +Calls `options.dispatch.pipeline(options, handler)`. + +See [Dispatcher.pipeline](docs/api/Dispatcher.md#dispatcherpipelineoptions-handler) for more details. + +### `undici.connect([url, options]): Promise` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`ConnectOptions`](docs/api/Dispatcher.md#parameter-connectoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns a promise with the result of the `Dispatcher.connect` method. + +Calls `options.dispatch.connect(options)`. + +See [Dispatcher.connect](docs/api/Dispatcher.md#dispatcherconnectoptions-callback) for more details. + +### `undici.fetch(input[, init]): Promise` + +Implements [fetch](https://fetch.spec.whatwg.org/#fetch-method). + +* https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch +* https://fetch.spec.whatwg.org/#fetch-method + +Only supported on Node 16.8+. + +Basic usage example: + +```js +import { fetch } from 'undici' + + +const res = await fetch('https://example.com') +const json = await res.json() +console.log(json) +``` + +You can pass an optional dispatcher to `fetch` as: + +```js +import { fetch, Agent } from 'undici' + +const res = await fetch('https://example.com', { + // Mocks are also supported + dispatcher: new Agent({ + keepAliveTimeout: 10, + keepAliveMaxTimeout: 10 + }) +}) +const json = await res.json() +console.log(json) +``` + +#### `request.body` + +A body can be of the following types: + +- ArrayBuffer +- ArrayBufferView +- AsyncIterables +- Blob +- Iterables +- String +- URLSearchParams +- FormData + +In this implementation of fetch, ```request.body``` now accepts ```Async Iterables```. It is not present in the [Fetch Standard.](https://fetch.spec.whatwg.org) + +```js +import { fetch } from 'undici' + +const data = { + async *[Symbol.asyncIterator]() { + yield 'hello' + yield 'world' + }, +} + +await fetch('https://example.com', { body: data, method: 'POST', duplex: 'half' }) +``` + +#### `request.duplex` + +- half + +In this implementation of fetch, `request.duplex` must be set if `request.body` is `ReadableStream` or `Async Iterables`. And fetch requests are currently always be full duplex. More detail refer to [Fetch Standard.](https://fetch.spec.whatwg.org/#dom-requestinit-duplex) + +#### `response.body` + +Nodejs has two kinds of streams: [web streams](https://nodejs.org/dist/latest-v16.x/docs/api/webstreams.html), which follow the API of the WHATWG web standard found in browsers, and an older Node-specific [streams API](https://nodejs.org/api/stream.html). `response.body` returns a readable web stream. If you would prefer to work with a Node stream you can convert a web stream using `.fromWeb()`. + +```js +import { fetch } from 'undici' +import { Readable } from 'node:stream' + +const response = await fetch('https://example.com') +const readableWebStream = response.body +const readableNodeStream = Readable.fromWeb(readableWebStream) +``` + +#### Specification Compliance + +This section documents parts of the [Fetch Standard](https://fetch.spec.whatwg.org) that Undici does +not support or does not fully implement. + +##### Garbage Collection + +* https://fetch.spec.whatwg.org/#garbage-collection + +The [Fetch Standard](https://fetch.spec.whatwg.org) allows users to skip consuming the response body by relying on +[garbage collection](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management#garbage_collection) to release connection resources. Undici does not do the same. Therefore, it is important to always either consume or cancel the response body. + +Garbage collection in Node is less aggressive and deterministic +(due to the lack of clear idle periods that browsers have through the rendering refresh rate) +which means that leaving the release of connection resources to the garbage collector can lead +to excessive connection usage, reduced performance (due to less connection re-use), and even +stalls or deadlocks when running out of connections. + +```js +// Do +const headers = await fetch(url) + .then(async res => { + for await (const chunk of res.body) { + // force consumption of body + } + return res.headers + }) + +// Do not +const headers = await fetch(url) + .then(res => res.headers) +``` + +However, if you want to get only headers, it might be better to use `HEAD` request method. Usage of this method will obviate the need for consumption or cancelling of the response body. See [MDN - HTTP - HTTP request methods - HEAD](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD) for more details. + +```js +const headers = await fetch(url, { method: 'HEAD' }) + .then(res => res.headers) +``` + +##### Forbidden and Safelisted Header Names + +* https://fetch.spec.whatwg.org/#cors-safelisted-response-header-name +* https://fetch.spec.whatwg.org/#forbidden-header-name +* https://fetch.spec.whatwg.org/#forbidden-response-header-name +* https://github.com/wintercg/fetch/issues/6 + +The [Fetch Standard](https://fetch.spec.whatwg.org) requires implementations to exclude certain headers from requests and responses. In browser environments, some headers are forbidden so the user agent remains in full control over them. In Undici, these constraints are removed to give more control to the user. + +### `undici.upgrade([url, options]): Promise` + +Upgrade to a different protocol. See [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **url** `string | URL | UrlObject` +* **options** [`UpgradeOptions`](docs/api/Dispatcher.md#parameter-upgradeoptions) + * **dispatcher** `Dispatcher` - Default: [getGlobalDispatcher](#undicigetglobaldispatcher) + * **maxRedirections** `Integer` - Default: `0` +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns a promise with the result of the `Dispatcher.upgrade` method. + +Calls `options.dispatcher.upgrade(options)`. + +See [Dispatcher.upgrade](docs/api/Dispatcher.md#dispatcherupgradeoptions-callback) for more details. + +### `undici.setGlobalDispatcher(dispatcher)` + +* dispatcher `Dispatcher` + +Sets the global dispatcher used by Common API Methods. + +### `undici.getGlobalDispatcher()` + +Gets the global dispatcher used by Common API Methods. + +Returns: `Dispatcher` + +### `undici.setGlobalOrigin(origin)` + +* origin `string | URL | undefined` + +Sets the global origin used in `fetch`. + +If `undefined` is passed, the global origin will be reset. This will cause `Response.redirect`, `new Request()`, and `fetch` to throw an error when a relative path is passed. + +```js +setGlobalOrigin('http://localhost:3000') + +const response = await fetch('/api/ping') + +console.log(response.url) // http://localhost:3000/api/ping +``` + +### `undici.getGlobalOrigin()` + +Gets the global origin used in `fetch`. + +Returns: `URL` + +### `UrlObject` + +* **port** `string | number` (optional) +* **path** `string` (optional) +* **pathname** `string` (optional) +* **hostname** `string` (optional) +* **origin** `string` (optional) +* **protocol** `string` (optional) +* **search** `string` (optional) + +## Specification Compliance + +This section documents parts of the HTTP/1.1 specification that Undici does +not support or does not fully implement. + +### Expect + +Undici does not support the `Expect` request header field. The request +body is always immediately sent and the `100 Continue` response will be +ignored. + +Refs: https://tools.ietf.org/html/rfc7231#section-5.1.1 + +### Pipelining + +Undici will only use pipelining if configured with a `pipelining` factor +greater than `1`. + +Undici always assumes that connections are persistent and will immediately +pipeline requests, without checking whether the connection is persistent. +Hence, automatic fallback to HTTP/1.0 or HTTP/1.1 without pipelining is +not supported. + +Undici will immediately pipeline when retrying requests after a failed +connection. However, Undici will not retry the first remaining requests in +the prior pipeline and instead error the corresponding callback/promise/stream. + +Undici will abort all running requests in the pipeline when any of them are +aborted. + +* Refs: https://tools.ietf.org/html/rfc2616#section-8.1.2.2 +* Refs: https://tools.ietf.org/html/rfc7230#section-6.3.2 + +### Manual Redirect + +Since it is not possible to manually follow an HTTP redirect on the server-side, +Undici returns the actual response instead of an `opaqueredirect` filtered one +when invoked with a `manual` redirect. This aligns `fetch()` with the other +implementations in Deno and Cloudflare Workers. + +Refs: https://fetch.spec.whatwg.org/#atomic-http-redirect-handling + +## Workarounds + +### Network address family autoselection. + +If you experience problem when connecting to a remote server that is resolved by your DNS servers to a IPv6 (AAAA record) +first, there are chances that your local router or ISP might have problem connecting to IPv6 networks. In that case +undici will throw an error with code `UND_ERR_CONNECT_TIMEOUT`. + +If the target server resolves to both a IPv6 and IPv4 (A records) address and you are using a compatible Node version +(18.3.0 and above), you can fix the problem by providing the `autoSelectFamily` option (support by both `undici.request` +and `undici.Agent`) which will enable the family autoselection algorithm when establishing the connection. + +## Collaborators + +* [__Daniele Belardi__](https://github.com/dnlup), +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Matthew Aitken__](https://github.com/KhafraDev), +* [__Robert Nagy__](https://github.com/ronag), +* [__Szymon Marczak__](https://github.com/szmarczak), +* [__Tomas Della Vedova__](https://github.com/delvedor), + +### Releasers + +* [__Ethan Arrowood__](https://github.com/ethan-arrowood), +* [__Matteo Collina__](https://github.com/mcollina), +* [__Robert Nagy__](https://github.com/ronag), +* [__Matthew Aitken__](https://github.com/KhafraDev), + +## License + +MIT diff --git a/node_modules/undici/docs/api/Agent.md b/node_modules/undici/docs/api/Agent.md new file mode 100644 index 0000000..dd5d99b --- /dev/null +++ b/node_modules/undici/docs/api/Agent.md @@ -0,0 +1,80 @@ +# Agent + +Extends: `undici.Dispatcher` + +Agent allow dispatching requests against multiple different origins. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new undici.Agent([options])` + +Arguments: + +* **options** `AgentOptions` (optional) + +Returns: `Agent` + +### Parameter: `AgentOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` +* **maxRedirections** `Integer` - Default: `0`. The number of HTTP redirection to follow unless otherwise specified in `DispatchOptions`. +* **interceptors** `{ Agent: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. + +## Instance Properties + +### `Agent.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Agent.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +## Instance Methods + +### `Agent.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Agent.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.dispatch(options, handler: AgentDispatchOptions)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +#### Parameter: `AgentDispatchOptions` + +Extends: [`DispatchOptions`](Dispatcher.md#parameter-dispatchoptions) + +* **origin** `string | URL` +* **maxRedirections** `Integer`. + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Agent.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Agent.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Agent.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Agent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Agent.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Agent.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). diff --git a/node_modules/undici/docs/api/BalancedPool.md b/node_modules/undici/docs/api/BalancedPool.md new file mode 100644 index 0000000..290c734 --- /dev/null +++ b/node_modules/undici/docs/api/BalancedPool.md @@ -0,0 +1,99 @@ +# Class: BalancedPool + +Extends: `undici.Dispatcher` + +A pool of [Pool](Pool.md) instances connected to multiple upstreams. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new BalancedPool(upstreams [, options])` + +Arguments: + +* **upstreams** `URL | string | string[]` - It should only include the **protocol, hostname, and port**. +* **options** `BalancedPoolOptions` (optional) + +### Parameter: `BalancedPoolOptions` + +Extends: [`PoolOptions`](Pool.md#parameter-pooloptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Pool(origin, opts)` + +The `PoolOptions` are passed to each of the `Pool` instances being created. +## Instance Properties + +### `BalancedPool.upstreams` + +Returns an array of upstreams that were previously added. + +### `BalancedPool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `BalancedPool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `BalancedPool.addUpstream(upstream)` + +Add an upstream. + +Arguments: + +* **upstream** `string` - It should only include the **protocol, hostname, and port**. + +### `BalancedPool.removeUpstream(upstream)` + +Removes an upstream that was previously addded. + +### `BalancedPool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `BalancedPool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `BalancedPool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `BalancedPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `BalancedPool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `BalancedPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `BalancedPool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `BalancedPool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/CacheStorage.md b/node_modules/undici/docs/api/CacheStorage.md new file mode 100644 index 0000000..08ee99f --- /dev/null +++ b/node_modules/undici/docs/api/CacheStorage.md @@ -0,0 +1,30 @@ +# CacheStorage + +Undici exposes a W3C spec-compliant implementation of [CacheStorage](https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage) and [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache). + +## Opening a Cache + +Undici exports a top-level CacheStorage instance. You can open a new Cache, or duplicate a Cache with an existing name, by using `CacheStorage.prototype.open`. If you open a Cache with the same name as an already-existing Cache, its list of cached Responses will be shared between both instances. + +```mjs +import { caches } from 'undici' + +const cache_1 = await caches.open('v1') +const cache_2 = await caches.open('v1') + +// Although .open() creates a new instance, +assert(cache_1 !== cache_2) +// The same Response is matched in both. +assert.deepStrictEqual(await cache_1.match('/req'), await cache_2.match('/req')) +``` + +## Deleting a Cache + +If a Cache is deleted, the cached Responses/Requests can still be used. + +```mjs +const response = await cache_1.match('/req') +await caches.delete('v1') + +await response.text() // the Response's body +``` diff --git a/node_modules/undici/docs/api/Client.md b/node_modules/undici/docs/api/Client.md new file mode 100644 index 0000000..b9e26f0 --- /dev/null +++ b/node_modules/undici/docs/api/Client.md @@ -0,0 +1,273 @@ +# Class: Client + +Extends: `undici.Dispatcher` + +A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Client(url[, options])` + +Arguments: + +* **url** `URL | string` - Should only include the **protocol, hostname, and port**. +* **options** `ClientOptions` (optional) + +Returns: `Client` + +### Parameter: `ClientOptions` + +> ⚠️ Warning: The `H2` support is experimental. + +* **bodyTimeout** `number | null` (optional) - Default: `300e3` - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - Default: `300e3` - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **keepAliveMaxTimeout** `number | null` (optional) - Default: `600e3` - The maximum allowed `keepAliveTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Defaults to 10 minutes. +* **keepAliveTimeout** `number | null` (optional) - Default: `4e3` - The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. See [MDN: HTTP - Headers - Keep-Alive directives](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Keep-Alive#directives) for more details. Defaults to 4 seconds. +* **keepAliveTimeoutThreshold** `number | null` (optional) - Default: `1e3` - A number of milliseconds subtracted from server *keep-alive* hints when overriding `keepAliveTimeout` to account for timing inaccuracies caused by e.g. transport latency. Defaults to 1 second. +* **maxHeaderSize** `number | null` (optional) - Default: `--max-http-header-size` or `16384` - The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. +* **maxResponseSize** `number | null` (optional) - Default: `-1` - The maximum length of response body in bytes. Set to `-1` to disable. +* **pipelining** `number | null` (optional) - Default: `1` - The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to `0` to disable keep-alive connections. +* **connect** `ConnectOptions | Function | null` (optional) - Default: `null`. +* **strictContentLength** `Boolean` (optional) - Default: `true` - Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. +* **interceptors** `{ Client: DispatchInterceptor[] }` - Default: `[RedirectInterceptor]` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). Note that the behavior of interceptors is Experimental and might change at any given time. +* **autoSelectFamily**: `boolean` (optional) - Default: depends on local Node version, on Node 18.13.0 and above is `false`. Enables a family autodetection algorithm that loosely implements section 5 of [RFC 8305](https://tools.ietf.org/html/rfc8305#section-5). See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. This option is ignored if not supported by the current Node version. +* **autoSelectFamilyAttemptTimeout**: `number` - Default: depends on local Node version, on Node 18.13.0 and above is `250`. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. See [here](https://nodejs.org/api/net.html#socketconnectoptions-connectlistener) for more details. +* **allowH2**: `boolean` - Default: `false`. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. +* **maxConcurrentStreams**: `number` - Default: `100`. Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + +#### Parameter: `ConnectOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. +* **timeout** `number | null` (optional) - In milliseconds, Default `10e3`. +* **servername** `string | null` (optional) +* **keepAlive** `boolean | null` (optional) - Default: `true` - TCP keep-alive enabled +* **keepAliveInitialDelay** `number | null` (optional) - Default: `60000` - TCP keep-alive interval for the socket in milliseconds + +### Example - Basic Client instantiation + +This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using `client.connect` to prematurely connect to the origin, or just call `client.request`. + +```js +'use strict' +import { Client } from 'undici' + +const client = new Client('http://localhost:3000') +``` + +### Example - Custom connector + +This will allow you to perform some additional check on the socket that will be used for the next request. + +```js +'use strict' +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +## Instance Methods + +### `Client.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Client.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). + +### `Client.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Client.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Client.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Client.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Client.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Client.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Properties + +### `Client.closed` + +* `boolean` + +`true` after `client.close()` has been called. + +### `Client.destroyed` + +* `boolean` + +`true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. + +### `Client.pipelining` + +* `number` + +Property to get and set the pipelining factor. + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +Emitted when a socket has been created and connected. The client will connect once `client.size > 0`. + +#### Example - Client connect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('connect', (origin) => { + console.log(`Connected to ${origin}`) // should print before the request body statement +}) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf-8') + body.on('data', console.log) + client.close() + server.close() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once `client.size > 0`. + +#### Example - Client disconnect event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.destroy() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('disconnect', (origin) => { + console.log(`Disconnected from ${origin}`) +}) + +try { + await client.request({ + path: '/', + method: 'GET' + }) +} catch (error) { + console.error(error.message) + client.close() + server.close() +} +``` + +### Event: `'drain'` + +Emitted when pipeline is no longer busy. + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). + +#### Example - Client drain event + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +client.on('drain', () => { + console.log('drain event') + client.close() + server.close() +}) + +const requests = [ + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }), + client.request({ path: '/', method: 'GET' }) +] + +await Promise.all(requests) + +console.log('requests completed') +``` + +### Event: `'error'` + +Invoked for users errors such as throwing in the `onError` handler. diff --git a/node_modules/undici/docs/api/Connector.md b/node_modules/undici/docs/api/Connector.md new file mode 100644 index 0000000..56821bd --- /dev/null +++ b/node_modules/undici/docs/api/Connector.md @@ -0,0 +1,115 @@ +# Connector + +Undici creates the underlying socket via the connector builder. +Normally, this happens automatically and you don't need to care about this, +but if you need to perform some additional check over the currently used socket, +this is the right place. + +If you want to create a custom connector, you must import the `buildConnector` utility. + +#### Parameter: `buildConnector.BuildOptions` + +Every Tls option, see [here](https://nodejs.org/api/tls.html#tls_tls_connect_options_callback). +Furthermore, the following options can be passed: + +* **socketPath** `string | null` (optional) - Default: `null` - An IPC endpoint, either Unix domain socket or Windows named pipe. +* **maxCachedSessions** `number | null` (optional) - Default: `100` - Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: `100`. +* **timeout** `number | null` (optional) - In milliseconds. Default `10e3`. +* **servername** `string | null` (optional) + +Once you call `buildConnector`, it will return a connector function, which takes the following parameters. + +#### Parameter: `connector.Options` + +* **hostname** `string` (required) +* **host** `string` (optional) +* **protocol** `string` (required) +* **port** `string` (required) +* **servername** `string` (optional) +* **localAddress** `string | null` (optional) Local address the socket should connect from. +* **httpSocket** `Socket` (optional) Establish secure connection on a given socket rather than creating a new socket. It can only be sent on TLS update. + +### Basic example + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (/* assertion */) { + socket.destroy() + cb(new Error('kaboom')) + } else { + cb(null, socket) + } + }) + } +}) +``` + +### Example: validate the CA fingerprint + +```js +'use strict' + +import { Client, buildConnector } from 'undici' + +const caFingerprint = 'FO:OB:AR' +const connector = buildConnector({ rejectUnauthorized: false }) +const client = new Client('https://localhost:3000', { + connect (opts, cb) { + connector(opts, (err, socket) => { + if (err) { + cb(err) + } else if (getIssuerCertificate(socket).fingerprint256 !== caFingerprint) { + socket.destroy() + cb(new Error('Fingerprint does not match or malformed certificate')) + } else { + cb(null, socket) + } + }) + } +}) + +client.request({ + path: '/', + method: 'GET' +}, (err, data) => { + if (err) throw err + + const bufs = [] + data.body.on('data', (buf) => { + bufs.push(buf) + }) + data.body.on('end', () => { + console.log(Buffer.concat(bufs).toString('utf8')) + client.close() + }) +}) + +function getIssuerCertificate (socket) { + let certificate = socket.getPeerCertificate(true) + while (certificate && Object.keys(certificate).length > 0) { + // invalid certificate + if (certificate.issuerCertificate == null) { + return null + } + + // We have reached the root certificate. + // In case of self-signed certificates, `issuerCertificate` may be a circular reference. + if (certificate.fingerprint256 === certificate.issuerCertificate.fingerprint256) { + break + } + + // continue the loop + certificate = certificate.issuerCertificate + } + return certificate +} +``` diff --git a/node_modules/undici/docs/api/ContentType.md b/node_modules/undici/docs/api/ContentType.md new file mode 100644 index 0000000..2bcc9f7 --- /dev/null +++ b/node_modules/undici/docs/api/ContentType.md @@ -0,0 +1,57 @@ +# MIME Type Parsing + +## `MIMEType` interface + +* **type** `string` +* **subtype** `string` +* **parameters** `Map` +* **essence** `string` + +## `parseMIMEType(input)` + +Implements [parse a MIME type](https://mimesniff.spec.whatwg.org/#parse-a-mime-type). + +Parses a MIME type, returning its type, subtype, and any associated parameters. If the parser can't parse an input it returns the string literal `'failure'`. + +```js +import { parseMIMEType } from 'undici' + +parseMIMEType('text/html; charset=gbk') +// { +// type: 'text', +// subtype: 'html', +// parameters: Map(1) { 'charset' => 'gbk' }, +// essence: 'text/html' +// } +``` + +Arguments: + +* **input** `string` + +Returns: `MIMEType|'failure'` + +## `serializeAMimeType(input)` + +Implements [serialize a MIME type](https://mimesniff.spec.whatwg.org/#serialize-a-mime-type). + +Serializes a MIMEType object. + +```js +import { serializeAMimeType } from 'undici' + +serializeAMimeType({ + type: 'text', + subtype: 'html', + parameters: new Map([['charset', 'gbk']]), + essence: 'text/html' +}) +// text/html;charset=gbk + +``` + +Arguments: + +* **mimeType** `MIMEType` + +Returns: `string` diff --git a/node_modules/undici/docs/api/Cookies.md b/node_modules/undici/docs/api/Cookies.md new file mode 100644 index 0000000..0cad379 --- /dev/null +++ b/node_modules/undici/docs/api/Cookies.md @@ -0,0 +1,101 @@ +# Cookie Handling + +## `Cookie` interface + +* **name** `string` +* **value** `string` +* **expires** `Date|number` (optional) +* **maxAge** `number` (optional) +* **domain** `string` (optional) +* **path** `string` (optional) +* **secure** `boolean` (optional) +* **httpOnly** `boolean` (optional) +* **sameSite** `'String'|'Lax'|'None'` (optional) +* **unparsed** `string[]` (optional) Left over attributes that weren't parsed. + +## `deleteCookie(headers, name[, attributes])` + +Sets the expiry time of the cookie to the unix epoch, causing browsers to delete it when received. + +```js +import { deleteCookie, Headers } from 'undici' + +const headers = new Headers() +deleteCookie(headers, 'name') + +console.log(headers.get('set-cookie')) // name=; Expires=Thu, 01 Jan 1970 00:00:00 GMT +``` + +Arguments: + +* **headers** `Headers` +* **name** `string` +* **attributes** `{ path?: string, domain?: string }` (optional) + +Returns: `void` + +## `getCookies(headers)` + +Parses the `Cookie` header and returns a list of attributes and values. + +```js +import { getCookies, Headers } from 'undici' + +const headers = new Headers({ + cookie: 'get=cookies; and=attributes' +}) + +console.log(getCookies(headers)) // { get: 'cookies', and: 'attributes' } +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Record` + +## `getSetCookies(headers)` + +Parses all `Set-Cookie` headers. + +```js +import { getSetCookies, Headers } from 'undici' + +const headers = new Headers({ 'set-cookie': 'undici=getSetCookies; Secure' }) + +console.log(getSetCookies(headers)) +// [ +// { +// name: 'undici', +// value: 'getSetCookies', +// secure: true +// } +// ] + +``` + +Arguments: + +* **headers** `Headers` + +Returns: `Cookie[]` + +## `setCookie(headers, cookie)` + +Appends a cookie to the `Set-Cookie` header. + +```js +import { setCookie, Headers } from 'undici' + +const headers = new Headers() +setCookie(headers, { name: 'undici', value: 'setCookie' }) + +console.log(headers.get('Set-Cookie')) // undici=setCookie +``` + +Arguments: + +* **headers** `Headers` +* **cookie** `Cookie` + +Returns: `void` diff --git a/node_modules/undici/docs/api/DiagnosticsChannel.md b/node_modules/undici/docs/api/DiagnosticsChannel.md new file mode 100644 index 0000000..0aa0b9a --- /dev/null +++ b/node_modules/undici/docs/api/DiagnosticsChannel.md @@ -0,0 +1,204 @@ +# Diagnostics Channel Support + +Stability: Experimental. + +Undici supports the [`diagnostics_channel`](https://nodejs.org/api/diagnostics_channel.html) (currently available only on Node.js v16+). +It is the preferred way to instrument Undici and retrieve internal information. + +The channels available are the following. + +## `undici:request:create` + +This message is published when a new outgoing request is created. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:create').subscribe(({ request }) => { + console.log('origin', request.origin) + console.log('completed', request.completed) + console.log('method', request.method) + console.log('path', request.path) + console.log('headers') // raw text, e.g: 'bar: bar\r\n' + request.addHeader('hello', 'world') + console.log('headers', request.headers) // e.g. 'bar: bar\r\nhello: world\r\n' +}) +``` + +Note: a request is only loosely completed to a given socket. + + +## `undici:request:bodySent` + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:bodySent').subscribe(({ request }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:request:headers` + +This message is published after the response headers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:headers').subscribe(({ request, response }) => { + // request is the same object undici:request:create + console.log('statusCode', response.statusCode) + console.log(response.statusText) + // response.headers are buffers. + console.log(response.headers.map((x) => x.toString())) +}) +``` + +## `undici:request:trailers` + +This message is published after the response body and trailers have been received, i.e. the response has been completed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:trailers').subscribe(({ request, trailers }) => { + // request is the same object undici:request:create + console.log('completed', request.completed) + // trailers are buffers. + console.log(trailers.map((x) => x.toString())) +}) +``` + +## `undici:request:error` + +This message is published if the request is going to error, but it has not errored yet. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:request:error').subscribe(({ request, error }) => { + // request is the same object undici:request:create +}) +``` + +## `undici:client:sendHeaders` + +This message is published right before the first byte of the request is written to the socket. + +*Note*: It will publish the exact headers that will be sent to the server in raw format. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:sendHeaders').subscribe(({ request, headers, socket }) => { + // request is the same object undici:request:create + console.log(`Full headers list ${headers.split('\r\n')}`); +}) +``` + +## `undici:client:beforeConnect` + +This message is published before creating a new connection for **any** request. +You can not assume that this event is related to any specific request. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:beforeConnect').subscribe(({ connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connected` + +This message is published after a connection is established. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connected').subscribe(({ socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket +}) +``` + +## `undici:client:connectError` + +This message is published if it did not succeed to create new connection + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:client:connectError').subscribe(({ error, socket, connectParams, connector }) => { + // const { host, hostname, protocol, port, servername } = connectParams + // connector is a function that creates the socket + console.log(`Connect failed with ${error.message}`) +}) +``` + +## `undici:websocket:open` + +This message is published after the client has successfully connected to a server. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:open').subscribe(({ address, protocol, extensions }) => { + console.log(address) // address, family, and port + console.log(protocol) // negotiated subprotocols + console.log(extensions) // negotiated extensions +}) +``` + +## `undici:websocket:close` + +This message is published after the connection has closed. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:close').subscribe(({ websocket, code, reason }) => { + console.log(websocket) // the WebSocket object + console.log(code) // the closing status code + console.log(reason) // the closing reason +}) +``` + +## `undici:websocket:socket_error` + +This message is published if the socket experiences an error. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:socket_error').subscribe((error) => { + console.log(error) +}) +``` + +## `undici:websocket:ping` + +This message is published after the client receives a ping frame, if the connection is not closing. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:ping').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` + +## `undici:websocket:pong` + +This message is published after the client receives a pong frame. + +```js +import diagnosticsChannel from 'diagnostics_channel' + +diagnosticsChannel.channel('undici:websocket:pong').subscribe(({ payload }) => { + // a Buffer or undefined, containing the optional application data of the frame + console.log(payload) +}) +``` diff --git a/node_modules/undici/docs/api/DispatchInterceptor.md b/node_modules/undici/docs/api/DispatchInterceptor.md new file mode 100644 index 0000000..7dfc260 --- /dev/null +++ b/node_modules/undici/docs/api/DispatchInterceptor.md @@ -0,0 +1,60 @@ +# Interface: DispatchInterceptor + +Extends: `Function` + +A function that can be applied to the `Dispatcher.Dispatch` function before it is invoked with a dispatch request. + +This allows one to write logic to intercept both the outgoing request, and the incoming response. + +### Parameter: `Dispatcher.Dispatch` + +The base dispatch function you are decorating. + +### ReturnType: `Dispatcher.Dispatch` + +A dispatch function that has been altered to provide additional logic + +### Basic Example + +Here is an example of an interceptor being used to provide a JWT bearer token + +```js +'use strict' + +const insertHeaderInterceptor = dispatch => { + return function InterceptedDispatch(opts, handler){ + opts.headers.push('Authorization', 'Bearer [Some token]') + return dispatch(opts, handler) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [insertHeaderInterceptor] } +}) + +``` + +### Basic Example 2 + +Here is a contrived example of an interceptor stripping the headers from a response. + +```js +'use strict' + +const clearHeadersInterceptor = dispatch => { + const { DecoratorHandler } = require('undici') + class ResultInterceptor extends DecoratorHandler { + onHeaders (statusCode, headers, resume) { + return super.onHeaders(statusCode, [], resume) + } + } + return function InterceptedDispatch(opts, handler){ + return dispatch(opts, new ResultInterceptor(handler)) + } +} + +const client = new Client('https://localhost:3000', { + interceptors: { Client: [clearHeadersInterceptor] } +}) + +``` diff --git a/node_modules/undici/docs/api/Dispatcher.md b/node_modules/undici/docs/api/Dispatcher.md new file mode 100644 index 0000000..fd463bf --- /dev/null +++ b/node_modules/undici/docs/api/Dispatcher.md @@ -0,0 +1,887 @@ +# Dispatcher + +Extends: `events.EventEmitter` + +Dispatcher is the core API used to dispatch requests. + +Requests are not guaranteed to be dispatched in order of invocation. + +## Instance Methods + +### `Dispatcher.close([callback]): Promise` + +Closes the dispatcher and gracefully waits for enqueued requests to complete before resolving. + +Arguments: + +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.close() // -> Promise +dispatcher.close(() => {}) // -> void +``` + +#### Example - Request resolves before Client closes + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('undici') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.setEncoding('utf8') + body.on('data', console.log) +} catch (error) {} + +await client.close() + +console.log('Client closed') +server.close() +``` + +### `Dispatcher.connect(options[, callback])` + +Starts two-way communications with the requested resource using [HTTP CONNECT](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/CONNECT). + +Arguments: + +* **options** `ConnectOptions` +* **callback** `(err: Error | null, data: ConnectData | null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `ConnectOptions` + +* **path** `string` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null` +* **opaque** `unknown` (optional) - This argument parameter is passed through to `ConnectData` + +#### Parameter: `ConnectData` + +* **statusCode** `number` +* **headers** `Record` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example - Connect request with echo + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + throw Error('should never get here') +}).listen() + +server.on('connect', (req, socket, head) => { + socket.write('HTTP/1.1 200 Connection established\r\n\r\n') + + let data = head.toString() + socket.on('data', (buf) => { + data += buf.toString() + }) + + socket.on('end', () => { + socket.end(data) + }) +}) + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { socket } = await client.connect({ + path: '/' + }) + const wanted = 'Body' + let data = '' + socket.on('data', d => { data += d }) + socket.on('end', () => { + console.log(`Data received: ${data.toString()} | Data wanted: ${wanted}`) + client.close() + server.close() + }) + socket.write(wanted) + socket.end() +} catch (error) { } +``` + +### `Dispatcher.destroy([error, callback]): Promise` + +Destroy the dispatcher abruptly with the given error. All the pending and running requests will be asynchronously aborted and error. Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. + +Both arguments are optional; the method can be called in four different ways: + +Arguments: + +* **error** `Error | null` (optional) +* **callback** `(error: Error | null, data: null) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +```js +dispatcher.destroy() // -> Promise +dispatcher.destroy(new Error()) // -> Promise +dispatcher.destroy(() => {}) // -> void +dispatcher.destroy(new Error(), () => {}) // -> void +``` + +#### Example - Request is aborted when Client is destroyed + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const request = client.request({ + path: '/', + method: 'GET' + }) + client.destroy() + .then(() => { + console.log('Client destroyed') + server.close() + }) + await request +} catch (error) { + console.error(error) +} +``` + +### `Dispatcher.dispatch(options, handler)` + +This is the low level API which all the preceding APIs are implemented on top of. +This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. +It is primarily intended for library developers who implement higher level APIs on top of this. + +Arguments: + +* **options** `DispatchOptions` +* **handler** `DispatchHandler` + +Returns: `Boolean` - `false` if dispatcher is busy and further dispatch calls won't make any progress until the `'drain'` event has been emitted. + +#### Parameter: `DispatchOptions` + +* **origin** `string | URL` +* **path** `string` +* **method** `string` +* **reset** `boolean` (optional) - Default: `false` - If `false`, the request will attempt to create a long-living connection by sending the `connection: keep-alive` header,otherwise will attempt to close it immediately after response by sending `connection: close` within the request and closing the socket afterwards. +* **body** `string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null` (optional) - Default: `null` +* **headers** `UndiciHeaders | string[]` (optional) - Default: `null`. +* **query** `Record | null` (optional) - Default: `null` - Query string params to be embedded in the request URL. Note that both keys and values of query are encoded using `encodeURIComponent`. If for some reason you need to send them unencoded, embed query params into path directly instead. +* **idempotent** `boolean` (optional) - Default: `true` if `method` is `'HEAD'` or `'GET'` - Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline has completed. +* **blocking** `boolean` (optional) - Default: `false` - Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. +* **upgrade** `string | null` (optional) - Default: `null` - Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. +* **bodyTimeout** `number | null` (optional) - The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Defaults to 300 seconds. +* **headersTimeout** `number | null` (optional) - The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. +* **throwOnError** `boolean` (optional) - Default: `false` - Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. +* **expectContinue** `boolean` (optional) - Default: `false` - For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server + +#### Parameter: `DispatchHandler` + +* **onConnect** `(abort: () => void, context: object) => void` - Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. +* **onError** `(error: Error) => void` - Invoked when an error has occurred. May not throw. +* **onUpgrade** `(statusCode: number, headers: Buffer[], socket: Duplex) => void` (optional) - Invoked when request is upgraded. Required if `DispatchOptions.upgrade` is defined or `DispatchOptions.method === 'CONNECT'`. +* **onHeaders** `(statusCode: number, headers: Buffer[], resume: () => void, statusText: string) => boolean` - Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. Not required for `upgrade` requests. +* **onData** `(chunk: Buffer) => boolean` - Invoked when response payload data is received. Not required for `upgrade` requests. +* **onComplete** `(trailers: Buffer[]) => void` - Invoked when response payload and trailers have been received and the request has completed. Not required for `upgrade` requests. +* **onBodySent** `(chunk: string | Buffer | Uint8Array) => void` - Invoked when a body chunk is sent to the server. Not required. For a stream or iterable body this will be invoked for every chunk. For other body types, it will be invoked once after the body is sent. + +#### Example 1 - Dispatch GET request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'GET', + headers: { + 'x-foo': 'bar' + } +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Data: ${res}`) + client.close() + server.close() + } +}) +``` + +#### Example 2 - Dispatch Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end() +}).listen() + +await once(server, 'listening') + +server.on('upgrade', (request, socket, head) => { + console.log('Node.js Server - upgrade event') + socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n') + socket.write('Upgrade: WebSocket\r\n') + socket.write('Connection: Upgrade\r\n') + socket.write('\r\n') + socket.end() +}) + +const client = new Client(`http://localhost:${server.address().port}`) + +client.dispatch({ + path: '/', + method: 'GET', + upgrade: 'websocket' +}, { + onConnect: () => { + console.log('Undici Client - onConnect') + }, + onError: (error) => { + console.log('onError') // shouldn't print + }, + onUpgrade: (statusCode, headers, socket) => { + console.log('Undici Client - onUpgrade') + console.log(`onUpgrade Headers: ${headers}`) + socket.on('data', buffer => { + console.log(buffer.toString('utf8')) + }) + socket.on('end', () => { + client.close() + server.close() + }) + socket.end() + } +}) +``` + +#### Example 3 - Dispatch POST request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.on('data', (data) => { + console.log(`Request Data: ${data.toString('utf8')}`) + const body = JSON.parse(data) + body.message = 'World' + response.end(JSON.stringify(body)) + }) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const data = [] + +client.dispatch({ + path: '/', + method: 'POST', + headers: { + 'content-type': 'application/json' + }, + body: JSON.stringify({ message: 'Hello' }) +}, { + onConnect: () => { + console.log('Connected!') + }, + onError: (error) => { + console.error(error) + }, + onHeaders: (statusCode, headers) => { + console.log(`onHeaders | statusCode: ${statusCode} | headers: ${headers}`) + }, + onData: (chunk) => { + console.log('onData: chunk received') + data.push(chunk) + }, + onComplete: (trailers) => { + console.log(`onComplete | trailers: ${trailers}`) + const res = Buffer.concat(data).toString('utf8') + console.log(`Response Data: ${res}`) + client.close() + server.close() + } +}) +``` + +### `Dispatcher.pipeline(options, handler)` + +For easy use with [stream.pipeline](https://nodejs.org/api/stream.html#stream_stream_pipeline_source_transforms_destination_callback). The `handler` argument should return a `Readable` from which the result will be read. Usually it should just return the `body` argument unless some kind of transformation needs to be performed based on e.g. `headers` or `statusCode`. The `handler` should validate the response and save any required state. If there is an error, it should be thrown. The function returns a `Duplex` which writes to the request and reads from the response. + +Arguments: + +* **options** `PipelineOptions` +* **handler** `(data: PipelineHandlerData) => stream.Readable` + +Returns: `stream.Duplex` + +#### Parameter: PipelineOptions + +Extends: [`RequestOptions`](#parameter-requestoptions) + +* **objectMode** `boolean` (optional) - Default: `false` - Set to `true` if the `handler` will return an object stream. + +#### Parameter: PipelineHandlerData + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **body** `stream.Readable` +* **context** `object` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Example 1 - Pipeline Echo + +```js +import { Readable, Writable, PassThrough, pipeline } from 'stream' +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + request.pipe(response) +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +let res = '' + +pipeline( + new Readable({ + read () { + this.push(Buffer.from('undici')) + this.push(null) + } + }), + client.pipeline({ + path: '/', + method: 'GET' + }, ({ statusCode, headers, body }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return pipeline(body, new PassThrough(), () => {}) + }), + new Writable({ + write (chunk, _, callback) { + res += chunk.toString() + callback() + }, + final (callback) { + console.log(`Response pipelined to writable: ${res}`) + callback() + } + }), + error => { + if (error) { + console.error(error) + } + + client.close() + server.close() + } +) +``` + +### `Dispatcher.request(options[, callback])` + +Performs a HTTP request. + +Non-idempotent requests will not be pipelined in order +to avoid indirect failures. + +Idempotent requests will be automatically retried if +they fail due to indirect failure from the request +at the head of the pipeline. This does not apply to +idempotent requests with a stream request body. + +All response bodies must always be fully consumed or destroyed. + +Arguments: + +* **options** `RequestOptions` +* **callback** `(error: Error | null, data: ResponseData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed. + +#### Parameter: `RequestOptions` + +Extends: [`DispatchOptions`](#parameter-dispatchoptions) + +* **opaque** `unknown` (optional) - Default: `null` - Used for passing through context to `ResponseData`. +* **signal** `AbortSignal | events.EventEmitter | null` (optional) - Default: `null`. +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +The `RequestOptions.method` property should not be value `'CONNECT'`. + +#### Parameter: `ResponseData` + +* **statusCode** `number` +* **headers** `Record` - Note that all header keys are lower-cased, e. g. `content-type`. +* **body** `stream.Readable` which also implements [the body mixin from the Fetch Standard](https://fetch.spec.whatwg.org/#body-mixin). +* **trailers** `Record` - This object starts out + as empty and will be mutated to contain trailers after `body` has emitted `'end'`. +* **opaque** `unknown` +* **context** `object` + +`body` contains the following additional [body mixin](https://fetch.spec.whatwg.org/#body-mixin) methods and properties: + +- `text()` +- `json()` +- `arrayBuffer()` +- `body` +- `bodyUsed` + +`body` can not be consumed twice. For example, calling `text()` after `json()` throws `TypeError`. + +`body` contains the following additional extensions: + +- `dump({ limit: Integer })`, dump the response by reading up to `limit` bytes without killing the socket (optional) - Default: 262144. + +Note that body will still be a `Readable` even if it is empty, but attempting to deserialize it with `json()` will result in an exception. Recommended way to ensure there is a body to deserialize is to check if status code is not 204, and `content-type` header starts with `application/json`. + +#### Example 1 - Basic GET Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body, headers, statusCode, trailers } = await client.request({ + path: '/', + method: 'GET' + }) + console.log(`response received ${statusCode}`) + console.log('headers', headers) + body.setEncoding('utf8') + body.on('data', console.log) + body.on('end', () => { + console.log('trailers', trailers) + }) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Aborting a request + +> Node.js v15+ is required to run this example + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const abortController = new AbortController() + +try { + client.request({ + path: '/', + method: 'GET', + signal: abortController.signal + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +abortController.abort() +``` + +Alternatively, any `EventEmitter` that emits an `'abort'` event may be used as an abort controller: + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import EventEmitter, { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) +const ee = new EventEmitter() + +try { + client.request({ + path: '/', + method: 'GET', + signal: ee + }) +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} + +ee.emit('abort') +``` + +Destroying the request or response body will have the same effect. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { body } = await client.request({ + path: '/', + method: 'GET' + }) + body.destroy() +} catch (error) { + console.error(error) // should print an RequestAbortedError + client.close() + server.close() +} +``` + +### `Dispatcher.stream(options, factory[, callback])` + +A faster version of `Dispatcher.request`. This method expects the second argument `factory` to return a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream which the response will be written to. This improves performance by avoiding creating an intermediate [`stream.Readable`](https://nodejs.org/api/stream.html#stream_readable_streams) stream when the user expects to directly pipe the response body to a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable) stream. + +As demonstrated in [Example 1 - Basic GET stream request](#example-1---basic-get-stream-request), it is recommended to use the `option.opaque` property to avoid creating a closure for the `factory` method. This pattern works well with Node.js Web Frameworks such as [Fastify](https://fastify.io). See [Example 2 - Stream to Fastify Response](#example-2---stream-to-fastify-response) for more details. + +Arguments: + +* **options** `RequestOptions` +* **factory** `(data: StreamFactoryData) => stream.Writable` +* **callback** `(error: Error | null, data: StreamData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `StreamFactoryData` + +* **statusCode** `number` +* **headers** `Record` +* **opaque** `unknown` +* **onInfo** `({statusCode: number, headers: Record}) => void | null` (optional) - Default: `null` - Callback collecting all the info headers (HTTP 100-199) received. + +#### Parameter: `StreamData` + +* **opaque** `unknown` +* **trailers** `Record` +* **context** `object` + +#### Example 1 - Basic GET stream request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import { Writable } from 'stream' + +const server = createServer((request, response) => { + response.end('Hello, World!') +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +const bufs = [] + +try { + await client.stream({ + path: '/', + method: 'GET', + opaque: { bufs } + }, ({ statusCode, headers, opaque: { bufs } }) => { + console.log(`response received ${statusCode}`) + console.log('headers', headers) + return new Writable({ + write (chunk, encoding, callback) { + bufs.push(chunk) + callback() + } + }) + }) + + console.log(Buffer.concat(bufs).toString('utf-8')) + + client.close() + server.close() +} catch (error) { + console.error(error) +} +``` + +#### Example 2 - Stream to Fastify Response + +In this example, a (fake) request is made to the fastify server using `fastify.inject()`. This request then executes the fastify route handler which makes a subsequent request to the raw Node.js http server using `undici.dispatcher.stream()`. The fastify response is passed to the `opaque` option so that undici can tap into the underlying writable stream using `response.raw`. This methodology demonstrates how one could use undici and fastify together to create fast-as-possible requests from one backend server to another. + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' +import fastify from 'fastify' + +const nodeServer = createServer((request, response) => { + response.end('Hello, World! From Node.js HTTP Server') +}).listen() + +await once(nodeServer, 'listening') + +console.log('Node Server listening') + +const nodeServerUndiciClient = new Client(`http://localhost:${nodeServer.address().port}`) + +const fastifyServer = fastify() + +fastifyServer.route({ + url: '/', + method: 'GET', + handler: (request, response) => { + nodeServerUndiciClient.stream({ + path: '/', + method: 'GET', + opaque: response + }, ({ opaque }) => opaque.raw) + } +}) + +await fastifyServer.listen() + +console.log('Fastify Server listening') + +const fastifyServerUndiciClient = new Client(`http://localhost:${fastifyServer.server.address().port}`) + +try { + const { statusCode, body } = await fastifyServerUndiciClient.request({ + path: '/', + method: 'GET' + }) + + console.log(`response received ${statusCode}`) + body.setEncoding('utf8') + body.on('data', console.log) + + nodeServerUndiciClient.close() + fastifyServerUndiciClient.close() + fastifyServer.close() + nodeServer.close() +} catch (error) { } +``` + +### `Dispatcher.upgrade(options[, callback])` + +Upgrade to a different protocol. Visit [MDN - HTTP - Protocol upgrade mechanism](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) for more details. + +Arguments: + +* **options** `UpgradeOptions` + +* **callback** `(error: Error | null, data: UpgradeData) => void` (optional) + +Returns: `void | Promise` - Only returns a `Promise` if no `callback` argument was passed + +#### Parameter: `UpgradeOptions` + +* **path** `string` +* **method** `string` (optional) - Default: `'GET'` +* **headers** `UndiciHeaders` (optional) - Default: `null` +* **protocol** `string` (optional) - Default: `'Websocket'` - A string of comma separated protocols, in descending preference order. +* **signal** `AbortSignal | EventEmitter | null` (optional) - Default: `null` + +#### Parameter: `UpgradeData` + +* **headers** `http.IncomingHeaders` +* **socket** `stream.Duplex` +* **opaque** `unknown` + +#### Example 1 - Basic Upgrade Request + +```js +import { createServer } from 'http' +import { Client } from 'undici' +import { once } from 'events' + +const server = createServer((request, response) => { + response.statusCode = 101 + response.setHeader('connection', 'upgrade') + response.setHeader('upgrade', request.headers.upgrade) + response.end() +}).listen() + +await once(server, 'listening') + +const client = new Client(`http://localhost:${server.address().port}`) + +try { + const { headers, socket } = await client.upgrade({ + path: '/', + }) + socket.on('end', () => { + console.log(`upgrade: ${headers.upgrade}`) // upgrade: Websocket + client.close() + server.close() + }) + socket.end() +} catch (error) { + console.error(error) + client.close() + server.close() +} +``` + +## Instance Events + +### Event: `'connect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` + +### Event: `'disconnect'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +### Event: `'connectionError'` + +Parameters: + +* **origin** `URL` +* **targets** `Array` +* **error** `Error` + +Emitted when dispatcher fails to connect to +origin. + +### Event: `'drain'` + +Parameters: + +* **origin** `URL` + +Emitted when dispatcher is no longer busy. + +## Parameter: `UndiciHeaders` + +* `Record | string[] | null` + +Header arguments such as `options.headers` in [`Client.dispatch`](Client.md#clientdispatchoptions-handlers) can be specified in two forms; either as an object specified by the `Record` (`IncomingHttpHeaders`) type, or an array of strings. An array representation of a header list must have an even length or an `InvalidArgumentError` will be thrown. + +Keys are lowercase and values are not modified. + +Response headers will derive a `host` from the `url` of the [Client](Client.md#class-client) instance if no `host` header was previously specified. + +### Example 1 - Object + +```js +{ + 'content-length': '123', + 'content-type': 'text/plain', + connection: 'keep-alive', + host: 'mysite.com', + accept: '*/*' +} +``` + +### Example 2 - Array + +```js +[ + 'content-length', '123', + 'content-type', 'text/plain', + 'connection', 'keep-alive', + 'host', 'mysite.com', + 'accept', '*/*' +] +``` diff --git a/node_modules/undici/docs/api/Errors.md b/node_modules/undici/docs/api/Errors.md new file mode 100644 index 0000000..917e45d --- /dev/null +++ b/node_modules/undici/docs/api/Errors.md @@ -0,0 +1,47 @@ +# Errors + +Undici exposes a variety of error objects that you can use to enhance your error handling. +You can find all the error objects inside the `errors` key. + +```js +import { errors } from 'undici' +``` + +| Error | Error Codes | Description | +| ------------------------------------ | ------------------------------------- | ------------------------------------------------------------------------- | +| `UndiciError` | `UND_ERR` | all errors below are extended from `UndiciError`. | +| `ConnectTimeoutError` | `UND_ERR_CONNECT_TIMEOUT` | socket is destroyed due to connect timeout. | +| `HeadersTimeoutError` | `UND_ERR_HEADERS_TIMEOUT` | socket is destroyed due to headers timeout. | +| `HeadersOverflowError` | `UND_ERR_HEADERS_OVERFLOW` | socket is destroyed due to headers' max size being exceeded. | +| `BodyTimeoutError` | `UND_ERR_BODY_TIMEOUT` | socket is destroyed due to body timeout. | +| `ResponseStatusCodeError` | `UND_ERR_RESPONSE_STATUS_CODE` | an error is thrown when `throwOnError` is `true` for status codes >= 400. | +| `InvalidArgumentError` | `UND_ERR_INVALID_ARG` | passed an invalid argument. | +| `InvalidReturnValueError` | `UND_ERR_INVALID_RETURN_VALUE` | returned an invalid value. | +| `RequestAbortedError` | `UND_ERR_ABORTED` | the request has been aborted by the user | +| `ClientDestroyedError` | `UND_ERR_DESTROYED` | trying to use a destroyed client. | +| `ClientClosedError` | `UND_ERR_CLOSED` | trying to use a closed client. | +| `SocketError` | `UND_ERR_SOCKET` | there is an error with the socket. | +| `NotSupportedError` | `UND_ERR_NOT_SUPPORTED` | encountered unsupported functionality. | +| `RequestContentLengthMismatchError` | `UND_ERR_REQ_CONTENT_LENGTH_MISMATCH` | request body does not match content-length header | +| `ResponseContentLengthMismatchError` | `UND_ERR_RES_CONTENT_LENGTH_MISMATCH` | response body does not match content-length header | +| `InformationalError` | `UND_ERR_INFO` | expected error with reason | +| `ResponseExceededMaxSizeError` | `UND_ERR_RES_EXCEEDED_MAX_SIZE` | response body exceed the max size allowed | + +### `SocketError` + +The `SocketError` has a `.socket` property which holds socket metadata: + +```ts +interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number +} +``` + +Be aware that in some cases the `.socket` property can be `null`. diff --git a/node_modules/undici/docs/api/Fetch.md b/node_modules/undici/docs/api/Fetch.md new file mode 100644 index 0000000..b5a6242 --- /dev/null +++ b/node_modules/undici/docs/api/Fetch.md @@ -0,0 +1,27 @@ +# Fetch + +Undici exposes a fetch() method starts the process of fetching a resource from the network. + +Documentation and examples can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/fetch). + +## File + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/File) + +In Node versions v18.13.0 and above and v19.2.0 and above, undici will default to using Node's [File](https://nodejs.org/api/buffer.html#class-file) class. In versions where it's not available, it will default to the undici one. + +## FormData + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/FormData) + +## Response + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Response) + +## Request + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Request) + +## Header + +This API is implemented as per the standard, you can find documentation on [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Headers) diff --git a/node_modules/undici/docs/api/MockAgent.md b/node_modules/undici/docs/api/MockAgent.md new file mode 100644 index 0000000..85ae690 --- /dev/null +++ b/node_modules/undici/docs/api/MockAgent.md @@ -0,0 +1,540 @@ +# Class: MockAgent + +Extends: `undici.Dispatcher` + +A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. + +## `new MockAgent([options])` + +Arguments: + +* **options** `MockAgentOptions` (optional) - It extends the `Agent` options. + +Returns: `MockAgent` + +### Parameter: `MockAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **agent** `Agent` (optional) - Default: `new Agent([options])` - a custom agent encapsulated by the MockAgent. + +### Example - Basic MockAgent instantiation + +This will instantiate the MockAgent. It will not do anything until registered as the agent to use with requests and mock interceptions are added. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +``` + +### Example - Basic MockAgent instantiation with custom agent + +```js +import { Agent, MockAgent } from 'undici' + +const agent = new Agent() + +const mockAgent = new MockAgent({ agent }) +``` + +## Instance Methods + +### `MockAgent.get(origin)` + +This method creates and retrieves MockPool or MockClient instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. + +For subsequent `MockAgent.get` calls on the same origin, the same mock instance will be returned. + +Arguments: + +* **origin** `string | RegExp | (value) => boolean` - a matcher for the pool origin to be retrieved from the MockAgent. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Returns: `MockClient | MockPool`. + +| `MockAgentOptions` | Mock instance returned | +| -------------------- | ---------------------- | +| `connections === 1` | `MockClient` | +| `connections` > `1` | `MockPool` | + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock agent dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock pool dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockPool }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked Request with local mock client dispatcher + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: mockClient }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') +mockPool.intercept({ path: '/hello'}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` +#### Example - Mock different requests within the same file +```js +const { MockAgent, setGlobalDispatcher } = require('undici'); +const agent = new MockAgent(); +agent.disableNetConnect(); +setGlobalDispatcher(agent); +describe('Test', () => { + it('200', async () => { + const mockAgent = agent.get('http://test.com'); + // your test + }); + it('200', async () => { + const mockAgent = agent.get('http://testing.com'); + // your test + }); +}); +``` + +#### Example - Mocked request with query body, headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2' +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2' +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request with origin regex + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get(new RegExp('http://localhost:3000')) +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with origin function + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get((origin) => origin === 'http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.close()` + +Closes the mock agent and waits for registered mock pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +await mockAgent.close() +``` + +### `MockAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `MockAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockAgent request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockAgent.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +### `MockAgent.deactivate()` + +This method disables mocking in MockAgent. + +Returns: `void` + +#### Example - Deactivate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +``` + +### `MockAgent.activate()` + +This method enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. + +Returns: `void` + +#### Example - Activate Mocking + +```js +import { MockAgent, setGlobalDispatcher } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.deactivate() +// No mocking will occur + +// Later +mockAgent.activate() +``` + +### `MockAgent.enableNetConnect([host])` + +When requests are not matched in a MockAgent intercept, a real HTTP request is attempted. We can control this further through the use of `enableNetConnect`. This is achieved by defining host matchers so only matching requests will be attempted. + +When using a string, it should only include the **hostname and optionally, the port**. In addition, calling this method multiple times with a string will allow all HTTP requests that match these values. + +Arguments: + +* **host** `string | RegExp | (value) => boolean` - (optional) + +Returns: `void` + +#### Example - Allow all non-matching urls to be dispatched in a real HTTP request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect() + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host string to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect('example-1.com') +mockAgent.enableNetConnect('example-2.com:8080') + +await request('http://example-1.com') +// A real request is made + +await request('http://example-2.com:8080') +// A real request is made + +await request('http://example-3.com') +// Will throw +``` + +#### Example - Allow requests matching a host regex to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect(new RegExp('example.com')) + +await request('http://example.com') +// A real request is made +``` + +#### Example - Allow requests matching a host function to make real requests + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +mockAgent.enableNetConnect((value) => value === 'example.com') + +await request('http://example.com') +// A real request is made +``` + +### `MockAgent.disableNetConnect()` + +This method causes all requests to throw when requests are not matched in a MockAgent intercept. + +Returns: `void` + +#### Example - Disable all non-matching requests by throwing an error for each + +```js +import { MockAgent, request } from 'undici' + +const mockAgent = new MockAgent() + +mockAgent.disableNetConnect() + +await request('http://example.com') +// Will throw +``` + +### `MockAgent.pendingInterceptors()` + +This method returns any pending interceptors registered on a mock agent. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +Returns: `PendingInterceptor[]` (where `PendingInterceptor` is a `MockDispatch` with an additional `origin: string`) + +#### Example - List all pending inteceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +const pendingInterceptors = agent.pendingInterceptors() +// Returns [ +// { +// timesInvoked: 0, +// times: 1, +// persist: false, +// consumed: false, +// pending: true, +// path: '/', +// method: 'GET', +// body: undefined, +// headers: undefined, +// data: { +// error: null, +// statusCode: 200, +// data: '', +// headers: {}, +// trailers: {} +// }, +// origin: 'https://example.com' +// } +// ] +``` + +### `MockAgent.assertNoPendingInterceptors([options])` + +This method throws if the mock agent has any pending interceptors. A pending interceptor meets one of the following criteria: + +- Is registered with neither `.times()` nor `.persist()`, and has not been invoked; +- Is persistent (i.e., registered with `.persist()`) and has not been invoked; +- Is registered with `.times()` and has not been invoked `` of times. + +#### Example - Check that there are no pending interceptors + +```js +const agent = new MockAgent() +agent.disableNetConnect() + +agent + .get('https://example.com') + .intercept({ method: 'GET', path: '/' }) + .reply(200) + +agent.assertNoPendingInterceptors() +// Throws an UndiciError with the following message: +// +// 1 interceptor is pending: +// +// ┌─────────┬────────┬───────────────────────┬──────┬─────────────┬────────────┬─────────────┬───────────┐ +// │ (index) │ Method │ Origin │ Path │ Status code │ Persistent │ Invocations │ Remaining │ +// ├─────────┼────────┼───────────────────────┼──────┼─────────────┼────────────┼─────────────┼───────────┤ +// │ 0 │ 'GET' │ 'https://example.com' │ '/' │ 200 │ '❌' │ 0 │ 1 │ +// └─────────┴────────┴───────────────────────┴──────┴─────────────┴────────────┴─────────────┴───────────┘ +``` diff --git a/node_modules/undici/docs/api/MockClient.md b/node_modules/undici/docs/api/MockClient.md new file mode 100644 index 0000000..ac54691 --- /dev/null +++ b/node_modules/undici/docs/api/MockClient.md @@ -0,0 +1,77 @@ +# Class: MockClient + +Extends: `undici.Client` + +A mock client class that implements the same api as [MockPool](MockPool.md). + +## `new MockClient(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockClientOptions` - It extends the `Client` options. + +Returns: `MockClient` + +### Parameter: `MockClientOptions` + +Extends: `ClientOptions` + +* **agent** `Agent` - the agent to associate this MockClient with. + +### Example - Basic MockClient instantiation + +We can use MockAgent to instantiate a MockClient ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +// Connections must be set to 1 to return a MockClient instance +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockClient.intercept(options)` + +Implements: [`MockPool.intercept(options)`](MockPool.md#mockpoolinterceptoptions) + +### `MockClient.close()` + +Implements: [`MockPool.close()`](MockPool.md#mockpoolclose) + +### `MockClient.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockClient.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockClient request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent({ connections: 1 }) + +const mockClient = mockAgent.get('http://localhost:3000') +mockClient.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await mockClient.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/MockErrors.md b/node_modules/undici/docs/api/MockErrors.md new file mode 100644 index 0000000..c1aa3db --- /dev/null +++ b/node_modules/undici/docs/api/MockErrors.md @@ -0,0 +1,12 @@ +# MockErrors + +Undici exposes a variety of mock error objects that you can use to enhance your mock error handling. +You can find all the mock error objects inside the `mockErrors` key. + +```js +import { mockErrors } from 'undici' +``` + +| Mock Error | Mock Error Codes | Description | +| --------------------- | ------------------------------- | ---------------------------------------------------------- | +| `MockNotMatchedError` | `UND_MOCK_ERR_MOCK_NOT_MATCHED` | The request does not match any registered mock dispatches. | diff --git a/node_modules/undici/docs/api/MockPool.md b/node_modules/undici/docs/api/MockPool.md new file mode 100644 index 0000000..96a986f --- /dev/null +++ b/node_modules/undici/docs/api/MockPool.md @@ -0,0 +1,547 @@ +# Class: MockPool + +Extends: `undici.Pool` + +A mock Pool class that implements the Pool API and is used by MockAgent to intercept real requests and return mocked responses. + +## `new MockPool(origin, [options])` + +Arguments: + +* **origin** `string` - It should only include the **protocol, hostname, and port**. +* **options** `MockPoolOptions` - It extends the `Pool` options. + +Returns: `MockPool` + +### Parameter: `MockPoolOptions` + +Extends: `PoolOptions` + +* **agent** `Agent` - the agent to associate this MockPool with. + +### Example - Basic MockPool instantiation + +We can use MockAgent to instantiate a MockPool ready to be used to intercept specified requests. It will not do anything until registered as the agent to use and any mock request are registered. + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +``` + +## Instance Methods + +### `MockPool.intercept(options)` + +This method defines the interception rules for matching against requests for a MockPool or MockPool. We can intercept multiple times on a single instance, but each intercept is only used once. For example if you expect to make 2 requests inside a test, you need to call `intercept()` twice. Assuming you use `disableNetConnect()` you will get `MockNotMatchedError` on the second request when you only call `intercept()` once. + +When defining interception rules, all the rules must pass for a request to be intercepted. If a request is not intercepted, a real request will be attempted. + +| Matcher type | Condition to pass | +|:------------:| -------------------------- | +| `string` | Exact match against string | +| `RegExp` | Regex must pass | +| `Function` | Function must return true | + +Arguments: + +* **options** `MockPoolInterceptOptions` - Interception options. + +Returns: `MockInterceptor` corresponding to the input options. + +### Parameter: `MockPoolInterceptOptions` + +* **path** `string | RegExp | (path: string) => boolean` - a matcher for the HTTP request path. When a `RegExp` or callback is used, it will match against the request path including all query parameters in alphabetical order. When a `string` is provided, the query parameters can be conveniently specified through the `MockPoolInterceptOptions.query` setting. +* **method** `string | RegExp | (method: string) => boolean` - (optional) - a matcher for the HTTP request method. Defaults to `GET`. +* **body** `string | RegExp | (body: string) => boolean` - (optional) - a matcher for the HTTP request body. +* **headers** `Record boolean`> - (optional) - a matcher for the HTTP request headers. To be intercepted, a request must match all defined headers. Extra headers not defined here may (or may not) be included in the request and do not affect the interception in any way. +* **query** `Record | null` - (optional) - a matcher for the HTTP request query string params. Only applies when a `string` was provided for `MockPoolInterceptOptions.path`. + +### Return: `MockInterceptor` + +We can define the behaviour of an intercepted request with the following options. + +* **reply** `(statusCode: number, replyData: string | Buffer | object | MockInterceptor.MockResponseDataHandler, responseOptions?: MockResponseOptions) => MockScope` - define a reply for a matching request. You can define the replyData as a callback to read incoming request data. Default for `responseOptions` is `{}`. +* **reply** `(callback: MockInterceptor.MockReplyOptionsCallback) => MockScope` - define a reply for a matching request, allowing dynamic mocking of all reply options rather than just the data. +* **replyWithError** `(error: Error) => MockScope` - define an error for a matching request to throw. +* **defaultReplyHeaders** `(headers: Record) => MockInterceptor` - define default headers to be included in subsequent replies. These are in addition to headers on a specific reply. +* **defaultReplyTrailers** `(trailers: Record) => MockInterceptor` - define default trailers to be included in subsequent replies. These are in addition to trailers on a specific reply. +* **replyContentLength** `() => MockInterceptor` - define automatically calculated `content-length` headers to be included in subsequent replies. + +The reply data of an intercepted request may either be a string, buffer, or JavaScript object. Objects are converted to JSON while strings and buffers are sent as-is. + +By default, `reply` and `replyWithError` define the behaviour for the first matching request only. Subsequent requests will not be affected (this can be changed using the returned `MockScope`). + +### Parameter: `MockResponseOptions` + +* **headers** `Record` - headers to be included on the mocked reply. +* **trailers** `Record` - trailers to be included on the mocked reply. + +### Return: `MockScope` + +A `MockScope` is associated with a single `MockInterceptor`. With this, we can configure the default behaviour of a intercepted reply. + +* **delay** `(waitInMs: number) => MockScope` - delay the associated reply by a set amount in ms. +* **persist** `() => MockScope` - any matching request will always reply with the defined response indefinitely. +* **times** `(repeatTimes: number) => MockScope` - any matching request will reply with the defined response a fixed amount of times. This is overridden by **persist**. + +#### Example - Basic Mocked Request + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +// MockPool +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ path: '/foo' }).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request using reply data callbacks + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, ({ headers }) => ({ message: headers.get('message') })) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Mocked request using reply options callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/echo', + method: 'GET', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(({ headers }) => ({ statusCode: 200, data: { message: headers.get('message') }}))) + +const { statusCode, body, headers } = await request('http://localhost:3000', { + headers: { + message: 'hello world!' + } +}) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // { "message":"hello world!" } +} +``` + +#### Example - Basic Mocked requests with multiple intercepts + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo') + +mockPool.intercept({ + path: '/hello', + method: 'GET', +}).reply(200, 'hello') + +const result1 = await request('http://localhost:3000/foo') + +console.log('response received', result1.statusCode) // response received 200 + +for await (const data of result1.body) { + console.log('data', data.toString('utf8')) // data foo +} + +const result2 = await request('http://localhost:3000/hello') + +console.log('response received', result2.statusCode) // response received 200 + +for await (const data of result2.body) { + console.log('data', data.toString('utf8')) // data hello +} +``` + +#### Example - Mocked request with query body, request headers and response headers and trailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo?hello=there&see=ya', + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + 'User-Agent': 'undici', + Host: 'example.com' + } +}).reply(200, { foo: 'bar' }, { + headers: { 'content-type': 'application/json' }, + trailers: { 'Content-MD5': 'test' } +}) + +const { + statusCode, + headers, + trailers, + body +} = await request('http://localhost:3000/foo?hello=there&see=ya', { + method: 'POST', + body: 'form1=data1&form2=data2', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } + }) + +console.log('response received', statusCode) // response received 200 +console.log('headers', headers) // { 'content-type': 'application/json' } + +for await (const data of body) { + console.log('data', data.toString('utf8')) // '{"foo":"bar"}' +} + +console.log('trailers', trailers) // { 'content-md5': 'test' } +``` + +#### Example - Mocked request using different matchers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: /^GET$/, + body: (value) => value === 'form=data', + headers: { + 'User-Agent': 'undici', + Host: /^example.com$/ + } +}).reply(200, 'foo') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { + method: 'GET', + body: 'form=data', + headers: { + foo: 'bar', + 'User-Agent': 'undici', + Host: 'example.com' + } +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Mocked request with reply with a defined error + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyWithError(new Error('kaboom')) + +try { + await request('http://localhost:3000/foo', { + method: 'GET' + }) +} catch (error) { + console.error(error) // Error: kaboom +} +``` + +#### Example - Mocked request with defaultReplyHeaders + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyHeaders({ foo: 'bar' }) + .reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { foo: 'bar' } +``` + +#### Example - Mocked request with defaultReplyTrailers + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).defaultReplyTrailers({ foo: 'bar' }) + .reply(200, 'foo') + +const { trailers } = await request('http://localhost:3000/foo') + +console.log('trailers', trailers) // trailers { foo: 'bar' } +``` + +#### Example - Mocked request with automatic content-length calculation + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, 'foo') + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '3' } +``` + +#### Example - Mocked request with automatic content-length calculation on an object + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).replyContentLength().reply(200, { foo: 'bar' }) + +const { headers } = await request('http://localhost:3000/foo') + +console.log('headers', headers) // headers { 'content-length': '13' } +``` + +#### Example - Mocked request with persist enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').persist() + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +// Etc +``` + +#### Example - Mocked request with times enabled + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +mockPool.intercept({ + path: '/foo', + method: 'GET' +}).reply(200, 'foo').times(2) + +const result1 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result2 = await request('http://localhost:3000/foo') +// Will match and return mocked data + +const result3 = await request('http://localhost:3000/foo') +// Will not match and make attempt a real request +``` + +#### Example - Mocked request with path callback + +```js +import { MockAgent, setGlobalDispatcher, request } from 'undici' +import querystring from 'querystring' + +const mockAgent = new MockAgent() +setGlobalDispatcher(mockAgent) + +const mockPool = mockAgent.get('http://localhost:3000') + +const matchPath = requestPath => { + const [pathname, search] = requestPath.split('?') + const requestQuery = querystring.parse(search) + + if (!pathname.startsWith('/foo')) { + return false + } + + if (!Object.keys(requestQuery).includes('foo') || requestQuery.foo !== 'bar') { + return false + } + + return true +} + +mockPool.intercept({ + path: matchPath, + method: 'GET' +}).reply(200, 'foo') + +const result = await request('http://localhost:3000/foo?foo=bar') +// Will match and return mocked data +``` + +### `MockPool.close()` + +Closes the mock pool and de-registers from associated MockAgent. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() +const mockPool = mockAgent.get('http://localhost:3000') + +await mockPool.close() +``` + +### `MockPool.dispatch(options, handlers)` + +Implements [`Dispatcher.dispatch(options, handlers)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `MockPool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +#### Example - MockPool request + +```js +import { MockAgent } from 'undici' + +const mockAgent = new MockAgent() + +const mockPool = mockAgent.get('http://localhost:3000') +mockPool.intercept({ + path: '/foo', + method: 'GET', +}).reply(200, 'foo') + +const { + statusCode, + body +} = await mockPool.request({ + origin: 'http://localhost:3000', + path: '/foo', + method: 'GET' +}) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` diff --git a/node_modules/undici/docs/api/Pool.md b/node_modules/undici/docs/api/Pool.md new file mode 100644 index 0000000..8fcabac --- /dev/null +++ b/node_modules/undici/docs/api/Pool.md @@ -0,0 +1,84 @@ +# Class: Pool + +Extends: `undici.Dispatcher` + +A pool of [Client](Client.md) instances connected to the same upstream target. + +Requests are not guaranteed to be dispatched in order of invocation. + +## `new Pool(url[, options])` + +Arguments: + +* **url** `URL | string` - It should only include the **protocol, hostname, and port**. +* **options** `PoolOptions` (optional) + +### Parameter: `PoolOptions` + +Extends: [`ClientOptions`](Client.md#parameter-clientoptions) + +* **factory** `(origin: URL, opts: Object) => Dispatcher` - Default: `(origin, opts) => new Client(origin, opts)` +* **connections** `number | null` (optional) - Default: `null` - The number of `Client` instances to create. When set to `null`, the `Pool` instance will create an unlimited amount of `Client` instances. +* **interceptors** `{ Pool: DispatchInterceptor[] } }` - Default: `{ Pool: [] }` - A list of interceptors that are applied to the dispatch method. Additional logic can be applied (such as, but not limited to: 302 status code handling, authentication, cookies, compression and caching). + +## Instance Properties + +### `Pool.closed` + +Implements [Client.closed](Client.md#clientclosed) + +### `Pool.destroyed` + +Implements [Client.destroyed](Client.md#clientdestroyed) + +### `Pool.stats` + +Returns [`PoolStats`](PoolStats.md) instance for this pool. + +## Instance Methods + +### `Pool.close([callback])` + +Implements [`Dispatcher.close([callback])`](Dispatcher.md#dispatcherclosecallback-promise). + +### `Pool.destroy([error, callback])` + +Implements [`Dispatcher.destroy([error, callback])`](Dispatcher.md#dispatcherdestroyerror-callback-promise). + +### `Pool.connect(options[, callback])` + +See [`Dispatcher.connect(options[, callback])`](Dispatcher.md#dispatcherconnectoptions-callback). + +### `Pool.dispatch(options, handler)` + +Implements [`Dispatcher.dispatch(options, handler)`](Dispatcher.md#dispatcherdispatchoptions-handler). + +### `Pool.pipeline(options, handler)` + +See [`Dispatcher.pipeline(options, handler)`](Dispatcher.md#dispatcherpipelineoptions-handler). + +### `Pool.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). + +### `Pool.stream(options, factory[, callback])` + +See [`Dispatcher.stream(options, factory[, callback])`](Dispatcher.md#dispatcherstreamoptions-factory-callback). + +### `Pool.upgrade(options[, callback])` + +See [`Dispatcher.upgrade(options[, callback])`](Dispatcher.md#dispatcherupgradeoptions-callback). + +## Instance Events + +### Event: `'connect'` + +See [Dispatcher Event: `'connect'`](Dispatcher.md#event-connect). + +### Event: `'disconnect'` + +See [Dispatcher Event: `'disconnect'`](Dispatcher.md#event-disconnect). + +### Event: `'drain'` + +See [Dispatcher Event: `'drain'`](Dispatcher.md#event-drain). diff --git a/node_modules/undici/docs/api/PoolStats.md b/node_modules/undici/docs/api/PoolStats.md new file mode 100644 index 0000000..16b6dc2 --- /dev/null +++ b/node_modules/undici/docs/api/PoolStats.md @@ -0,0 +1,35 @@ +# Class: PoolStats + +Aggregate stats for a [Pool](Pool.md) or [BalancedPool](BalancedPool.md). + +## `new PoolStats(pool)` + +Arguments: + +* **pool** `Pool` - Pool or BalancedPool from which to return stats. + +## Instance Properties + +### `PoolStats.connected` + +Number of open socket connections in this pool. + +### `PoolStats.free` + +Number of open socket connections in this pool that do not have an active request. + +### `PoolStats.pending` + +Number of pending requests across all clients in this pool. + +### `PoolStats.queued` + +Number of queued requests across all clients in this pool. + +### `PoolStats.running` + +Number of currently active requests across all clients in this pool. + +### `PoolStats.size` + +Number of active, pending, or queued requests across all clients in this pool. diff --git a/node_modules/undici/docs/api/ProxyAgent.md b/node_modules/undici/docs/api/ProxyAgent.md new file mode 100644 index 0000000..cebfe68 --- /dev/null +++ b/node_modules/undici/docs/api/ProxyAgent.md @@ -0,0 +1,126 @@ +# Class: ProxyAgent + +Extends: `undici.Dispatcher` + +A Proxy Agent class that implements the Agent API. It allows the connection through proxy in a simple way. + +## `new ProxyAgent([options])` + +Arguments: + +* **options** `ProxyAgentOptions` (required) - It extends the `Agent` options. + +Returns: `ProxyAgent` + +### Parameter: `ProxyAgentOptions` + +Extends: [`AgentOptions`](Agent.md#parameter-agentoptions) + +* **uri** `string` (required) - It can be passed either by a string or a object containing `uri` as string. +* **token** `string` (optional) - It can be passed by a string of token for authentication. +* **auth** `string` (**deprecated**) - Use token. +* **clientFactory** `(origin: URL, opts: Object) => Dispatcher` (optional) - Default: `(origin, opts) => new Pool(origin, opts)` +* **requestTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the request. See [TLS](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). +* **proxyTls** `BuildOptions` (optional) - Options object passed when creating the underlying socket via the connector builder for the proxy server. See [TLS](https://nodejs.org/api/tls.html#tlsconnectoptions-callback). + +Examples: + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +// or +const proxyAgent = new ProxyAgent({ uri: 'my.proxy.server' }) +``` + +#### Example - Basic ProxyAgent instantiation + +This will instantiate the ProxyAgent. It will not do anything until registered as the agent to use with requests. + +```js +import { ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +``` + +#### Example - Basic Proxy Request with global agent dispatcher + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +const { statusCode, body } = await request('http://localhost:3000/foo') + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with local agent dispatcher + +```js +import { ProxyAgent, request } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const { + statusCode, + body +} = await request('http://localhost:3000/foo', { dispatcher: proxyAgent }) + +console.log('response received', statusCode) // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')) // data foo +} +``` + +#### Example - Basic Proxy Request with authentication + +```js +import { setGlobalDispatcher, request, ProxyAgent } from 'undici'; + +const proxyAgent = new ProxyAgent({ + uri: 'my.proxy.server', + // token: 'Bearer xxxx' + token: `Basic ${Buffer.from('username:password').toString('base64')}` +}); +setGlobalDispatcher(proxyAgent); + +const { statusCode, body } = await request('http://localhost:3000/foo'); + +console.log('response received', statusCode); // response received 200 + +for await (const data of body) { + console.log('data', data.toString('utf8')); // data foo +} +``` + +### `ProxyAgent.close()` + +Closes the proxy agent and waits for registered pools and clients to also close before resolving. + +Returns: `Promise` + +#### Example - clean up after tests are complete + +```js +import { ProxyAgent, setGlobalDispatcher } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') +setGlobalDispatcher(proxyAgent) + +await proxyAgent.close() +``` + +### `ProxyAgent.dispatch(options, handlers)` + +Implements [`Agent.dispatch(options, handlers)`](Agent.md#parameter-agentdispatchoptions). + +### `ProxyAgent.request(options[, callback])` + +See [`Dispatcher.request(options [, callback])`](Dispatcher.md#dispatcherrequestoptions-callback). diff --git a/node_modules/undici/docs/api/RetryHandler.md b/node_modules/undici/docs/api/RetryHandler.md new file mode 100644 index 0000000..2323ce4 --- /dev/null +++ b/node_modules/undici/docs/api/RetryHandler.md @@ -0,0 +1,108 @@ +# Class: RetryHandler + +Extends: `undici.DispatcherHandlers` + +A handler class that implements the retry logic for a request. + +## `new RetryHandler(dispatchOptions, retryHandlers, [retryOptions])` + +Arguments: + +- **options** `Dispatch.DispatchOptions & RetryOptions` (required) - It is an intersection of `Dispatcher.DispatchOptions` and `RetryOptions`. +- **retryHandlers** `RetryHandlers` (required) - Object containing the `dispatch` to be used on every retry, and `handler` for handling the `dispatch` lifecycle. + +Returns: `retryHandler` + +### Parameter: `Dispatch.DispatchOptions & RetryOptions` + +Extends: [`Dispatch.DispatchOptions`](Dispatcher.md#parameter-dispatchoptions). + +#### `RetryOptions` + +- **retry** `(err: Error, context: RetryContext, callback: (err?: Error | null) => void) => void` (optional) - Function to be called after every retry. It should pass error if no more retries should be performed. +- **maxRetries** `number` (optional) - Maximum number of retries. Default: `5` +- **maxTimeout** `number` (optional) - Maximum number of milliseconds to wait before retrying. Default: `30000` (30 seconds) +- **minTimeout** `number` (optional) - Minimum number of milliseconds to wait before retrying. Default: `500` (half a second) +- **timeoutFactor** `number` (optional) - Factor to multiply the timeout by for each retry attempt. Default: `2` +- **retryAfter** `boolean` (optional) - It enables automatic retry after the `Retry-After` header is received. Default: `true` +- +- **methods** `string[]` (optional) - Array of HTTP methods to retry. Default: `['GET', 'PUT', 'HEAD', 'OPTIONS', 'DELETE']` +- **statusCodes** `number[]` (optional) - Array of HTTP status codes to retry. Default: `[429, 500, 502, 503, 504]` +- **errorCodes** `string[]` (optional) - Array of Error codes to retry. Default: `['ECONNRESET', 'ECONNREFUSED', 'ENOTFOUND', 'ENETDOWN','ENETUNREACH', 'EHOSTDOWN', + +**`RetryContext`** + +- `state`: `RetryState` - Current retry state. It can be mutated. +- `opts`: `Dispatch.DispatchOptions & RetryOptions` - Options passed to the retry handler. + +### Parameter `RetryHandlers` + +- **dispatch** `(options: Dispatch.DispatchOptions, handlers: Dispatch.DispatchHandlers) => Promise` (required) - Dispatch function to be called after every retry. +- **handler** Extends [`Dispatch.DispatchHandlers`](Dispatcher.md#dispatcherdispatchoptions-handler) (required) - Handler function to be called after the request is successful or the retries are exhausted. + +Examples: + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const chunks = []; +const handler = new RetryHandler( + { + ...dispatchOptions, + retryOptions: { + // custom retry function + retry: function (err, state, callback) { + counter++; + + if (err.code && err.code === "UND_ERR_DESTROYED") { + callback(err); + return; + } + + if (err.statusCode === 206) { + callback(err); + return; + } + + setTimeout(() => callback(null), 1000); + }, + }, + }, + { + dispatch: (...args) => { + return client.dispatch(...args); + }, + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) { + // do something with headers + }, + onData(chunk) { + chunks.push(chunk); + return true; + }, + onComplete() {}, + onError() { + // handle error properly + }, + }, + } +); +``` + +#### Example - Basic RetryHandler with defaults + +```js +const client = new Client(`http://localhost:${server.address().port}`); +const handler = new RetryHandler(dispatchOptions, { + dispatch: client.dispatch.bind(client), + handler: { + onConnect() {}, + onBodySent() {}, + onHeaders(status, _rawHeaders, resume, _statusMessage) {}, + onData(chunk) {}, + onComplete() {}, + onError(err) {}, + }, +}); +``` diff --git a/node_modules/undici/docs/api/WebSocket.md b/node_modules/undici/docs/api/WebSocket.md new file mode 100644 index 0000000..9d374f4 --- /dev/null +++ b/node_modules/undici/docs/api/WebSocket.md @@ -0,0 +1,43 @@ +# Class: WebSocket + +> ⚠️ Warning: the WebSocket API is experimental. + +Extends: [`EventTarget`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget) + +The WebSocket object provides a way to manage a WebSocket connection to a server, allowing bidirectional communication. The API follows the [WebSocket spec](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) and [RFC 6455](https://datatracker.ietf.org/doc/html/rfc6455). + +## `new WebSocket(url[, protocol])` + +Arguments: + +* **url** `URL | string` - The url's protocol *must* be `ws` or `wss`. +* **protocol** `string | string[] | WebSocketInit` (optional) - Subprotocol(s) to request the server use, or a [`Dispatcher`](./Dispatcher.md). + +### Example: + +This example will not work in browsers or other platforms that don't allow passing an object. + +```mjs +import { WebSocket, ProxyAgent } from 'undici' + +const proxyAgent = new ProxyAgent('my.proxy.server') + +const ws = new WebSocket('wss://echo.websocket.events', { + dispatcher: proxyAgent, + protocols: ['echo', 'chat'] +}) +``` + +If you do not need a custom Dispatcher, it's recommended to use the following pattern: + +```mjs +import { WebSocket } from 'undici' + +const ws = new WebSocket('wss://echo.websocket.events', ['echo', 'chat']) +``` + +## Read More + +- [MDN - WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) +- [The WebSocket Specification](https://www.rfc-editor.org/rfc/rfc6455) +- [The WHATWG WebSocket Specification](https://websockets.spec.whatwg.org/) diff --git a/node_modules/undici/docs/api/api-lifecycle.md b/node_modules/undici/docs/api/api-lifecycle.md new file mode 100644 index 0000000..d158126 --- /dev/null +++ b/node_modules/undici/docs/api/api-lifecycle.md @@ -0,0 +1,62 @@ +# Client Lifecycle + +An Undici [Client](Client.md) can be best described as a state machine. The following list is a summary of the various state transitions the `Client` will go through in its lifecycle. This document also contains detailed breakdowns of each state. + +> This diagram is not a perfect representation of the undici Client. Since the Client class is not actually implemented as a state-machine, actual execution may deviate slightly from what is described below. Consider this as a general resource for understanding the inner workings of the Undici client rather than some kind of formal specification. + +## State Transition Overview + +* A `Client` begins in the **idle** state with no socket connection and no requests in queue. + * The *connect* event transitions the `Client` to the **pending** state where requests can be queued prior to processing. + * The *close* and *destroy* events transition the `Client` to the **destroyed** state. Since there are no requests in the queue, the *close* event immediately transitions to the **destroyed** state. +* The **pending** state indicates the underlying socket connection has been successfully established and requests are queueing. + * The *process* event transitions the `Client` to the **processing** state where requests are processed. + * If requests are queued, the *close* event transitions to the **processing** state; otherwise, it transitions to the **destroyed** state. + * The *destroy* event transitions to the **destroyed** state. +* The **processing** state initializes to the **processing.running** state. + * If the current request requires draining, the *needDrain* event transitions the `Client` into the **processing.busy** state which will return to the **processing.running** state with the *drainComplete* event. + * After all queued requests are completed, the *keepalive* event transitions the `Client` back to the **pending** state. If no requests are queued during the timeout, the **close** event transitions the `Client` to the **destroyed** state. + * If the *close* event is fired while the `Client` still has queued requests, the `Client` transitions to the **process.closing** state where it will complete all existing requests before firing the *done* event. + * The *done* event gracefully transitions the `Client` to the **destroyed** state. + * At any point in time, the *destroy* event will transition the `Client` from the **processing** state to the **destroyed** state, destroying any queued requests. +* The **destroyed** state is a final state and the `Client` is no longer functional. + +![A state diagram representing an Undici Client instance](../assets/lifecycle-diagram.png) + +> The diagram was generated using Mermaid.js Live Editor. Modify the state diagram [here](https://mermaid-js.github.io/mermaid-live-editor/#/edit/eyJjb2RlIjoic3RhdGVEaWFncmFtLXYyXG4gICAgWypdIC0tPiBpZGxlXG4gICAgaWRsZSAtLT4gcGVuZGluZyA6IGNvbm5lY3RcbiAgICBpZGxlIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95L2Nsb3NlXG4gICAgXG4gICAgcGVuZGluZyAtLT4gaWRsZSA6IHRpbWVvdXRcbiAgICBwZW5kaW5nIC0tPiBkZXN0cm95ZWQgOiBkZXN0cm95XG5cbiAgICBzdGF0ZSBjbG9zZV9mb3JrIDw8Zm9yaz4-XG4gICAgcGVuZGluZyAtLT4gY2xvc2VfZm9yayA6IGNsb3NlXG4gICAgY2xvc2VfZm9yayAtLT4gcHJvY2Vzc2luZ1xuICAgIGNsb3NlX2ZvcmsgLS0-IGRlc3Ryb3llZFxuXG4gICAgcGVuZGluZyAtLT4gcHJvY2Vzc2luZyA6IHByb2Nlc3NcblxuICAgIHByb2Nlc3NpbmcgLS0-IHBlbmRpbmcgOiBrZWVwYWxpdmVcbiAgICBwcm9jZXNzaW5nIC0tPiBkZXN0cm95ZWQgOiBkb25lXG4gICAgcHJvY2Vzc2luZyAtLT4gZGVzdHJveWVkIDogZGVzdHJveVxuXG4gICAgc3RhdGUgcHJvY2Vzc2luZyB7XG4gICAgICAgIHJ1bm5pbmcgLS0-IGJ1c3kgOiBuZWVkRHJhaW5cbiAgICAgICAgYnVzeSAtLT4gcnVubmluZyA6IGRyYWluQ29tcGxldGVcbiAgICAgICAgcnVubmluZyAtLT4gWypdIDoga2VlcGFsaXZlXG4gICAgICAgIHJ1bm5pbmcgLS0-IGNsb3NpbmcgOiBjbG9zZVxuICAgICAgICBjbG9zaW5nIC0tPiBbKl0gOiBkb25lXG4gICAgICAgIFsqXSAtLT4gcnVubmluZ1xuICAgIH1cbiAgICAiLCJtZXJtYWlkIjp7InRoZW1lIjoiYmFzZSJ9LCJ1cGRhdGVFZGl0b3IiOmZhbHNlfQ) + +## State details + +### idle + +The **idle** state is the initial state of a `Client` instance. While an `origin` is required for instantiating a `Client` instance, the underlying socket connection will not be established until a request is queued using [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers). By calling `Client.dispatch()` directly or using one of the multiple implementations ([`Client.connect()`](Client.md#clientconnectoptions-callback), [`Client.pipeline()`](Client.md#clientpipelineoptions-handler), [`Client.request()`](Client.md#clientrequestoptions-callback), [`Client.stream()`](Client.md#clientstreamoptions-factory-callback), and [`Client.upgrade()`](Client.md#clientupgradeoptions-callback)), the `Client` instance will transition from **idle** to [**pending**](#pending) and then most likely directly to [**processing**](#processing). + +Calling [`Client.close()`](Client.md#clientclosecallback) or [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state since the `Client` instance will have no queued requests in this state. + +### pending + +The **pending** state signifies a non-processing `Client`. Upon entering this state, the `Client` establishes a socket connection and emits the [`'connect'`](Client.md#event-connect) event signalling a connection was successfully established with the `origin` provided during `Client` instantiation. The internal queue is initially empty, and requests can start queueing. + +Calling [`Client.close()`](Client.md#clientclosecallback) with queued requests, transitions the `Client` to the [**processing**](#processing) state. Without queued requests, it transitions to the [**destroyed**](#destroyed) state. + +Calling [`Client.destroy()`](Client.md#clientdestroyerror-callback) transitions directly to the [**destroyed**](#destroyed) state regardless of existing requests. + +### processing + +The **processing** state is a state machine within itself. It initializes to the [**processing.running**](#running) state. The [`Client.dispatch()`](Client.md#clientdispatchoptions-handlers), [`Client.close()`](Client.md#clientclosecallback), and [`Client.destroy()`](Client.md#clientdestroyerror-callback) can be called at any time while the `Client` is in this state. `Client.dispatch()` will add more requests to the queue while existing requests continue to be processed. `Client.close()` will transition to the [**processing.closing**](#closing) state. And `Client.destroy()` will transition to [**destroyed**](#destroyed). + +#### running + +In the **processing.running** sub-state, queued requests are being processed in a FIFO order. If a request body requires draining, the *needDrain* event transitions to the [**processing.busy**](#busy) sub-state. The *close* event transitions the Client to the [**process.closing**](#closing) sub-state. If all queued requests are processed and neither [`Client.close()`](Client.md#clientclosecallback) nor [`Client.destroy()`](Client.md#clientdestroyerror-callback) are called, then the [**processing**](#processing) machine will trigger a *keepalive* event transitioning the `Client` back to the [**pending**](#pending) state. During this time, the `Client` is waiting for the socket connection to timeout, and once it does, it triggers the *timeout* event and transitions to the [**idle**](#idle) state. + +#### busy + +This sub-state is only entered when a request body is an instance of [Stream](https://nodejs.org/api/stream.html) and requires draining. The `Client` cannot process additional requests while in this state and must wait until the currently processing request body is completely drained before transitioning back to [**processing.running**](#running). + +#### closing + +This sub-state is only entered when a `Client` instance has queued requests and the [`Client.close()`](Client.md#clientclosecallback) method is called. In this state, the `Client` instance continues to process requests as usual, with the one exception that no additional requests can be queued. Once all of the queued requests are processed, the `Client` will trigger the *done* event gracefully entering the [**destroyed**](#destroyed) state without an error. + +### destroyed + +The **destroyed** state is a final state for the `Client` instance. Once in this state, a `Client` is nonfunctional. Calling any other `Client` methods will result in an `ClientDestroyedError`. diff --git a/node_modules/undici/docs/assets/lifecycle-diagram.png b/node_modules/undici/docs/assets/lifecycle-diagram.png new file mode 100644 index 0000000..4ef17b5 Binary files /dev/null and b/node_modules/undici/docs/assets/lifecycle-diagram.png differ diff --git a/node_modules/undici/docs/best-practices/client-certificate.md b/node_modules/undici/docs/best-practices/client-certificate.md new file mode 100644 index 0000000..4fc84ec --- /dev/null +++ b/node_modules/undici/docs/best-practices/client-certificate.md @@ -0,0 +1,64 @@ +# Client certificate + +Client certificate authentication can be configured with the `Client`, the required options are passed along through the `connect` option. + +The client certificates must be signed by a trusted CA. The Node.js default is to trust the well-known CAs curated by Mozilla. + +Setting the server option `requestCert: true` tells the server to request the client certificate. + +The server option `rejectUnauthorized: false` allows us to handle any invalid certificate errors in client code. The `authorized` property on the socket of the incoming request will show if the client certificate was valid. The `authorizationError` property will give the reason if the certificate was not valid. + +### Client Certificate Authentication + +```js +const { readFileSync } = require('fs') +const { join } = require('path') +const { createServer } = require('https') +const { Client } = require('undici') + +const serverOptions = { + ca: [ + readFileSync(join(__dirname, 'client-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'server-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'server-crt.pem'), 'utf8'), + requestCert: true, + rejectUnauthorized: false +} + +const server = createServer(serverOptions, (req, res) => { + // true if client cert is valid + if(req.client.authorized === true) { + console.log('valid') + } else { + console.error(req.client.authorizationError) + } + res.end() +}) + +server.listen(0, function () { + const tls = { + ca: [ + readFileSync(join(__dirname, 'server-ca-crt.pem'), 'utf8') + ], + key: readFileSync(join(__dirname, 'client-key.pem'), 'utf8'), + cert: readFileSync(join(__dirname, 'client-crt.pem'), 'utf8'), + rejectUnauthorized: false, + servername: 'agent1' + } + const client = new Client(`https://localhost:${server.address().port}`, { + connect: tls + }) + + client.request({ + path: '/', + method: 'GET' + }, (err, { body }) => { + body.on('data', (buf) => {}) + body.on('end', () => { + client.close() + server.close() + }) + }) +}) +``` diff --git a/node_modules/undici/docs/best-practices/mocking-request.md b/node_modules/undici/docs/best-practices/mocking-request.md new file mode 100644 index 0000000..6954392 --- /dev/null +++ b/node_modules/undici/docs/best-practices/mocking-request.md @@ -0,0 +1,136 @@ +# Mocking Request + +Undici has its own mocking [utility](../api/MockAgent.md). It allow us to intercept undici HTTP requests and return mocked values instead. It can be useful for testing purposes. + +Example: + +```js +// bank.mjs +import { request } from 'undici' + +export async function bankTransfer(recipient, amount) { + const { body } = await request('http://localhost:3000/bank-transfer', + { + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient, + amount + }) + } + ) + return await body.json() +} +``` + +And this is what the test file looks like: + +```js +// index.test.mjs +import { strict as assert } from 'assert' +import { MockAgent, setGlobalDispatcher, } from 'undici' +import { bankTransfer } from './bank.mjs' + +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +// intercept the request +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, { + message: 'transaction processed' +}) + +const success = await bankTransfer('1234567890', '100') + +assert.deepEqual(success, { message: 'transaction processed' }) + +// if you dont want to check whether the body or the headers contain the same value +// just remove it from interceptor +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(400, { + message: 'bank account not found' +}) + +const badRequest = await bankTransfer('1234567890', '100') + +assert.deepEqual(badRequest, { message: 'bank account not found' }) +``` + +Explore other MockAgent functionality [here](../api/MockAgent.md) + +## Debug Mock Value + +When the interceptor and the request options are not the same, undici will automatically make a real HTTP request. To prevent real requests from being made, use `mockAgent.disableNetConnect()`: + +```js +const mockAgent = new MockAgent(); + +setGlobalDispatcher(mockAgent); +mockAgent.disableNetConnect() + +// Provide the base url to the request +const mockPool = mockAgent.get('http://localhost:3000'); + +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', +}).reply(200, { + message: 'transaction processed' +}) + +const badRequest = await bankTransfer('1234567890', '100') +// Will throw an error +// MockNotMatchedError: Mock dispatch not matched for path '/bank-transfer': +// subsequent request to origin http://localhost:3000 was not allowed (net.connect disabled) +``` + +## Reply with data based on request + +If the mocked response needs to be dynamically derived from the request parameters, you can provide a function instead of an object to `reply`: + +```js +mockPool.intercept({ + path: '/bank-transfer', + method: 'POST', + headers: { + 'X-TOKEN-SECRET': 'SuperSecretToken', + }, + body: JSON.stringify({ + recipient: '1234567890', + amount: '100' + }) +}).reply(200, (opts) => { + // do something with opts + + return { message: 'transaction processed' } +}) +``` + +in this case opts will be + +``` +{ + method: 'POST', + headers: { 'X-TOKEN-SECRET': 'SuperSecretToken' }, + body: '{"recipient":"1234567890","amount":"100"}', + origin: 'http://localhost:3000', + path: '/bank-transfer' +} +``` diff --git a/node_modules/undici/docs/best-practices/proxy.md b/node_modules/undici/docs/best-practices/proxy.md new file mode 100644 index 0000000..bf10295 --- /dev/null +++ b/node_modules/undici/docs/best-practices/proxy.md @@ -0,0 +1,127 @@ +# Connecting through a proxy + +Connecting through a proxy is possible by: + +- Using [AgentProxy](../api/ProxyAgent.md). +- Configuring `Client` or `Pool` constructor. + +The proxy url should be passed to the `Client` or `Pool` constructor, while the upstream server url +should be added to every request call in the `path`. +For instance, if you need to send a request to the `/hello` route of your upstream server, +the `path` should be `path: 'http://upstream.server:port/hello?foo=bar'`. + +If you proxy requires basic authentication, you can send it via the `proxy-authorization` header. + +### Connect without authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar' +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + +### Connect with authentication + +```js +import { Client } from 'undici' +import { createServer } from 'http' +import proxy from 'proxy' + +const server = await buildServer() +const proxyServer = await buildProxy() + +const serverUrl = `http://localhost:${server.address().port}` +const proxyUrl = `http://localhost:${proxyServer.address().port}` + +proxyServer.authenticate = function (req, fn) { + fn(null, req.headers['proxy-authorization'] === `Basic ${Buffer.from('user:pass').toString('base64')}`) +} + +server.on('request', (req, res) => { + console.log(req.url) // '/hello?foo=bar' + res.setHeader('content-type', 'application/json') + res.end(JSON.stringify({ hello: 'world' })) +}) + +const client = new Client(proxyUrl) + +const response = await client.request({ + method: 'GET', + path: serverUrl + '/hello?foo=bar', + headers: { + 'proxy-authorization': `Basic ${Buffer.from('user:pass').toString('base64')}` + } +}) + +response.body.setEncoding('utf8') +let data = '' +for await (const chunk of response.body) { + data += chunk +} +console.log(response.statusCode) // 200 +console.log(JSON.parse(data)) // { hello: 'world' } + +server.close() +proxyServer.close() +client.close() + +function buildServer () { + return new Promise((resolve, reject) => { + const server = createServer() + server.listen(0, () => resolve(server)) + }) +} + +function buildProxy () { + return new Promise((resolve, reject) => { + const server = proxy(createServer()) + server.listen(0, () => resolve(server)) + }) +} +``` + diff --git a/node_modules/undici/docs/best-practices/writing-tests.md b/node_modules/undici/docs/best-practices/writing-tests.md new file mode 100644 index 0000000..57549de --- /dev/null +++ b/node_modules/undici/docs/best-practices/writing-tests.md @@ -0,0 +1,20 @@ +# Writing tests + +Undici is tuned for a production use case and its default will keep +a socket open for a few seconds after an HTTP request is completed to +remove the overhead of opening up a new socket. These settings that makes +Undici shine in production are not a good fit for using Undici in automated +tests, as it will result in longer execution times. + +The following are good defaults that will keep the socket open for only 10ms: + +```js +import { request, setGlobalDispatcher, Agent } from 'undici' + +const agent = new Agent({ + keepAliveTimeout: 10, // milliseconds + keepAliveMaxTimeout: 10 // milliseconds +}) + +setGlobalDispatcher(agent) +``` diff --git a/node_modules/undici/index-fetch.js b/node_modules/undici/index-fetch.js new file mode 100644 index 0000000..ba31a65 --- /dev/null +++ b/node_modules/undici/index-fetch.js @@ -0,0 +1,15 @@ +'use strict' + +const fetchImpl = require('./lib/fetch').fetch + +module.exports.fetch = function fetch (resource, init = undefined) { + return fetchImpl(resource, init).catch((err) => { + Error.captureStackTrace(err, this) + throw err + }) +} +module.exports.FormData = require('./lib/fetch/formdata').FormData +module.exports.Headers = require('./lib/fetch/headers').Headers +module.exports.Response = require('./lib/fetch/response').Response +module.exports.Request = require('./lib/fetch/request').Request +module.exports.WebSocket = require('./lib/websocket/websocket').WebSocket diff --git a/node_modules/undici/index.d.ts b/node_modules/undici/index.d.ts new file mode 100644 index 0000000..83a786d --- /dev/null +++ b/node_modules/undici/index.d.ts @@ -0,0 +1,3 @@ +export * from './types/index' +import Undici from './types/index' +export default Undici diff --git a/node_modules/undici/index.js b/node_modules/undici/index.js new file mode 100644 index 0000000..26302cc --- /dev/null +++ b/node_modules/undici/index.js @@ -0,0 +1,167 @@ +'use strict' + +const Client = require('./lib/client') +const Dispatcher = require('./lib/dispatcher') +const errors = require('./lib/core/errors') +const Pool = require('./lib/pool') +const BalancedPool = require('./lib/balanced-pool') +const Agent = require('./lib/agent') +const util = require('./lib/core/util') +const { InvalidArgumentError } = errors +const api = require('./lib/api') +const buildConnector = require('./lib/core/connect') +const MockClient = require('./lib/mock/mock-client') +const MockAgent = require('./lib/mock/mock-agent') +const MockPool = require('./lib/mock/mock-pool') +const mockErrors = require('./lib/mock/mock-errors') +const ProxyAgent = require('./lib/proxy-agent') +const RetryHandler = require('./lib/handler/RetryHandler') +const { getGlobalDispatcher, setGlobalDispatcher } = require('./lib/global') +const DecoratorHandler = require('./lib/handler/DecoratorHandler') +const RedirectHandler = require('./lib/handler/RedirectHandler') +const createRedirectInterceptor = require('./lib/interceptor/redirectInterceptor') + +let hasCrypto +try { + require('crypto') + hasCrypto = true +} catch { + hasCrypto = false +} + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor + +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = require('./lib/fetch').fetch + } + + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } + + throw err + } + } + module.exports.Headers = require('./lib/fetch/headers').Headers + module.exports.Response = require('./lib/fetch/response').Response + module.exports.Request = require('./lib/fetch/request').Request + module.exports.FormData = require('./lib/fetch/formdata').FormData + module.exports.File = require('./lib/fetch/file').File + module.exports.FileReader = require('./lib/fileapi/filereader').FileReader + + const { setGlobalOrigin, getGlobalOrigin } = require('./lib/fetch/global') + + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin + + const { CacheStorage } = require('./lib/cache/cachestorage') + const { kConstruct } = require('./lib/cache/symbols') + + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) +} + +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = require('./lib/cookies') + + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie + + const { parseMIMEType, serializeAMimeType } = require('./lib/fetch/dataURL') + + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} + +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = require('./lib/websocket/websocket') + + module.exports.WebSocket = WebSocket +} + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors diff --git a/node_modules/undici/lib/agent.js b/node_modules/undici/lib/agent.js new file mode 100644 index 0000000..0b18f2a --- /dev/null +++ b/node_modules/undici/lib/agent.js @@ -0,0 +1,148 @@ +'use strict' + +const { InvalidArgumentError } = require('./core/errors') +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = require('./core/symbols') +const DispatcherBase = require('./dispatcher-base') +const Pool = require('./pool') +const Client = require('./client') +const util = require('./core/util') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const { WeakRef, FinalizationRegistry } = require('./compat/dispatcher-weakref')() + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] + + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) + + const agent = this + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + const ref = this[kClients].get(key) + + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } + + await Promise.all(destroyPromises) + } +} + +module.exports = Agent diff --git a/node_modules/undici/lib/api/abort-signal.js b/node_modules/undici/lib/api/abort-signal.js new file mode 100644 index 0000000..2985c1e --- /dev/null +++ b/node_modules/undici/lib/api/abort-signal.js @@ -0,0 +1,54 @@ +const { addAbortListener } = require('../core/util') +const { RequestAbortedError } = require('../core/errors') + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} + +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} diff --git a/node_modules/undici/lib/api/api-connect.js b/node_modules/undici/lib/api/api-connect.js new file mode 100644 index 0000000..fd2b6ad --- /dev/null +++ b/node_modules/undici/lib/api/api-connect.js @@ -0,0 +1,104 @@ +'use strict' + +const { AsyncResource } = require('async_hooks') +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect diff --git a/node_modules/undici/lib/api/api-pipeline.js b/node_modules/undici/lib/api/api-pipeline.js new file mode 100644 index 0000000..af4a180 --- /dev/null +++ b/node_modules/undici/lib/api/api-pipeline.js @@ -0,0 +1,249 @@ +'use strict' + +const { + Readable, + Duplex, + PassThrough +} = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', util.nop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { ret, res } = this + + assert(!res, 'pipeline cannot be retried') + + if (ret.destroyed) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline diff --git a/node_modules/undici/lib/api/api-request.js b/node_modules/undici/lib/api/api-request.js new file mode 100644 index 0000000..d4281ce --- /dev/null +++ b/node_modules/undici/lib/api/api-request.js @@ -0,0 +1,180 @@ +'use strict' + +const Readable = require('./readable') +const { + InvalidArgumentError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) + + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } + } + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + util.parseHeaders(trailers, this.trailers) + + res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + removeSignal(this) + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request +module.exports.RequestHandler = RequestHandler diff --git a/node_modules/undici/lib/api/api-stream.js b/node_modules/undici/lib/api/api-stream.js new file mode 100644 index 0000000..c571a6f --- /dev/null +++ b/node_modules/undici/lib/api/api-stream.js @@ -0,0 +1,220 @@ +'use strict' + +const { finished, PassThrough } = require('stream') +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = require('../core/errors') +const util = require('../core/util') +const { getResolveErrorBodyCallback } = require('./util') +const { AsyncResource } = require('async_hooks') +const { addSignal, removeSignal } = require('./abort-signal') + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + let res + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() + + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream diff --git a/node_modules/undici/lib/api/api-upgrade.js b/node_modules/undici/lib/api/api-upgrade.js new file mode 100644 index 0000000..ef783e8 --- /dev/null +++ b/node_modules/undici/lib/api/api-upgrade.js @@ -0,0 +1,105 @@ +'use strict' + +const { InvalidArgumentError, RequestAbortedError, SocketError } = require('../core/errors') +const { AsyncResource } = require('async_hooks') +const util = require('../core/util') +const { addSignal, removeSignal } = require('./abort-signal') +const assert = require('assert') + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + assert.strictEqual(statusCode, 101) + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade diff --git a/node_modules/undici/lib/api/index.js b/node_modules/undici/lib/api/index.js new file mode 100644 index 0000000..8983a5e --- /dev/null +++ b/node_modules/undici/lib/api/index.js @@ -0,0 +1,7 @@ +'use strict' + +module.exports.request = require('./api-request') +module.exports.stream = require('./api-stream') +module.exports.pipeline = require('./api-pipeline') +module.exports.upgrade = require('./api-upgrade') +module.exports.connect = require('./api-connect') diff --git a/node_modules/undici/lib/api/readable.js b/node_modules/undici/lib/api/readable.js new file mode 100644 index 0000000..5269dfa --- /dev/null +++ b/node_modules/undici/lib/api/readable.js @@ -0,0 +1,322 @@ +// Ported from https://github.com/nodejs/undici/pull/907 + +'use strict' + +const assert = require('assert') +const { Readable } = require('stream') +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = require('../core/errors') +const util = require('../core/util') +const { ReadableStreamFrom, toUSVString } = require('../core/util') + +let Blob + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') + +const noop = () => {} + +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + return super.destroy(err) + } + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal + + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) + } + } + + if (this.closed) { + return Promise.resolve(null) + } + + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop + + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) + } +} + +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} + +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} + +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } + + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = require('buffer').Blob + } + resolve(new Blob(body, { type: stream[kContentType] })) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} diff --git a/node_modules/undici/lib/api/util.js b/node_modules/undici/lib/api/util.js new file mode 100644 index 0000000..bffd702 --- /dev/null +++ b/node_modules/undici/lib/api/util.js @@ -0,0 +1,46 @@ +const assert = require('assert') +const { + ResponseStatusCodeError +} = require('../core/errors') +const { toUSVString } = require('../core/util') + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) + + let chunks = [] + let limit = 0 + + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } + } + + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } + + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} + +module.exports = { getResolveErrorBodyCallback } diff --git a/node_modules/undici/lib/balanced-pool.js b/node_modules/undici/lib/balanced-pool.js new file mode 100644 index 0000000..10bc6a4 --- /dev/null +++ b/node_modules/undici/lib/balanced-pool.js @@ -0,0 +1,190 @@ +'use strict' + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = require('./core/errors') +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = require('./pool-base') +const Pool = require('./pool') +const { kUrl, kInterceptors } = require('./core/symbols') +const { parseOrigin } = require('./core/util') +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool diff --git a/node_modules/undici/lib/cache/cache.js b/node_modules/undici/lib/cache/cache.js new file mode 100644 index 0000000..9b31108 --- /dev/null +++ b/node_modules/undici/lib/cache/cache.js @@ -0,0 +1,838 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { urlEquals, fieldValues: getFieldValues } = require('./util') +const { kEnumerableProperty, isDisturbed } = require('../core/util') +const { kHeadersList } = require('../core/symbols') +const { webidl } = require('../fetch/webidl') +const { Response, cloneResponse } = require('../fetch/response') +const { Request } = require('../fetch/request') +const { kState, kHeaders, kGuard, kRealm } = require('../fetch/symbols') +const { fetching } = require('../fetch/index') +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = require('../fetch/util') +const assert = require('assert') +const { getGlobalDispatcher } = require('../global') + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + const p = await this.matchAll(request, options) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null) + const body = responseObject[kState].body + responseObject[kState] = response + responseObject[kState].body = body + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + + responseList.push(responseObject) + } + + // 6. + return Object.freeze(responseList) + } + + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) + + request = webidl.converters.RequestInfo(request) + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) + + requests = webidl.converters['sequence'](requests) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState] + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) + + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) + + // 1. + let innerRequest = null + + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + /** + * @type {Request} + */ + let r = null + + if (request instanceof Request) { + r = request[kState] + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = new Request(request)[kState] + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a') + requestObject[kState] = request + requestObject[kHeaders][kHeadersList] = request.headersList + requestObject[kHeaders][kGuard] = 'immutable' + requestObject[kRealm] = request.client + + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter(Response) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} diff --git a/node_modules/undici/lib/cache/cachestorage.js b/node_modules/undici/lib/cache/cachestorage.js new file mode 100644 index 0000000..7e7f0cf --- /dev/null +++ b/node_modules/undici/lib/cache/cachestorage.js @@ -0,0 +1,144 @@ +'use strict' + +const { kConstruct } = require('./symbols') +const { Cache } = require('./cache') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) + + cacheName = webidl.converters.DOMString(cacheName) + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} diff --git a/node_modules/undici/lib/cache/symbols.js b/node_modules/undici/lib/cache/symbols.js new file mode 100644 index 0000000..40448d6 --- /dev/null +++ b/node_modules/undici/lib/cache/symbols.js @@ -0,0 +1,5 @@ +'use strict' + +module.exports = { + kConstruct: require('../core/symbols').kConstruct +} diff --git a/node_modules/undici/lib/cache/util.js b/node_modules/undici/lib/cache/util.js new file mode 100644 index 0000000..44d52b7 --- /dev/null +++ b/node_modules/undici/lib/cache/util.js @@ -0,0 +1,49 @@ +'use strict' + +const assert = require('assert') +const { URLSerializer } = require('../fetch/dataURL') +const { isValidHeaderName } = require('../fetch/util') + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function fieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue + } + + values.push(value) + } + + return values +} + +module.exports = { + urlEquals, + fieldValues +} diff --git a/node_modules/undici/lib/client.js b/node_modules/undici/lib/client.js new file mode 100644 index 0000000..22cb390 --- /dev/null +++ b/node_modules/undici/lib/client.js @@ -0,0 +1,2283 @@ +// @ts-check + +'use strict' + +/* global WebAssembly */ + +const assert = require('assert') +const net = require('net') +const http = require('http') +const { pipeline } = require('stream') +const util = require('./core/util') +const timers = require('./timers') +const Request = require('./core/request') +const DispatcherBase = require('./dispatcher-base') +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = require('./core/errors') +const buildConnector = require('./core/connect') +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = require('./core/symbols') + +/** @type {import('http2')} */ +let http2 +try { + http2 = require('http2') +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 + +// Experimental +let h2ExperimentalWarned = false + +const FastBuffer = Buffer[Symbol.species] + +const kClosedResolve = Symbol('kClosedResolve') + +const channels = {} + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} + +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super() + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kHTTPConnVersion] = 'h1' + + // HTTP/2 + this[kHTTP2Session] = null + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + } + this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } + + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) + } else { + resume(this, true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize]) { + resolve(null) + } else { + this[kClosedResolve] = resolve + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } + + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } + + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } + + resume(this) + }) + } +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + + onError(this[kClient], err) +} + +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) + } +} + +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} + +function onHTTP2GoAway (code) { + const client = this[kClient] + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) + client[kSocket] = null + client[kHTTP2Session] = null + + if (client.destroyed) { + assert(this[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + } else if (client[kRunning] > 0) { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', + client[kUrl], + [client], + err + ) + + resume(client) +} + +const constants = require('./llhttp/constants') +const createRedirectInterceptor = require('./interceptor/redirectInterceptor') +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? require('./llhttp/llhttp-wasm.js') : undefined + + let mod + try { + mod = await WebAssembly.compile(Buffer.from(require('./llhttp/llhttp_simd-wasm.js'), 'base64')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || require('./llhttp/llhttp-wasm.js'), 'base64')) + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) +} + +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() + } + } else { + this.timeout = null + } + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) + + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + resume(client) + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(statusCode >= 100) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() + } +} + +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this + + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + } + + this[kError] = err + + onError(this[kClient], err) +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this + + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this + + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) +} + +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return + } + + client[kConnecting] = false + + assert(socket) + + const isH2 = socket.alpnProtocol === 'h2' + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) + + client[kHTTPConnVersion] = 'h2' + session[kClient] = client + session[kSocket] = socket + session.on('error', onHttp2SessionError) + session.on('frameError', onHttp2FrameError) + session.on('end', onHttp2SessionEnd) + session.on('goaway', onHTTP2GoAway) + session.on('close', onSocketClose) + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + } + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) + + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + const socket = client[kSocket] + + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } + } + + if (client[kConnecting]) { + return + } + + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } + + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } + + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return + } + + const { body, method, path, host, upgrade, headers, blocking, reset } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (headers) { + header += headers + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) + } + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } + + return true +} + +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders + + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } + + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] + + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method + + if (method === 'CONNECT') { + session.ref() + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) + } + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } + + // Increment counter as we have new several streams open + ++h2State.openStreams + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + stream.pause() + } + }) + + stream.once('end', () => { + request.onComplete([]) + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() + } + }) + + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) + + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + stream.cork() + stream.write(body) + stream.uncork() + stream.end() + request.onBodySent(body) + request.onRequestSent() + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }) + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }) + } + } else if (util.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }) + } else if (util.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }) + } else { + assert(false) + } + } +} + +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err) + util.destroy(h2stream, err) + } else { + request.onRequestSent() + } + } + ) + + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } + + return + } + + let finished = false + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + const onAbort = function () { + if (finished) { + return + } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) +} + +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') + + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + if (isH2) { + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + } else { + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + } + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} + +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + } catch (err) { + h2stream.destroy(err) + } finally { + request.onRequestSent() + h2stream.end() + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } + + return + } + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + resume(client) + } + + destroy (err) { + const { socket, client } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} + +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +module.exports = Client diff --git a/node_modules/undici/lib/compat/dispatcher-weakref.js b/node_modules/undici/lib/compat/dispatcher-weakref.js new file mode 100644 index 0000000..8cb99e2 --- /dev/null +++ b/node_modules/undici/lib/compat/dispatcher-weakref.js @@ -0,0 +1,48 @@ +'use strict' + +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = require('../core/symbols') + +class CompatWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} + +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } + } +} + +module.exports = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} diff --git a/node_modules/undici/lib/cookies/constants.js b/node_modules/undici/lib/cookies/constants.js new file mode 100644 index 0000000..85f1fec --- /dev/null +++ b/node_modules/undici/lib/cookies/constants.js @@ -0,0 +1,12 @@ +'use strict' + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} diff --git a/node_modules/undici/lib/cookies/index.js b/node_modules/undici/lib/cookies/index.js new file mode 100644 index 0000000..c9c1f28 --- /dev/null +++ b/node_modules/undici/lib/cookies/index.js @@ -0,0 +1,184 @@ +'use strict' + +const { parseSetCookie } = require('./parse') +const { stringify, getHeadersList } = require('./util') +const { webidl } = require('../fetch/webidl') +const { Headers } = require('../fetch/headers') + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = getHeadersList(headers).cookies + + if (!cookies) { + return [] + } + + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} diff --git a/node_modules/undici/lib/cookies/parse.js b/node_modules/undici/lib/cookies/parse.js new file mode 100644 index 0000000..aae2750 --- /dev/null +++ b/node_modules/undici/lib/cookies/parse.js @@ -0,0 +1,317 @@ +'use strict' + +const { maxNameValuePairSize, maxAttributeValueSize } = require('./constants') +const { isCTLExcludingHtab } = require('./util') +const { collectASequenceOfCodePointsFast } = require('../fetch/dataURL') +const assert = require('assert') + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} diff --git a/node_modules/undici/lib/cookies/util.js b/node_modules/undici/lib/cookies/util.js new file mode 100644 index 0000000..2290329 --- /dev/null +++ b/node_modules/undici/lib/cookies/util.js @@ -0,0 +1,291 @@ +'use strict' + +const assert = require('assert') +const { kHeadersList } = require('../core/symbols') + +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) + + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] + + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +let kHeadersListNode + +function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] + } + + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ) + + assert(kHeadersListNode, 'Headers cannot be parsed') + } + + const headersList = headers[kHeadersListNode] + assert(headersList) + + return headersList +} + +module.exports = { + isCTLExcludingHtab, + stringify, + getHeadersList +} diff --git a/node_modules/undici/lib/core/connect.js b/node_modules/undici/lib/core/connect.js new file mode 100644 index 0000000..3309117 --- /dev/null +++ b/node_modules/undici/lib/core/connect.js @@ -0,0 +1,189 @@ +'use strict' + +const net = require('net') +const assert = require('assert') +const util = require('./util') +const { InvalidArgumentError, ConnectTimeoutError } = require('./errors') + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } + } +} + +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = require('tls') + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } + + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() + } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) + } +} + +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} + +module.exports = buildConnector diff --git a/node_modules/undici/lib/core/constants.js b/node_modules/undici/lib/core/constants.js new file mode 100644 index 0000000..6ec770d --- /dev/null +++ b/node_modules/undici/lib/core/constants.js @@ -0,0 +1,118 @@ +'use strict' + +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) + +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} diff --git a/node_modules/undici/lib/core/errors.js b/node_modules/undici/lib/core/errors.js new file mode 100644 index 0000000..7af704b --- /dev/null +++ b/node_modules/undici/lib/core/errors.js @@ -0,0 +1,230 @@ +'use strict' + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} + +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } +} + +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} + +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} + +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} + +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} + +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} + +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} + +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} + +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} + +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} + +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} + +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + Error.captureStackTrace(this, RequestRetryError) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} + +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} diff --git a/node_modules/undici/lib/core/request.js b/node_modules/undici/lib/core/request.js new file mode 100644 index 0000000..3697e6a --- /dev/null +++ b/node_modules/undici/lib/core/request.js @@ -0,0 +1,499 @@ +'use strict' + +const { + InvalidArgumentError, + NotSupportedError +} = require('./errors') +const assert = require('assert') +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = require('./symbols') +const util = require('./util') + +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +const channels = {} + +let extractBody + +try { + const diagnosticsChannel = require('diagnostics_channel') + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? util.buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = '' + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } + + if (!extractBody) { + extractBody = require('../fetch/body.js').extractBody + } + + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` + } + this.body = bodyStream.stream + this.contentLength = bodyStream.length + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` + } + + util.validateHandler(handler, method, upgrade) + + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this + } + + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } + + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } + + const request = new Request(origin, opts, handler) + + request.headers = {} + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(request, key, headers[key], true) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + return request + } + + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} + + for (const header of rawHeaders) { + const [key, value] = header.split(': ') + + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value + } + + return headers + } +} + +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + return skipAppend ? val : `${key}: ${val}\r\n` +} + +function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` + else request.headers[key] = processHeaderValue(key, val[i], skipAppend) + } else { + request.headers += processHeaderValue(key, val[i]) + } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } + } +} + +module.exports = Request diff --git a/node_modules/undici/lib/core/symbols.js b/node_modules/undici/lib/core/symbols.js new file mode 100644 index 0000000..68d8566 --- /dev/null +++ b/node_modules/undici/lib/core/symbols.js @@ -0,0 +1,63 @@ +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable') +} diff --git a/node_modules/undici/lib/core/util.js b/node_modules/undici/lib/core/util.js new file mode 100644 index 0000000..5741650 --- /dev/null +++ b/node_modules/undici/lib/core/util.js @@ -0,0 +1,522 @@ +'use strict' + +const assert = require('assert') +const { kDestroyed, kBodyUsed } = require('./symbols') +const { IncomingMessage } = require('http') +const stream = require('stream') +const net = require('net') +const { InvalidArgumentError } = require('./errors') +const { Blob } = require('buffer') +const nodeUtil = require('util') +const { stringify } = require('querystring') +const { headerNameLowerCasedRecord } = require('./constants') + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) + } + + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} + +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} + +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} + +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers + + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1].map(x => x.toString('utf8')) + } else { + obj[key] = headers[i + 1].toString('utf8') + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 + + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') + + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val) + hasContentLength = true + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1 + } else { + ret.push(key, val) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} + +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} + +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} + +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} + +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err + } + } +} + +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} + +const hasToWellFormed = !!String.prototype.toWellFormed + +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } + + return `${val}` +} + +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + parseRangeHeader, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +} diff --git a/node_modules/undici/lib/dispatcher-base.js b/node_modules/undici/lib/dispatcher-base.js new file mode 100644 index 0000000..5c0220b --- /dev/null +++ b/node_modules/undici/lib/dispatcher-base.js @@ -0,0 +1,192 @@ +'use strict' + +const Dispatcher = require('./dispatcher') +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = require('./core/errors') +const { kDestroy, kClose, kDispatch, kInterceptors } = require('./core/symbols') + +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') + +class DispatcherBase extends Dispatcher { + constructor () { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase diff --git a/node_modules/undici/lib/dispatcher.js b/node_modules/undici/lib/dispatcher.js new file mode 100644 index 0000000..9b809d8 --- /dev/null +++ b/node_modules/undici/lib/dispatcher.js @@ -0,0 +1,19 @@ +'use strict' + +const EventEmitter = require('events') + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher diff --git a/node_modules/mixme/LICENSE b/node_modules/undici/lib/fetch/LICENSE similarity index 54% rename from node_modules/mixme/LICENSE rename to node_modules/undici/lib/fetch/LICENSE index 0f99a5d..2943500 100644 --- a/node_modules/mixme/LICENSE +++ b/node_modules/undici/lib/fetch/LICENSE @@ -1,22 +1,21 @@ - MIT License -Copyright (c) 2018 SARL Adaltas. +Copyright (c) 2020 Ethan Arrowood -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: +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 +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 +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. diff --git a/node_modules/undici/lib/fetch/body.js b/node_modules/undici/lib/fetch/body.js new file mode 100644 index 0000000..fd8481b --- /dev/null +++ b/node_modules/undici/lib/fetch/body.js @@ -0,0 +1,605 @@ +'use strict' + +const Busboy = require('@fastify/busboy') +const util = require('../core/util') +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = require('./util') +const { FormData } = require('./formdata') +const { kState } = require('./symbols') +const { webidl } = require('./webidl') +const { DOMException, structuredClone } = require('./constants') +const { Blob, File: NativeFile } = require('buffer') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { isErrored } = require('../core/util') +const { isUint8Array, isArrayBuffer } = require('util/types') +const { File: UndiciFile } = require('./file') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = require('stream/web').ReadableStream + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} + +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true + + yield * stream + } + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, + + async formData () { + webidl.brandCheck(this, instance) + + throwIfAborted(this[kState]) + + const contentType = this.headers.get('Content-Type') + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value + + const responseFormData = new FormData() + + let busboy + + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } + + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') + + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) + + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } else { + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += streamingDecoder.decode(chunk, { stream: true }) + } + text += streamingDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) + } + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } + } + } + + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} diff --git a/node_modules/undici/lib/fetch/constants.js b/node_modules/undici/lib/fetch/constants.js new file mode 100644 index 0000000..218fcbe --- /dev/null +++ b/node_modules/undici/lib/fetch/constants.js @@ -0,0 +1,151 @@ +'use strict' + +const { MessageChannel, receiveMessageOnPort } = require('worker_threads') + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +const badPortsSet = new Set(badPorts) + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +// https://fetch.spec.whatwg.org/#request-body-header-name +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel + +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') + } + + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } + +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} diff --git a/node_modules/undici/lib/fetch/dataURL.js b/node_modules/undici/lib/fetch/dataURL.js new file mode 100644 index 0000000..7b6a606 --- /dev/null +++ b/node_modules/undici/lib/fetch/dataURL.js @@ -0,0 +1,627 @@ +const assert = require('assert') +const { atob } = require('buffer') +const { isomorphicDecode } = require('./util') + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data) + const bytes = new Uint8Array(binary.length) + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } + + return bytes +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} diff --git a/node_modules/undici/lib/fetch/file.js b/node_modules/undici/lib/fetch/file.js new file mode 100644 index 0000000..3133d25 --- /dev/null +++ b/node_modules/undici/lib/fetch/file.js @@ -0,0 +1,344 @@ +'use strict' + +const { Blob, File: NativeFile } = require('buffer') +const { types } = require('util') +const { kState } = require('./symbols') +const { isBlobLike } = require('./util') +const { webidl } = require('./webidl') +const { parseMIMEType, serializeAMimeType } = require('./dataURL') +const { kEnumerableProperty } = require('../core/util') +const encoder = new TextEncoder() + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase() + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified + } + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } + } + + get name () { + webidl.brandCheck(this, File) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, File) + + return this[kState].lastModified + } + + get type () { + webidl.brandCheck(this, File) + + return this[kState].type + } +} + +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) + +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' + } + + return value + }, + defaultValue: 'transparent' + } +]) + +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(encoder.encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) + } + } + + // 3. Return bytes. + return bytes +} + +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' + + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' + } + + return s.replace(/\r?\n/g, nativeLineEnding) +} + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { File, FileLike, isFileLike } diff --git a/node_modules/undici/lib/fetch/formdata.js b/node_modules/undici/lib/fetch/formdata.js new file mode 100644 index 0000000..5975e26 --- /dev/null +++ b/node_modules/undici/lib/fetch/formdata.js @@ -0,0 +1,265 @@ +'use strict' + +const { isBlobLike, toUSVString, makeIterator } = require('./util') +const { kState } = require('./symbols') +const { File: UndiciFile, FileLike, isFileLike } = require('./file') +const { webidl } = require('./webidl') +const { Blob, File: NativeFile } = require('buffer') + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } + } + + entries () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } +} + +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData } diff --git a/node_modules/undici/lib/fetch/global.js b/node_modules/undici/lib/fetch/global.js new file mode 100644 index 0000000..1df6f12 --- /dev/null +++ b/node_modules/undici/lib/fetch/global.js @@ -0,0 +1,40 @@ +'use strict' + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} diff --git a/node_modules/undici/lib/fetch/headers.js b/node_modules/undici/lib/fetch/headers.js new file mode 100644 index 0000000..2f1c0be --- /dev/null +++ b/node_modules/undici/lib/fetch/headers.js @@ -0,0 +1,589 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { kHeadersList, kConstruct } = require('../core/symbols') +const { kGuard } = require('./symbols') +const { kEnumerableProperty } = require('../core/util') +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = require('./util') +const { webidl } = require('./webidl') +const assert = require('assert') + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (headers[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (headers[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } + + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) + } + } + + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null + + name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + const value = this[kHeadersMap].get(name.toLowerCase()) + + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return value === undefined ? null : value.value + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } + } + + return headers + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return + } + this[kHeadersList] = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this[kGuard] = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this[kHeadersList].delete(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this[kHeadersList].set(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + this[kHeadersList][kHeadersSortedMap] = headers + + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + + values () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } + + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } + + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) + + return this[kHeadersList] + } +} + +Headers.prototype[Symbol.iterator] = Headers.prototype.entries + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } +}) + +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } + + return webidl.converters['record'](V) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + Headers, + HeadersList +} diff --git a/node_modules/undici/lib/fetch/index.js b/node_modules/undici/lib/fetch/index.js new file mode 100644 index 0000000..dea2069 --- /dev/null +++ b/node_modules/undici/lib/fetch/index.js @@ -0,0 +1,2148 @@ +// https://github.com/Ethan-Arrowood/undici-fetch + +'use strict' + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = require('./response') +const { Headers } = require('./headers') +const { Request, makeRequest } = require('./request') +const zlib = require('zlib') +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = require('./util') +const { kState, kHeaders, kGuard, kRealm } = require('./symbols') +const assert = require('assert') +const { safelyExtractBody } = require('./body') +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = require('./constants') +const { kHeadersList } = require('../core/symbols') +const EE = require('events') +const { Readable, pipeline } = require('stream') +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = require('../core/util') +const { dataURLProcessor, serializeAMimeType } = require('./dataURL') +const { TransformStream } = require('stream/web') +const { getGlobalDispatcher } = require('../global') +const { webidl } = require('./webidl') +const { STATUS_CODES } = require('http') +const GET_OR_HEAD = ['GET', 'HEAD'] + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) + + // 1. Let p be a new promise. + const p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState] + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return Promise.resolve() + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require('buffer').resolveObjectURL + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) + } + + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 + } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) + } + return Promise.resolve() + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') + } + } + + httpRequest.headersList.delete('host') + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } + + let codings = [] + let location = '' + + const headers = new Headers() + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } + } + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } + } + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers[kHeadersList].append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} diff --git a/node_modules/undici/lib/fetch/request.js b/node_modules/undici/lib/fetch/request.js new file mode 100644 index 0000000..6fe4dff --- /dev/null +++ b/node_modules/undici/lib/fetch/request.js @@ -0,0 +1,946 @@ +/* globals AbortController */ + +'use strict' + +const { extractBody, mixinBody, cloneBody } = require('./body') +const { Headers, fill: fillHeaders, HeadersList } = require('./headers') +const { FinalizationRegistry } = require('../compat/dispatcher-weakref')() +const util = require('../core/util') +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = require('./util') +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = require('./constants') +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList, kConstruct } = require('../core/symbols') +const assert = require('assert') +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require('events') + +let TransformStream = globalThis.TransformStream + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return + } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) + + // 4. Set request’s method to method. + request.method = method + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this[kState] = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} + + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = this[kHeaders][kHeadersList] + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const [key, val] of headers) { + headersList.append(key, val) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = require('stream/web').TransformStream + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kConstruct) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason) + } + ) + } + clonedRequestObject[kSignal] = ac.signal + + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} + +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) + +module.exports = { Request, makeRequest } diff --git a/node_modules/undici/lib/fetch/response.js b/node_modules/undici/lib/fetch/response.js new file mode 100644 index 0000000..7338612 --- /dev/null +++ b/node_modules/undici/lib/fetch/response.js @@ -0,0 +1,571 @@ +'use strict' + +const { Headers, HeadersList, fill } = require('./headers') +const { extractBody, cloneBody, mixinBody } = require('./body') +const util = require('../core/util') +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = require('./util') +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = require('./constants') +const { kState, kHeaders, kGuard, kRealm } = require('./symbols') +const { webidl } = require('./webidl') +const { FormData } = require('./formdata') +const { getGlobalOrigin } = require('./global') +const { URLSerializer } = require('./dataURL') +const { kHeadersList, kConstruct } = require('../core/symbols') +const assert = require('assert') +const { types } = require('util') + +const ReadableStream = globalThis.ReadableStream || require('stream/web').ReadableStream +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // TODO + this[kRealm] = { settingsObject: {} } + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + return clonedResponseObject + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) + } + } +} + +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) + +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) + +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } + + return webidl.converters.DOMString(V) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} diff --git a/node_modules/undici/lib/fetch/symbols.js b/node_modules/undici/lib/fetch/symbols.js new file mode 100644 index 0000000..0b947d5 --- /dev/null +++ b/node_modules/undici/lib/fetch/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} diff --git a/node_modules/undici/lib/fetch/util.js b/node_modules/undici/lib/fetch/util.js new file mode 100644 index 0000000..ede4ec4 --- /dev/null +++ b/node_modules/undici/lib/fetch/util.js @@ -0,0 +1,1144 @@ +'use strict' + +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = require('./constants') +const { getGlobalOrigin } = require('./global') +const { performance } = require('perf_hooks') +const { isBlobLike, toUSVString, ReadableStreamFrom } = require('../core/util') +const assert = require('assert') +const { isUint8Array } = require('util/types') + +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = require('crypto') + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} + +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} + +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +function isValidHeaderName (potentialValue) { + return isValidHTTPToken(potentialValue) +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } + + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } + } +} + +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If response is not eligible for integrity validation, return false. + // TODO + + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } + + // 7. Return false. + return false +} + +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' + } + } + return algorithm +} + +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } + + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } + } + + metadataList.length = pos + + return metadataList +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + } + + return true +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +const normalizeMethodRecord = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizeMethodRecord, null) + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + } + + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + + // 2. Let thisValue be the this value. + + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break + } + } + + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} + +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader + + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } +} + +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = require('stream/web').ReadableStream + } + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +const MAXIMUM_ARGUMENT_LENGTH = 65535 + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 + + while (true) { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } + + return url.protocol === 'https:' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) + +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + normalizeMethodRecord, + parseMetadata +} diff --git a/node_modules/undici/lib/fetch/webidl.js b/node_modules/undici/lib/fetch/webidl.js new file mode 100644 index 0000000..6fcf2ab --- /dev/null +++ b/node_modules/undici/lib/fetch/webidl.js @@ -0,0 +1,646 @@ +'use strict' + +const { types } = require('util') +const { hasOwn, toUSVString } = require('./util') + +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) + } +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl +} diff --git a/node_modules/undici/lib/fileapi/encoding.js b/node_modules/undici/lib/fileapi/encoding.js new file mode 100644 index 0000000..1d1d2b6 --- /dev/null +++ b/node_modules/undici/lib/fileapi/encoding.js @@ -0,0 +1,290 @@ +'use strict' + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } +} + +module.exports = { + getEncoding +} diff --git a/node_modules/undici/lib/fileapi/filereader.js b/node_modules/undici/lib/fileapi/filereader.js new file mode 100644 index 0000000..cd36a22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/filereader.js @@ -0,0 +1,344 @@ +'use strict' + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = require('./util') +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = require('./symbols') +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } + + get onerror () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } + + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } + + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) + +module.exports = { + FileReader +} diff --git a/node_modules/undici/lib/fileapi/progressevent.js b/node_modules/undici/lib/fileapi/progressevent.js new file mode 100644 index 0000000..778cf22 --- /dev/null +++ b/node_modules/undici/lib/fileapi/progressevent.js @@ -0,0 +1,78 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total + } +} + +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +]) + +module.exports = { + ProgressEvent +} diff --git a/node_modules/undici/lib/fileapi/symbols.js b/node_modules/undici/lib/fileapi/symbols.js new file mode 100644 index 0000000..dd11746 --- /dev/null +++ b/node_modules/undici/lib/fileapi/symbols.js @@ -0,0 +1,10 @@ +'use strict' + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} diff --git a/node_modules/undici/lib/fileapi/util.js b/node_modules/undici/lib/fileapi/util.js new file mode 100644 index 0000000..1d10899 --- /dev/null +++ b/node_modules/undici/lib/fileapi/util.js @@ -0,0 +1,392 @@ +'use strict' + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = require('./symbols') +const { ProgressEvent } = require('./progressevent') +const { getEncoding } = require('./encoding') +const { DOMException } = require('../fetch/constants') +const { serializeAMimeType, parseMIMEType } = require('../fetch/dataURL') +const { types } = require('util') +const { StringDecoder } = require('string_decoder') +const { btoa } = require('buffer') + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() +} + +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) +} + +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } +} + +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) + + let slice = 0 + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} + +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null +} + +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) + + let offset = 0 + + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} + +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} diff --git a/node_modules/undici/lib/global.js b/node_modules/undici/lib/global.js new file mode 100644 index 0000000..18bfd73 --- /dev/null +++ b/node_modules/undici/lib/global.js @@ -0,0 +1,32 @@ +'use strict' + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = require('./core/errors') +const Agent = require('./agent') + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} diff --git a/node_modules/undici/lib/handler/DecoratorHandler.js b/node_modules/undici/lib/handler/DecoratorHandler.js new file mode 100644 index 0000000..9d70a76 --- /dev/null +++ b/node_modules/undici/lib/handler/DecoratorHandler.js @@ -0,0 +1,35 @@ +'use strict' + +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } + + onConnect (...args) { + return this.handler.onConnect(...args) + } + + onError (...args) { + return this.handler.onError(...args) + } + + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } + + onHeaders (...args) { + return this.handler.onHeaders(...args) + } + + onData (...args) { + return this.handler.onData(...args) + } + + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } +} diff --git a/node_modules/undici/lib/handler/RedirectHandler.js b/node_modules/undici/lib/handler/RedirectHandler.js new file mode 100644 index 0000000..933725f --- /dev/null +++ b/node_modules/undici/lib/handler/RedirectHandler.js @@ -0,0 +1,221 @@ +'use strict' + +const util = require('../core/util') +const { kBodyUsed } = require('../core/symbols') +const assert = require('assert') +const { InvalidArgumentError } = require('../core/errors') +const EE = require('events') + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade) + + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } + } + + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed informations. + */ + + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} + +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler diff --git a/node_modules/undici/lib/handler/RetryHandler.js b/node_modules/undici/lib/handler/RetryHandler.js new file mode 100644 index 0000000..3710447 --- /dev/null +++ b/node_modules/undici/lib/handler/RetryHandler.js @@ -0,0 +1,336 @@ +const assert = require('assert') + +const { kRetryHandlerDefaultRetry } = require('../core/symbols') +const { RequestRetryError } = require('../core/errors') +const { isDisturbed, parseHeaders, parseRangeHeader } = require('../core/util') + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + const diff = new Date(retryAfter).getTime() - current + + return diff +} + +class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {} + + this.dispatch = handlers.dispatch + this.handler = handlers.handler + this.opts = dispatchOpts + this.abort = null + this.aborted = false + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + timeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE' + ] + } + + this.retryCount = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) + } + + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() + } + } + + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) + } + } + + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + timeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + let { counter, currentTimeout } = state + + currentTimeout = + currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout + + // Any code that is not a Undici's originated and allowed to retry + if ( + code && + code !== 'UND_ERR_REQ_RETRY' && + code !== 'UND_ERR_SOCKET' && + !errorCodes.includes(code) + ) { + cb(err) + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers != null && headers['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) + + state.currentTimeout = retryTimeout + + setTimeout(() => cb(null), retryTimeout) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) + + this.retryCount += 1 + + if (statusCode >= 300) { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null + + if (statusCode !== 206) { + return true + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + const { start, size, end = size } = contentRange + + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') + + this.resume = resume + return true + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const { start, size, end = size } = range + + assert( + start != null && Number.isFinite(start) && this.start !== start, + 'content-range mismatch' + ) + assert(Number.isFinite(start)) + assert( + end != null && Number.isFinite(end) && this.end !== end, + 'invalid content-length' + ) + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const err = new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + + this.abort(err) + + return false + } + + onData (chunk) { + this.start += chunk.length + + return this.handler.onData(chunk) + } + + onComplete (rawTrailers) { + this.retryCount = 0 + return this.handler.onComplete(rawTrailers) + } + + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ) + + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ''}` + } + } + } + + try { + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } + } + } +} + +module.exports = RetryHandler diff --git a/node_modules/undici/lib/interceptor/redirectInterceptor.js b/node_modules/undici/lib/interceptor/redirectInterceptor.js new file mode 100644 index 0000000..7cc035e --- /dev/null +++ b/node_modules/undici/lib/interceptor/redirectInterceptor.js @@ -0,0 +1,21 @@ +'use strict' + +const RedirectHandler = require('../handler/RedirectHandler') + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor diff --git a/node_modules/undici/lib/llhttp/constants.d.ts b/node_modules/undici/lib/llhttp/constants.d.ts new file mode 100644 index 0000000..b75ab1b --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.d.ts @@ -0,0 +1,199 @@ +import { IEnumMap } from './utils'; +export declare type HTTPMode = 'loose' | 'strict'; +export declare enum ERROR { + OK = 0, + INTERNAL = 1, + STRICT = 2, + LF_EXPECTED = 3, + UNEXPECTED_CONTENT_LENGTH = 4, + CLOSED_CONNECTION = 5, + INVALID_METHOD = 6, + INVALID_URL = 7, + INVALID_CONSTANT = 8, + INVALID_VERSION = 9, + INVALID_HEADER_TOKEN = 10, + INVALID_CONTENT_LENGTH = 11, + INVALID_CHUNK_SIZE = 12, + INVALID_STATUS = 13, + INVALID_EOF_STATE = 14, + INVALID_TRANSFER_ENCODING = 15, + CB_MESSAGE_BEGIN = 16, + CB_HEADERS_COMPLETE = 17, + CB_MESSAGE_COMPLETE = 18, + CB_CHUNK_HEADER = 19, + CB_CHUNK_COMPLETE = 20, + PAUSED = 21, + PAUSED_UPGRADE = 22, + PAUSED_H2_UPGRADE = 23, + USER = 24 +} +export declare enum TYPE { + BOTH = 0, + REQUEST = 1, + RESPONSE = 2 +} +export declare enum FLAGS { + CONNECTION_KEEP_ALIVE = 1, + CONNECTION_CLOSE = 2, + CONNECTION_UPGRADE = 4, + CHUNKED = 8, + UPGRADE = 16, + CONTENT_LENGTH = 32, + SKIPBODY = 64, + TRAILING = 128, + TRANSFER_ENCODING = 512 +} +export declare enum LENIENT_FLAGS { + HEADERS = 1, + CHUNKED_LENGTH = 2, + KEEP_ALIVE = 4 +} +export declare enum METHODS { + DELETE = 0, + GET = 1, + HEAD = 2, + POST = 3, + PUT = 4, + CONNECT = 5, + OPTIONS = 6, + TRACE = 7, + COPY = 8, + LOCK = 9, + MKCOL = 10, + MOVE = 11, + PROPFIND = 12, + PROPPATCH = 13, + SEARCH = 14, + UNLOCK = 15, + BIND = 16, + REBIND = 17, + UNBIND = 18, + ACL = 19, + REPORT = 20, + MKACTIVITY = 21, + CHECKOUT = 22, + MERGE = 23, + 'M-SEARCH' = 24, + NOTIFY = 25, + SUBSCRIBE = 26, + UNSUBSCRIBE = 27, + PATCH = 28, + PURGE = 29, + MKCALENDAR = 30, + LINK = 31, + UNLINK = 32, + SOURCE = 33, + PRI = 34, + DESCRIBE = 35, + ANNOUNCE = 36, + SETUP = 37, + PLAY = 38, + PAUSE = 39, + TEARDOWN = 40, + GET_PARAMETER = 41, + SET_PARAMETER = 42, + REDIRECT = 43, + RECORD = 44, + FLUSH = 45 +} +export declare const METHODS_HTTP: METHODS[]; +export declare const METHODS_ICE: METHODS[]; +export declare const METHODS_RTSP: METHODS[]; +export declare const METHOD_MAP: IEnumMap; +export declare const H_METHOD_MAP: IEnumMap; +export declare enum FINISH { + SAFE = 0, + SAFE_WITH_CB = 1, + UNSAFE = 2 +} +export declare type CharList = Array; +export declare const ALPHA: CharList; +export declare const NUM_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const HEX_MAP: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; + A: number; + B: number; + C: number; + D: number; + E: number; + F: number; + a: number; + b: number; + c: number; + d: number; + e: number; + f: number; +}; +export declare const NUM: CharList; +export declare const ALPHANUM: CharList; +export declare const MARK: CharList; +export declare const USERINFO_CHARS: CharList; +export declare const STRICT_URL_CHAR: CharList; +export declare const URL_CHAR: CharList; +export declare const HEX: CharList; +export declare const STRICT_TOKEN: CharList; +export declare const TOKEN: CharList; +export declare const HEADER_CHARS: CharList; +export declare const CONNECTION_TOKEN_CHARS: CharList; +export declare const MAJOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare const MINOR: { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 5: number; + 6: number; + 7: number; + 8: number; + 9: number; +}; +export declare enum HEADER_STATE { + GENERAL = 0, + CONNECTION = 1, + CONTENT_LENGTH = 2, + TRANSFER_ENCODING = 3, + UPGRADE = 4, + CONNECTION_KEEP_ALIVE = 5, + CONNECTION_CLOSE = 6, + CONNECTION_UPGRADE = 7, + TRANSFER_ENCODING_CHUNKED = 8 +} +export declare const SPECIAL_HEADERS: { + connection: HEADER_STATE; + 'content-length': HEADER_STATE; + 'proxy-connection': HEADER_STATE; + 'transfer-encoding': HEADER_STATE; + upgrade: HEADER_STATE; +}; diff --git a/node_modules/undici/lib/llhttp/constants.js b/node_modules/undici/lib/llhttp/constants.js new file mode 100644 index 0000000..fb0b5a2 --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js @@ -0,0 +1,278 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = require("./utils"); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/constants.js.map b/node_modules/undici/lib/llhttp/constants.js.map new file mode 100644 index 0000000..6ac54bc --- /dev/null +++ b/node_modules/undici/lib/llhttp/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/llhttp/constants.ts"],"names":[],"mappings":";;;AAAA,mCAA8C;AAI9C,YAAY;AAEZ,IAAY,KA6BX;AA7BD,WAAY,KAAK;IACf,6BAAM,CAAA;IACN,yCAAQ,CAAA;IACR,qCAAM,CAAA;IACN,+CAAW,CAAA;IACX,2EAAyB,CAAA;IACzB,2DAAiB,CAAA;IACjB,qDAAc,CAAA;IACd,+CAAW,CAAA;IACX,yDAAgB,CAAA;IAChB,uDAAe,CAAA;IACf,kEAAoB,CAAA;IACpB,sEAAsB,CAAA;IACtB,8DAAkB,CAAA;IAClB,sDAAc,CAAA;IACd,4DAAiB,CAAA;IACjB,4EAAyB,CAAA;IAEzB,0DAAgB,CAAA;IAChB,gEAAmB,CAAA;IACnB,gEAAmB,CAAA;IACnB,wDAAe,CAAA;IACf,4DAAiB,CAAA;IAEjB,sCAAM,CAAA;IACN,sDAAc,CAAA;IACd,4DAAiB,CAAA;IAEjB,kCAAI,CAAA;AACN,CAAC,EA7BW,KAAK,GAAL,aAAK,KAAL,aAAK,QA6BhB;AAED,IAAY,IAIX;AAJD,WAAY,IAAI;IACd,+BAAQ,CAAA;IACR,qCAAO,CAAA;IACP,uCAAQ,CAAA;AACV,CAAC,EAJW,IAAI,GAAJ,YAAI,KAAJ,YAAI,QAIf;AAED,IAAY,KAWX;AAXD,WAAY,KAAK;IACf,mEAA8B,CAAA;IAC9B,yDAAyB,CAAA;IACzB,6DAA2B,CAAA;IAC3B,uCAAgB,CAAA;IAChB,wCAAgB,CAAA;IAChB,sDAAuB,CAAA;IACvB,0CAAiB,CAAA;IACjB,2CAAiB,CAAA;IACjB,mBAAmB;IACnB,6DAA0B,CAAA;AAC5B,CAAC,EAXW,KAAK,GAAL,aAAK,KAAL,aAAK,QAWhB;AAED,IAAY,aAIX;AAJD,WAAY,aAAa;IACvB,uDAAgB,CAAA;IAChB,qEAAuB,CAAA;IACv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AI,CAAC,KAAK,GAAG,EAAE;QACb,oBAAY,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;KACtB;CACF;AAED,aAAa;AACA,QAAA,sBAAsB,GACjC,oBAAY,CAAC,MAAM,CAAC,CAAC,CAAkB,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;AAE3C,QAAA,KAAK,GAAG,eAAO,CAAC;AAChB,QAAA,KAAK,GAAG,aAAK,CAAC;AAE3B,IAAY,YAWX;AAXD,WAAY,YAAY;IACtB,qDAAW,CAAA;IACX,2DAAU,CAAA;IACV,mEAAc,CAAA;IACd,yEAAiB,CAAA;IACjB,qDAAO,CAAA;IAEP,iFAAqB,CAAA;IACrB,uEAAgB,CAAA;IAChB,2EAAkB,CAAA;IAClB,yFAAyB,CAAA;AAC3B,CAAC,EAXW,YAAY,GAAZ,oBAAY,KAAZ,oBAAY,QAWvB;AAEY,QAAA,eAAe,GAAG;IAC7B,YAAY,EAAE,YAAY,CAAC,UAAU;IACrC,gBAAgB,EAAE,YAAY,CAAC,cAAc;IAC7C,kBAAkB,EAAE,YAAY,CAAC,UAAU;IAC3C,mBAAmB,EAAE,YAAY,CAAC,iBAAiB;IACnD,SAAS,EAAE,YAAY,CAAC,OAAO;CAChC,CAAC"} \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/llhttp-wasm.js b/node_modules/undici/lib/llhttp/llhttp-wasm.js new file mode 100644 index 0000000..ad4682c --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp-wasm.js @@ -0,0 +1 @@ +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZX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ua2VkX2xlbmd0aAAjHWxsaHR0cF9zZXRfbGVuaWVudF9rZWVwX2FsaXZlACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQA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C0AK0UNAEEAIQMgAC8BMCIEQQJxRQ0BDAILQQAhAyAALwEwIgRBAXFFDQELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ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AkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/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ACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBD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DAwMDAwMDAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8=' diff --git a/node_modules/undici/lib/llhttp/llhttp.wasm b/node_modules/undici/lib/llhttp/llhttp.wasm new file mode 100644 index 0000000..fe63282 Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp.wasm differ diff --git a/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js new file mode 100644 index 0000000..017e247 --- /dev/null +++ b/node_modules/undici/lib/llhttp/llhttp_simd-wasm.js @@ -0,0 +1 @@ +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQ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Tk3MS8tJyspCrLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIABBnH9qDvQDY2IAAWFhYWFhYQIDBAVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhY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xQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC0kBAXsgAEEQav0MAAAAAAAAAAAAAAAAAAAAACIB/QsDACAAIAH9CwMAIABBMGogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ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w3dAUHDASEQDP4DCyABIgEgAkcNkAFB9wAhEAz9AwsgASIBIAJHDYYBQe8AIRAM/AMLIAEiASACRw1/QeoAIRAM+wMLIAEiASACRw17QegAIRAM+gMLIAEiASACRw14QeYAIRAM+QMLIAEiASACRw0aQRghEAz4AwsgASIBIAJHDRRBEiEQDPcDCyABIgEgAkcNWUHFACEQDPYDCyABIgEgAkcNSkE/IRAM9QMLIAEiASACRw1IQTwhEAz0AwsgASIBIAJHDUFBMSEQDPMDCyAALQAuQQFGDesDDIcCCyAAIAEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgs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IAAgATYCFCAAIAQ2AgxBACEQDLsBCwJAIAEtAABBUGoiEEH/AXFBCk8NACAAIBA6ACogAUEBaiEBQc8AIRAMogELIAAoAgQhBCAAQQA2AgQCQCAAIAQgARCtgICAACIEDQAgASEBDKcBCyAAQd4ANgIcIAAgATYCFCAAIAQ2AgxBACEQDLoBCyAAQQA2AgAgF0EBaiEBAkAgAC0AKUEjTw0AIAEhAQxZCyAAQQA2AhwgACABNgIUIABB04mAgAA2AhAgAEEINgIMQQAhEAy5AQsgAEEANgIAC0EAIRAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcI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Q1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' diff --git a/node_modules/undici/lib/llhttp/llhttp_simd.wasm b/node_modules/undici/lib/llhttp/llhttp_simd.wasm new file mode 100644 index 0000000..7aa0b55 Binary files /dev/null and b/node_modules/undici/lib/llhttp/llhttp_simd.wasm differ diff --git a/node_modules/undici/lib/llhttp/utils.d.ts b/node_modules/undici/lib/llhttp/utils.d.ts new file mode 100644 index 0000000..15497f3 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.d.ts @@ -0,0 +1,4 @@ +export interface IEnumMap { + [key: string]: number; +} +export declare function enumToMap(obj: any): IEnumMap; diff --git a/node_modules/undici/lib/llhttp/utils.js b/node_modules/undici/lib/llhttp/utils.js new file mode 100644 index 0000000..8a32e56 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js @@ -0,0 +1,15 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; +} +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/utils.js.map b/node_modules/undici/lib/llhttp/utils.js.map new file mode 100644 index 0000000..2d7c356 --- /dev/null +++ b/node_modules/undici/lib/llhttp/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/llhttp/utils.ts"],"names":[],"mappings":";;;AAIA,SAAgB,SAAS,CAAC,GAAQ;IAChC,MAAM,GAAG,GAAa,EAAE,CAAC;IAEzB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;QAC/B,MAAM,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,CAAC;QACvB,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,GAAG,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;SAClB;IACH,CAAC,CAAC,CAAC;IAEH,OAAO,GAAG,CAAC;AACb,CAAC;AAXD,8BAWC"} \ No newline at end of file diff --git a/node_modules/undici/lib/llhttp/wasm_build_env.txt b/node_modules/undici/lib/llhttp/wasm_build_env.txt new file mode 100644 index 0000000..5f478b5 --- /dev/null +++ b/node_modules/undici/lib/llhttp/wasm_build_env.txt @@ -0,0 +1,32 @@ +alpine-baselayout-data-3.4.0-r0 +musl-1.2.3-r4 +busybox-1.35.0-r29 +busybox-binsh-1.35.0-r29 +alpine-baselayout-3.4.0-r0 +alpine-keys-2.4-r1 +ca-certificates-bundle-20220614-r4 +libcrypto3-3.0.8-r3 +libssl3-3.0.8-r3 +ssl_client-1.35.0-r29 +zlib-1.2.13-r0 +apk-tools-2.12.10-r1 +scanelf-1.3.5-r1 +musl-utils-1.2.3-r4 +libc-utils-0.7.2-r3 +libgcc-12.2.1_git20220924-r4 +libstdc++-12.2.1_git20220924-r4 +libffi-3.4.4-r0 +xz-libs-5.2.9-r0 +libxml2-2.10.4-r0 +zstd-libs-1.5.5-r0 +llvm15-libs-15.0.7-r0 +clang15-libs-15.0.7-r0 +libstdc++-dev-12.2.1_git20220924-r4 +clang15-15.0.7-r0 +lld-libs-15.0.7-r0 +lld-15.0.7-r0 +wasi-libc-0.20220525-r1 +wasi-libcxx-15.0.7-r0 +wasi-libcxxabi-15.0.7-r0 +wasi-compiler-rt-15.0.7-r0 +wasi-sdk-16-r0 diff --git a/node_modules/undici/lib/mock/mock-agent.js b/node_modules/undici/lib/mock/mock-agent.js new file mode 100644 index 0000000..828e8af --- /dev/null +++ b/node_modules/undici/lib/mock/mock-agent.js @@ -0,0 +1,171 @@ +'use strict' + +const { kClients } = require('../core/symbols') +const Agent = require('../agent') +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = require('./mock-symbols') +const MockClient = require('./mock-client') +const MockPool = require('./mock-pool') +const { matchValue, buildMockOptions } = require('./mock-utils') +const { InvalidArgumentError, UndiciError } = require('../core/errors') +const Dispatcher = require('../dispatcher') +const Pluralizer = require('./pluralizer') +const PendingInterceptorsFormatter = require('./pending-interceptors-formatter') + +class FakeWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value + } +} + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } +} + +module.exports = MockAgent diff --git a/node_modules/undici/lib/mock/mock-client.js b/node_modules/undici/lib/mock/mock-client.js new file mode 100644 index 0000000..5f31215 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-client.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Client = require('../client') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient diff --git a/node_modules/undici/lib/mock/mock-errors.js b/node_modules/undici/lib/mock/mock-errors.js new file mode 100644 index 0000000..5442c0e --- /dev/null +++ b/node_modules/undici/lib/mock/mock-errors.js @@ -0,0 +1,17 @@ +'use strict' + +const { UndiciError } = require('../core/errors') + +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} + +module.exports = { + MockNotMatchedError +} diff --git a/node_modules/undici/lib/mock/mock-interceptor.js b/node_modules/undici/lib/mock/mock-interceptor.js new file mode 100644 index 0000000..781e477 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-interceptor.js @@ -0,0 +1,206 @@ +'use strict' + +const { getResponseData, buildKey, addMockDispatch } = require('./mock-utils') +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = require('./mock-symbols') +const { InvalidArgumentError } = require('../core/errors') +const { buildURL } = require('../core/util') + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') + } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope diff --git a/node_modules/undici/lib/mock/mock-pool.js b/node_modules/undici/lib/mock/mock-pool.js new file mode 100644 index 0000000..0a3a7cd --- /dev/null +++ b/node_modules/undici/lib/mock/mock-pool.js @@ -0,0 +1,59 @@ +'use strict' + +const { promisify } = require('util') +const Pool = require('../pool') +const { buildMockDispatch } = require('./mock-utils') +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = require('./mock-symbols') +const { MockInterceptor } = require('./mock-interceptor') +const Symbols = require('../core/symbols') +const { InvalidArgumentError } = require('../core/errors') + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool diff --git a/node_modules/undici/lib/mock/mock-symbols.js b/node_modules/undici/lib/mock/mock-symbols.js new file mode 100644 index 0000000..8c4cbb6 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-symbols.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') +} diff --git a/node_modules/undici/lib/mock/mock-utils.js b/node_modules/undici/lib/mock/mock-utils.js new file mode 100644 index 0000000..42ea185 --- /dev/null +++ b/node_modules/undici/lib/mock/mock-utils.js @@ -0,0 +1,351 @@ +'use strict' + +const { MockNotMatchedError } = require('./mock-errors') +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = require('./mock-symbols') +const { buildURL, nop } = require('../core/util') +const { STATUS_CODES } = require('http') +const { + types: { + isPromise + } +} = require('util') + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?') + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} diff --git a/node_modules/undici/lib/mock/pending-interceptors-formatter.js b/node_modules/undici/lib/mock/pending-interceptors-formatter.js new file mode 100644 index 0000000..1bc7539 --- /dev/null +++ b/node_modules/undici/lib/mock/pending-interceptors-formatter.js @@ -0,0 +1,40 @@ +'use strict' + +const { Transform } = require('stream') +const { Console } = require('console') + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} diff --git a/node_modules/undici/lib/mock/pluralizer.js b/node_modules/undici/lib/mock/pluralizer.js new file mode 100644 index 0000000..47f150b --- /dev/null +++ b/node_modules/undici/lib/mock/pluralizer.js @@ -0,0 +1,29 @@ +'use strict' + +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} + +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' +} + +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } +} diff --git a/node_modules/undici/lib/node/fixed-queue.js b/node_modules/undici/lib/node/fixed-queue.js new file mode 100644 index 0000000..3572681 --- /dev/null +++ b/node_modules/undici/lib/node/fixed-queue.js @@ -0,0 +1,117 @@ +/* eslint-disable */ + +'use strict' + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +} + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; diff --git a/node_modules/undici/lib/pool-base.js b/node_modules/undici/lib/pool-base.js new file mode 100644 index 0000000..2a909ee --- /dev/null +++ b/node_modules/undici/lib/pool-base.js @@ -0,0 +1,194 @@ +'use strict' + +const DispatcherBase = require('./dispatcher-base') +const FixedQueue = require('./node/fixed-queue') +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = require('./core/symbols') +const PoolStats = require('./pool-stats') + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') + +class PoolBase extends DispatcherBase { + constructor () { + super() + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + return Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} diff --git a/node_modules/undici/lib/pool-stats.js b/node_modules/undici/lib/pool-stats.js new file mode 100644 index 0000000..b4af8ae --- /dev/null +++ b/node_modules/undici/lib/pool-stats.js @@ -0,0 +1,34 @@ +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = require('./core/symbols') +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats diff --git a/node_modules/undici/lib/pool.js b/node_modules/undici/lib/pool.js new file mode 100644 index 0000000..e3cd339 --- /dev/null +++ b/node_modules/undici/lib/pool.js @@ -0,0 +1,94 @@ +'use strict' + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = require('./pool-base') +const Client = require('./client') +const { + InvalidArgumentError +} = require('./core/errors') +const util = require('./core/util') +const { kUrl, kInterceptors } = require('./core/symbols') +const buildConnector = require('./core/connect') + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool diff --git a/node_modules/undici/lib/proxy-agent.js b/node_modules/undici/lib/proxy-agent.js new file mode 100644 index 0000000..e3c0f6f --- /dev/null +++ b/node_modules/undici/lib/proxy-agent.js @@ -0,0 +1,189 @@ +'use strict' + +const { kProxy, kClose, kDestroy, kInterceptors } = require('./core/symbols') +const { URL } = require('url') +const Agent = require('./agent') +const Pool = require('./pool') +const DispatcherBase = require('./dispatcher-base') +const { InvalidArgumentError, RequestAbortedError } = require('./core/errors') +const buildConnector = require('./core/connect') + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host, username, password } = resolvedUrl + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + }) + } + + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent diff --git a/node_modules/undici/lib/timers.js b/node_modules/undici/lib/timers.js new file mode 100644 index 0000000..5782217 --- /dev/null +++ b/node_modules/undici/lib/timers.js @@ -0,0 +1,97 @@ +'use strict' + +let fastNow = Date.now() +let fastNowTimeout + +const fastTimers = [] + +function onTimeout () { + fastNow = Date.now() + + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] + + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } + + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } + + if (fastTimers.length > 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } +} + +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 + + this.refresh() + } + + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } + + this.state = 0 + } + + clear () { + this.state = -1 + } +} + +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } +} diff --git a/node_modules/undici/lib/websocket/connection.js b/node_modules/undici/lib/websocket/connection.js new file mode 100644 index 0000000..e0fa697 --- /dev/null +++ b/node_modules/undici/lib/websocket/connection.js @@ -0,0 +1,291 @@ +'use strict' + +const diagnosticsChannel = require('diagnostics_channel') +const { uid, states } = require('./constants') +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = require('./symbols') +const { fireEvent, failWebsocketConnection } = require('./util') +const { CloseEvent } = require('./events') +const { makeRequest } = require('../fetch/request') +const { fetching } = require('../fetch/index') +const { Headers } = require('../fetch/headers') +const { getGlobalDispatcher } = require('../global') +const { kHeadersList } = require('../core/symbols') + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('crypto') +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList] + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response) + } + }) + + return controller +} + +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } +} + +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() +} + +module.exports = { + establishWebSocketConnection +} diff --git a/node_modules/undici/lib/websocket/constants.js b/node_modules/undici/lib/websocket/constants.js new file mode 100644 index 0000000..406b8e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/constants.js @@ -0,0 +1,51 @@ +'use strict' + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer +} diff --git a/node_modules/undici/lib/websocket/events.js b/node_modules/undici/lib/websocket/events.js new file mode 100644 index 0000000..621a226 --- /dev/null +++ b/node_modules/undici/lib/websocket/events.js @@ -0,0 +1,303 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { kEnumerableProperty } = require('../core/util') +const { MessagePort } = require('worker_threads') + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent +} diff --git a/node_modules/undici/lib/websocket/frame.js b/node_modules/undici/lib/websocket/frame.js new file mode 100644 index 0000000..d867ad1 --- /dev/null +++ b/node_modules/undici/lib/websocket/frame.js @@ -0,0 +1,73 @@ +'use strict' + +const { maxUnsigned16Bit } = require('./constants') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = require('crypto') +} catch { + +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } + + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } + + return buffer + } +} + +module.exports = { + WebsocketFrameSend +} diff --git a/node_modules/undici/lib/websocket/receiver.js b/node_modules/undici/lib/websocket/receiver.js new file mode 100644 index 0000000..bdd2031 --- /dev/null +++ b/node_modules/undici/lib/websocket/receiver.js @@ -0,0 +1,344 @@ +'use strict' + +const { Writable } = require('stream') +const diagnosticsChannel = require('diagnostics_channel') +const { parserStates, opcodes, states, emptyBuffer } = require('./constants') +const { kReadyState, kSentClose, kResponse, kReceivedClose } = require('./symbols') +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = require('./util') +const { WebsocketFrameSend } = require('./frame') + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + constructor (ws) { + super() + + this.ws = ws + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + const payloadLength = buffer[1] & 0x7F + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } + + const body = this.consume(payloadLength) + + this.#info.closeInfo = this.parseCloseBody(false, body) + + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true + + this.end() + + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + const body = this.consume(payloadLength) + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } + + this.#state = parserStates.INFO + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + const body = this.consume(payloadLength) + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk + + const body = this.consume(this.#info.payloadLength) + + this.#fragments.push(body) + + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) + + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + + this.#info = {} + this.#fragments.length = 0 + } + + this.#state = parserStates.INFO + } + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n) + let offset = 0 + + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } + + this.#byteOffset -= n + + return buffer + } + + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } + + return { code } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return null + } + + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } + + return { code, reason } + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} diff --git a/node_modules/undici/lib/websocket/symbols.js b/node_modules/undici/lib/websocket/symbols.js new file mode 100644 index 0000000..11d03e3 --- /dev/null +++ b/node_modules/undici/lib/websocket/symbols.js @@ -0,0 +1,12 @@ +'use strict' + +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} diff --git a/node_modules/undici/lib/websocket/util.js b/node_modules/undici/lib/websocket/util.js new file mode 100644 index 0000000..6c59b2c --- /dev/null +++ b/node_modules/undici/lib/websocket/util.js @@ -0,0 +1,200 @@ +'use strict' + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols') +const { states, opcodes } = require('./constants') +const { MessageEvent, ErrorEvent } = require('./events') + +/* globals Blob */ + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws + + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } + + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} + +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived +} diff --git a/node_modules/undici/lib/websocket/websocket.js b/node_modules/undici/lib/websocket/websocket.js new file mode 100644 index 0000000..e4aa58f --- /dev/null +++ b/node_modules/undici/lib/websocket/websocket.js @@ -0,0 +1,641 @@ +'use strict' + +const { webidl } = require('../fetch/webidl') +const { DOMException } = require('../fetch/constants') +const { URLSerializer } = require('../fetch/dataURL') +const { getGlobalOrigin } = require('../fetch/global') +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = require('./constants') +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = require('./symbols') +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = require('./util') +const { establishWebSocketConnection } = require('./connection') +const { WebsocketFrameSend } = require('./frame') +const { ByteParser } = require('./receiver') +const { kEnumerableProperty, isBlobLike } = require('../core/util') +const { getGlobalDispatcher } = require('../global') +const { types } = require('util') + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) + + // 11. Let client be this's relevant settings object. + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING + } + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) + + data = webidl.converters.WebSocketSendData(data) + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V) +} + +// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} diff --git a/node_modules/undici/package.json b/node_modules/undici/package.json new file mode 100644 index 0000000..65a2d98 --- /dev/null +++ b/node_modules/undici/package.json @@ -0,0 +1,167 @@ +{ + "name": "undici", + "version": "5.28.4", + "description": "An HTTP/1.1 client, written from scratch for Node.js", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ], + "keywords": [ + "fetch", + "http", + "https", + "promise", + "request", + "curl", + "wget", + "xhr", + "whatwg" + ], + "main": "index.js", + "types": "index.d.ts", + "files": [ + "*.d.ts", + "index.js", + "index-fetch.js", + "lib", + "types", + "docs" + ], + "scripts": { + "build:node": "npx esbuild@0.19.4 index-fetch.js --bundle --platform=node --outfile=undici-fetch.js --define:esbuildDetection=1 --keep-names", + "prebuild:wasm": "node build/wasm.js --prebuild", + "build:wasm": "node build/wasm.js --docker", + "lint": "standard | snazzy", + "lint:fix": "standard --fix | snazzy", + "test": "node scripts/generate-pem && npm run test:tap && npm run test:node-fetch && npm run test:fetch && npm run test:cookies && npm run test:wpt && npm run test:websocket && npm run test:jest && npm run test:typescript", + "test:cookies": "node scripts/verifyVersion 16 || tap test/cookie/*.js", + "test:node-fetch": "node scripts/verifyVersion.js 16 || mocha --exit test/node-fetch", + "test:fetch": "node scripts/verifyVersion.js 16 || (npm run build:node && tap --expose-gc test/fetch/*.js && tap test/webidl/*.js)", + "test:jest": "node scripts/verifyVersion.js 14 || jest", + "test:tap": "tap test/*.js test/diagnostics-channel/*.js", + "test:tdd": "tap test/*.js test/diagnostics-channel/*.js -w", + "test:typescript": "node scripts/verifyVersion.js 14 || tsd && tsc --skipLibCheck test/imports/undici-import.ts", + "test:websocket": "node scripts/verifyVersion.js 18 || tap test/websocket/*.js", + "test:wpt": "node scripts/verifyVersion 18 || (node test/wpt/start-fetch.mjs && node test/wpt/start-FileAPI.mjs && node test/wpt/start-mimesniff.mjs && node test/wpt/start-xhr.mjs && node test/wpt/start-websockets.mjs)", + "coverage": "nyc --reporter=text --reporter=html npm run test", + "coverage:ci": "nyc --reporter=lcov npm run test", + "bench": "PORT=3042 concurrently -k -s first npm:bench:server npm:bench:run", + "bench:server": "node benchmarks/server.js", + "prebench:run": "node benchmarks/wait.js", + "bench:run": "CONNECTIONS=1 node benchmarks/benchmark.js; CONNECTIONS=50 node benchmarks/benchmark.js", + "serve:website": "docsify serve .", + "prepare": "husky install", + "fuzz": "jsfuzz test/fuzzing/fuzz.js corpus" + }, + "devDependencies": { + "@sinonjs/fake-timers": "^11.1.0", + "@types/node": "^18.0.3", + "abort-controller": "^3.0.0", + "atomic-sleep": "^1.0.0", + "chai": "^4.3.4", + "chai-as-promised": "^7.1.1", + "chai-iterator": "^3.0.2", + "chai-string": "^1.5.0", + "concurrently": "^8.0.1", + "cronometro": "^1.0.5", + "delay": "^5.0.0", + "dns-packet": "^5.4.0", + "docsify-cli": "^4.4.3", + "form-data": "^4.0.0", + "formdata-node": "^4.3.1", + "https-pem": "^3.0.0", + "husky": "^8.0.1", + "import-fresh": "^3.3.0", + "jest": "^29.0.2", + "jsdom": "^23.0.0", + "jsfuzz": "^1.0.15", + "mocha": "^10.0.0", + "mockttp": "^3.9.2", + "p-timeout": "^3.2.0", + "pre-commit": "^1.2.2", + "proxy": "^1.0.2", + "proxyquire": "^2.1.3", + "semver": "^7.5.4", + "sinon": "^17.0.1", + "snazzy": "^9.0.0", + "standard": "^17.0.0", + "table": "^6.8.0", + "tap": "^16.1.0", + "tsd": "^0.29.0", + "typescript": "^5.0.2", + "wait-on": "^7.0.1", + "ws": "^8.11.0" + }, + "engines": { + "node": ">=14.0" + }, + "standard": { + "env": [ + "mocha" + ], + "ignore": [ + "lib/llhttp/constants.js", + "lib/llhttp/utils.js", + "test/wpt/tests" + ] + }, + "tsd": { + "directory": "test/types", + "compilerOptions": { + "esModuleInterop": true, + "lib": [ + "esnext" + ] + } + }, + "jest": { + "testMatch": [ + "/test/jest/**" + ] + }, + "dependencies": { + "@fastify/busboy": "^2.0.0" + } +} diff --git a/node_modules/undici/types/README.md b/node_modules/undici/types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici/types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici/types/agent.d.ts b/node_modules/undici/types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici/types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici/types/api.d.ts b/node_modules/undici/types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici/types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici/types/balanced-pool.d.ts b/node_modules/undici/types/balanced-pool.d.ts new file mode 100644 index 0000000..d1e9375 --- /dev/null +++ b/node_modules/undici/types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/node_modules/undici/types/cache.d.ts b/node_modules/undici/types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici/types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici/types/client.d.ts b/node_modules/undici/types/client.d.ts new file mode 100644 index 0000000..56e78cc --- /dev/null +++ b/node_modules/undici/types/client.d.ts @@ -0,0 +1,97 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overridden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici/types/connector.d.ts b/node_modules/undici/types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici/types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici/types/content-type.d.ts b/node_modules/undici/types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici/types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici/types/cookies.d.ts b/node_modules/undici/types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici/types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici/types/diagnostics-channel.d.ts b/node_modules/undici/types/diagnostics-channel.d.ts new file mode 100644 index 0000000..85d4482 --- /dev/null +++ b/node_modules/undici/types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici/types/dispatcher.d.ts b/node_modules/undici/types/dispatcher.d.ts new file mode 100644 index 0000000..efc53ee --- /dev/null +++ b/node_modules/undici/types/dispatcher.d.ts @@ -0,0 +1,241 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void, statusText: string): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici/types/errors.d.ts b/node_modules/undici/types/errors.d.ts new file mode 100644 index 0000000..7923ddd --- /dev/null +++ b/node_modules/undici/types/errors.d.ts @@ -0,0 +1,128 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/node_modules/undici/types/fetch.d.ts b/node_modules/undici/types/fetch.d.ts new file mode 100644 index 0000000..440f2b0 --- /dev/null +++ b/node_modules/undici/types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal | null + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici/types/file.d.ts b/node_modules/undici/types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici/types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/filereader.d.ts b/node_modules/undici/types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici/types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici/types/formdata.d.ts b/node_modules/undici/types/formdata.d.ts new file mode 100644 index 0000000..df29a57 --- /dev/null +++ b/node_modules/undici/types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici/types/global-dispatcher.d.ts b/node_modules/undici/types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici/types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici/types/global-origin.d.ts b/node_modules/undici/types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici/types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici/types/handlers.d.ts b/node_modules/undici/types/handlers.d.ts new file mode 100644 index 0000000..eb4f5a9 --- /dev/null +++ b/node_modules/undici/types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/node_modules/undici/types/header.d.ts b/node_modules/undici/types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici/types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici/types/index.d.ts b/node_modules/undici/types/index.d.ts new file mode 100644 index 0000000..0ea8bdc --- /dev/null +++ b/node_modules/undici/types/index.d.ts @@ -0,0 +1,65 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import RetryHandler from'./retry-handler' +import { request, pipeline, stream, connect, upgrade } from './api' + +export * from './cookies' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler, RetryHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var RetryHandler: typeof import ('./retry-handler').default + var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; +} diff --git a/node_modules/undici/types/interceptors.d.ts b/node_modules/undici/types/interceptors.d.ts new file mode 100644 index 0000000..047ac17 --- /dev/null +++ b/node_modules/undici/types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/node_modules/undici/types/mock-agent.d.ts b/node_modules/undici/types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici/types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici/types/mock-client.d.ts b/node_modules/undici/types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici/types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/mock-errors.d.ts b/node_modules/undici/types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici/types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici/types/mock-interceptor.d.ts b/node_modules/undici/types/mock-interceptor.d.ts new file mode 100644 index 0000000..6b3961c --- /dev/null +++ b/node_modules/undici/types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici/types/mock-pool.d.ts b/node_modules/undici/types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici/types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici/types/patch.d.ts b/node_modules/undici/types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici/types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici/types/pool-stats.d.ts b/node_modules/undici/types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici/types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici/types/pool.d.ts b/node_modules/undici/types/pool.d.ts new file mode 100644 index 0000000..7747d48 --- /dev/null +++ b/node_modules/undici/types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici/types/proxy-agent.d.ts b/node_modules/undici/types/proxy-agent.d.ts new file mode 100644 index 0000000..96b2638 --- /dev/null +++ b/node_modules/undici/types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici/types/readable.d.ts b/node_modules/undici/types/readable.d.ts new file mode 100644 index 0000000..4549a8c --- /dev/null +++ b/node_modules/undici/types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici/types/retry-handler.d.ts b/node_modules/undici/types/retry-handler.d.ts new file mode 100644 index 0000000..0528eb4 --- /dev/null +++ b/node_modules/undici/types/retry-handler.d.ts @@ -0,0 +1,116 @@ +import Dispatcher from "./dispatcher"; + +export default RetryHandler; + +declare class RetryHandler implements Dispatcher.DispatchHandlers { + constructor( + options: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }, + retryHandlers: RetryHandler.RetryHandlers + ); +} + +declare namespace RetryHandler { + export type RetryState = { counter: number; currentTimeout: number }; + + export type RetryContext = { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + } + + export type OnRetryCallback = (result?: Error | null) => void; + + export type RetryCallback = ( + err: Error, + context: { + state: RetryState; + opts: Dispatcher.DispatchOptions & { + retryOptions?: RetryHandler.RetryOptions; + }; + }, + callback: OnRetryCallback + ) => number | null; + + export interface RetryOptions { + /** + * Callback to be invoked on every retry iteration. + * It receives the error, current state of the retry object and the options object + * passed when instantiating the retry handler. + * + * @type {RetryCallback} + * @memberof RetryOptions + */ + retry?: RetryCallback; + /** + * Maximum number of retries to allow. + * + * @type {number} + * @memberof RetryOptions + * @default 5 + */ + maxRetries?: number; + /** + * Max number of milliseconds allow between retries + * + * @type {number} + * @memberof RetryOptions + * @default 30000 + */ + maxTimeout?: number; + /** + * Initial number of milliseconds to wait before retrying for the first time. + * + * @type {number} + * @memberof RetryOptions + * @default 500 + */ + minTimeout?: number; + /** + * Factior to multiply the timeout factor between retries. + * + * @type {number} + * @memberof RetryOptions + * @default 2 + */ + timeoutFactor?: number; + /** + * It enables to automatically infer timeout between retries based on the `Retry-After` header. + * + * @type {boolean} + * @memberof RetryOptions + * @default true + */ + retryAfter?: boolean; + /** + * HTTP methods to retry. + * + * @type {Dispatcher.HttpMethod[]} + * @memberof RetryOptions + * @default ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + */ + methods?: Dispatcher.HttpMethod[]; + /** + * Error codes to be retried. e.g. `ECONNRESET`, `ENOTFOUND`, `ETIMEDOUT`, `ECONNREFUSED`, etc. + * + * @type {string[]} + * @default ['ECONNRESET','ECONNREFUSED','ENOTFOUND','ENETDOWN','ENETUNREACH','EHOSTDOWN','EHOSTUNREACH','EPIPE'] + */ + errorCodes?: string[]; + /** + * HTTP status codes to be retried. + * + * @type {number[]} + * @memberof RetryOptions + * @default [500, 502, 503, 504, 429], + */ + statusCodes?: number[]; + } + + export interface RetryHandlers { + dispatch: Dispatcher["dispatch"]; + handler: Dispatcher.DispatchHandlers; + } +} diff --git a/node_modules/undici/types/webidl.d.ts b/node_modules/undici/types/webidl.d.ts new file mode 100644 index 0000000..40cfe06 --- /dev/null +++ b/node_modules/undici/types/webidl.d.ts @@ -0,0 +1,220 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/node_modules/undici/types/websocket.d.ts b/node_modules/undici/types/websocket.d.ts new file mode 100644 index 0000000..15a357d --- /dev/null +++ b/node_modules/undici/types/websocket.d.ts @@ -0,0 +1,131 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/universal-user-agent/dist-node/index.js b/node_modules/universal-user-agent/dist-node/index.js index 16c05dc..8865c7c 100644 --- a/node_modules/universal-user-agent/dist-node/index.js +++ b/node_modules/universal-user-agent/dist-node/index.js @@ -7,7 +7,7 @@ function getUserAgent() { return navigator.userAgent; } - if (typeof process === "object" && "version" in process) { + if (typeof process === "object" && process.version !== undefined) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } diff --git a/node_modules/universal-user-agent/dist-node/index.js.map b/node_modules/universal-user-agent/dist-node/index.js.map index 6a435c4..0a2cead 100644 --- a/node_modules/universal-user-agent/dist-node/index.js.map +++ b/node_modules/universal-user-agent/dist-node/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n if (typeof process === \"object\" && \"version\" in process) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n return \"\";\n}\n"],"names":["getUserAgent","navigator","userAgent","process","version","substr","platform","arch"],"mappings":";;;;AAAO,SAASA,YAAT,GAAwB;AAC3B,MAAI,OAAOC,SAAP,KAAqB,QAArB,IAAiC,eAAeA,SAApD,EAA+D;AAC3D,WAAOA,SAAS,CAACC,SAAjB;AACH;;AACD,MAAI,OAAOC,OAAP,KAAmB,QAAnB,IAA+B,aAAaA,OAAhD,EAAyD;AACrD,WAAQ,WAAUA,OAAO,CAACC,OAAR,CAAgBC,MAAhB,CAAuB,CAAvB,CAA0B,KAAIF,OAAO,CAACG,QAAS,KAAIH,OAAO,CAACI,IAAK,GAAlF;AACH;;AACD,SAAO,4BAAP;AACH;;;;"} \ No newline at end of file +{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n return \"\";\n}\n"],"names":["getUserAgent","navigator","userAgent","process","version","undefined","substr","platform","arch"],"mappings":";;;;AAAO,SAASA,YAAT,GAAwB;AAC3B,MAAI,OAAOC,SAAP,KAAqB,QAArB,IAAiC,eAAeA,SAApD,EAA+D;AAC3D,WAAOA,SAAS,CAACC,SAAjB;AACH;;AACD,MAAI,OAAOC,OAAP,KAAmB,QAAnB,IAA+BA,OAAO,CAACC,OAAR,KAAoBC,SAAvD,EAAkE;AAC9D,WAAQ,WAAUF,OAAO,CAACC,OAAR,CAAgBE,MAAhB,CAAuB,CAAvB,CAA0B,KAAIH,OAAO,CAACI,QAAS,KAAIJ,OAAO,CAACK,IAAK,GAAlF;AACH;;AACD,SAAO,4BAAP;AACH;;;;"} \ No newline at end of file diff --git a/node_modules/universal-user-agent/dist-src/index.js b/node_modules/universal-user-agent/dist-src/index.js index 79d75d3..3006e37 100644 --- a/node_modules/universal-user-agent/dist-src/index.js +++ b/node_modules/universal-user-agent/dist-src/index.js @@ -2,7 +2,7 @@ export function getUserAgent() { if (typeof navigator === "object" && "userAgent" in navigator) { return navigator.userAgent; } - if (typeof process === "object" && "version" in process) { + if (typeof process === "object" && process.version !== undefined) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } return ""; diff --git a/node_modules/universal-user-agent/dist-web/index.js b/node_modules/universal-user-agent/dist-web/index.js index c550c02..fc742b9 100644 --- a/node_modules/universal-user-agent/dist-web/index.js +++ b/node_modules/universal-user-agent/dist-web/index.js @@ -2,7 +2,7 @@ function getUserAgent() { if (typeof navigator === "object" && "userAgent" in navigator) { return navigator.userAgent; } - if (typeof process === "object" && "version" in process) { + if (typeof process === "object" && process.version !== undefined) { return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; } return ""; diff --git a/node_modules/universal-user-agent/dist-web/index.js.map b/node_modules/universal-user-agent/dist-web/index.js.map index b9d9d79..2cdf193 100644 --- a/node_modules/universal-user-agent/dist-web/index.js.map +++ b/node_modules/universal-user-agent/dist-web/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n if (typeof process === \"object\" && \"version\" in process) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n return \"\";\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;AAC/B,IAAI,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,WAAW,IAAI,SAAS,EAAE;AACnE,QAAQ,OAAO,SAAS,CAAC,SAAS,CAAC;AACnC,KAAK;AACL,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,SAAS,IAAI,OAAO,EAAE;AAC7D,QAAQ,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC7F,KAAK;AACL,IAAI,OAAO,4BAA4B,CAAC;AACxC;;;;"} \ No newline at end of file +{"version":3,"file":"index.js","sources":["../dist-src/index.js"],"sourcesContent":["export function getUserAgent() {\n if (typeof navigator === \"object\" && \"userAgent\" in navigator) {\n return navigator.userAgent;\n }\n if (typeof process === \"object\" && process.version !== undefined) {\n return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`;\n }\n return \"\";\n}\n"],"names":[],"mappings":"AAAO,SAAS,YAAY,GAAG;AAC/B,IAAI,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,WAAW,IAAI,SAAS,EAAE;AACnE,QAAQ,OAAO,SAAS,CAAC,SAAS,CAAC;AACnC,KAAK;AACL,IAAI,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE;AACtE,QAAQ,OAAO,CAAC,QAAQ,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,EAAE,OAAO,CAAC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAC7F,KAAK;AACL,IAAI,OAAO,4BAA4B,CAAC;AACxC;;;;"} \ No newline at end of file diff --git a/node_modules/universal-user-agent/package.json b/node_modules/universal-user-agent/package.json index ac3e658..c386163 100644 --- a/node_modules/universal-user-agent/package.json +++ b/node_modules/universal-user-agent/package.json @@ -1,7 +1,7 @@ { "name": "universal-user-agent", "description": "Get a user agent string in both browser and node", - "version": "6.0.0", + "version": "6.0.1", "license": "ISC", "files": [ "dist-*/", diff --git a/node_modules/webpagetest/.travis.yml b/node_modules/webpagetest/.travis.yml index 5ae4894..07cc301 100644 --- a/node_modules/webpagetest/.travis.yml +++ b/node_modules/webpagetest/.travis.yml @@ -1,3 +1,3 @@ language: node_js node_js: - - 10 + - 17 diff --git a/node_modules/webpagetest/README.md b/node_modules/webpagetest/README.md index 055b57e..b5bef8c 100644 --- a/node_modules/webpagetest/README.md +++ b/node_modules/webpagetest/README.md @@ -1,18 +1,20 @@ -

            WebPageTest Logo

            +

            WebPageTest Logo

            Learn about more WebPageTest API Integrations in our docs

            # WebPageTest API Wrapper for NodeJS -[![Build Status](https://travis-ci.com/WebPageTest/webpagetest-api.svg?branch=master)](https://travis-ci.com/WebPageTest/webpagetest-api) + [![NPM Version](https://img.shields.io/npm/v/webpagetest.svg?style=flat)](https://www.npmjs.org/package/webpagetest) [![NPM Downloads](https://img.shields.io/npm/dm/webpagetest.svg?style=flat)](https://www.npmjs.org/package/webpagetest) WebPageTest API Wrapper is a [NPM](https://npmjs.org) package that wraps [WebPageTest](https://github.com/WPO-Foundation/webpagetest) API for [NodeJS](https://nodejs.org) as a module and a command-line tool. + +For a better understanding of WebPageTest API Wrapper, here are some sample [Node Recipies](https://github.com/WebPageTest/WebPageTest-API-Recipes) ## Getting started ```bash -$ npm install webpagetest -g +npm install webpagetest -g ``` ## Basics @@ -20,7 +22,7 @@ $ npm install webpagetest -g ### Command line ```bash -$ webpagetest test https://docs.webpagetest.org/api/integrations/ +webpagetest test https://docs.webpagetest.org/api/integrations/ -k YOURAPIKEY ``` ### Docker @@ -28,22 +30,25 @@ $ webpagetest test https://docs.webpagetest.org/api/integrations/ #### Build ```bash -$ docker build -t webpagetest-api . +docker build -t webpagetest-api . ``` #### Run ```bash -$ docker run -it --rm webpagetest-api -k YOURAPIKEY test https://docs.webpagetest.org/api/integrations/ +docker run -it --rm webpagetest-api -k YOURAPIKEY test https://docs.webpagetest.org/api/integrations/ ``` ### Module ```javascript const WebPageTest = require("webpagetest"); -const wpt = new WebPageTest("www.webpagetest.org"); -wpt.runTest("https://docs.webpagetest.org/api/integrations/", (err, data) => { +const wptServer = "www.webpagetest.org"; +const wpt = new WebPageTest(wptServer, "YOUR_API_KEY"); + +const siteToTest = "https://docs.webpagetest.org/api/integrations/"; +wpt.runTest(siteToTest, (err, data) => { console.log(err || data); }); ``` @@ -53,7 +58,7 @@ wpt.runTest("https://docs.webpagetest.org/api/integrations/", (err, data) => { ### Help ```bash -$ webpagetest --help +webpagetest --help ``` ### Commands @@ -63,6 +68,7 @@ $ webpagetest --help - **locations** _[options]_: list locations and the number of pending tests - **testers** _[options]_: list testers status and details - **test** _[options] \_: run test, _\_ can also be a path to a script file +- **testAndWait** _[options] \_: run test and waits for the result, _\_ can also be a path to a script file - **testBalance** _[options]_: get remaining tests for the account - **restart** _\_: restart test - **cancel** _\_: cancel running/pending test @@ -117,7 +123,7 @@ _The default WPT server can also be specified via environment variable `WEBPAGET - **--injectScript** _\_: JavaScript to run after the document has started loading - **-E, --tester** _\_: run the test on a specific PC (name must match exactly or the test will not run) - **-W, --mobile**: (experimental) emulate mobile browser: Chrome mobile user agent, 640x960 screen, 2x scaling and fixed viewport (Chrome only) -- **--device** _\_: device name from mobile_devices.ini to use for mobile emulation (only when mobile=1 is specified to enable emulation and only for Chrome) +- **--device** _\_: device name from [mobile_devices.ini](https://github.com/WPO-Foundation/webpagetest/blob/master/www/settings/mobile_devices.ini) to use for mobile emulation (only when --mobile is specified to enable emulation and only for Chrome) - **-M, --timeline**: capture Developer Tools Timeline (Chrome only) - **-J, --callstack**: set between 1-5 to include the JS call stack. must be used in conjunction with timeline (increases overhead) (Chrome only) - **-q, --chrometrace**: capture chrome trace (about://tracing) (Chrome only) @@ -233,10 +239,10 @@ _The default WPT server can also be specified via environment variable `WEBPAGET ### Examples -#### 1. Get all available locations +#### 1. Get API available locations ```bash -$ webpagetest locations +$ webpagetest locations -k YOURAPIKEY ``` ```javascript @@ -264,41 +270,10 @@ $ webpagetest locations } ``` -#### 2. Get API available locations +#### 2. Run test on https://docs.webpagetest.org/api/integrations/ from San Jose on IE9 ```bash -$ webpagetest locations --key 1F2A3K4E5 -``` - -```javascript -{ - "response": { - "statusCode": 200, "statusText": "Ok", - "data": { - "location": [ - ... - { - "id": "SanJose_IE9", - "Label": "San Jose, CA USA (IE 9,Chrome,Firefox)", - "location": "SanJose_IE9", - "Browser": "IE 9", - "PendingTests": { - "p1": 0, "p2": 0, "p3": 0, "p4": 0, "p5": 2, "p6": 2, "p7": 0, - "p8": 0, "p9": 0, "Total": 7, "HighPriority": 2, "LowPriority": 4, - "Testing": 1, "Idle": 0 - } - }, - ... - ] - } - } -} -``` - -#### 3. Run test on https://docs.webpagetest.org/api/integrations/ from San Jose on IE9 - -```bash -$ webpagetest test https://docs.webpagetest.org/api/integrations/ --key 1F2A3K4E5 --location SanJose_IE9 +webpagetest test https://docs.webpagetest.org/api/integrations/ -k YOURAPIKEY --location SanJose_IE9 ``` ```javascript @@ -317,10 +292,10 @@ $ webpagetest test https://docs.webpagetest.org/api/integrations/ --key 1F2A3K4E } ``` -#### 4. Check current test status +#### 3. Check current test status ```bash -$ webpagetest status 121025_PT_N8K +webpagetest status 121025_PT_N8K -k YOURAPIKEY ``` ```javascript @@ -338,10 +313,10 @@ $ webpagetest status 121025_PT_N8K } ``` -#### 5. Get test results +#### 4. Get test results ```bash -$ webpagetest results 121025_PT_N8K +webpagetest results 121025_PT_N8K -k YOURAPIKEY ``` ```javascript @@ -373,23 +348,12 @@ $ webpagetest results 121025_PT_N8K } ``` -#### 6. Get test waterfall thumbnail from repeat view as data URI - -```bash -$ webpagetest waterfall 121025_PT_N8K --thumbnail --cached --uri -``` -```javascript -{ - "type": "image/png", - "data": "iVBORw0KGgoAAAANSUhEUgA...RK5CYII=" -} -``` -#### 7. Get remaining tests count for the account +#### 5. Get remaining tests count for the account ```bash -$ webpagetest testBalance --key 1F2A3K4E5 +webpagetest testBalance -k YOURAPIKEY ``` ```javascript @@ -403,13 +367,13 @@ $ webpagetest testBalance --key 1F2A3K4E5 #### Run test on https://docs.webpagetest.org/api/integrations/ and poll results every 5 seconds timing out in 60 seconds ```bash -$ webpagetest test https://docs.webpagetest.org/api/integrations/ --poll 5 --timeout 60 +webpagetest test https://docs.webpagetest.org/api/integrations/ --poll 5 --timeout 60 ``` #### Or run test on https://docs.webpagetest.org/api/integrations/ and wait for results listening on localhost\* port 8000\*\* ```bash -$ webpagetest test https://docs.webpagetest.org/api/integrations/ --wait 8000 +webpagetest test https://docs.webpagetest.org/api/integrations/ --wait 8000 ``` ```javascript @@ -448,6 +412,7 @@ Methods and options (including the one letter shorthands) are the same when usin - `getTesters(options, callback)` - `getTestBalance(options, callback)` - `runTest(url_or_script, options, callback)` +- `runTestAndWait(url_or_script, options, callback)` - `restartTest(id, options, callback)` - `cancelTest(id, options, callback)` - `getHARData(id, options, callback)` @@ -516,7 +481,7 @@ wpt.runTest(script, (err, data) => { - **dryRun**: _Boolean_, if `true`, method does not make an actual request to the API Server but rather returns an object with `url` which contains the actual URL to make the GET request to WebPageTest API Server - **server**: _String_, if specified, overrides the WebPageTest server informed in the constructor only for that method call -#### Test (works for `runTest` method only) +#### Test (works with `runTest` and `runTestAndWait`) - **location**: _String_, location to test from - **connectivity**: _String_, connectivity profile -- requires location to be specified -- (Cable|DSL|3GSlow|3G|3GFast|4G|LTE|Edge|2G|Dial|FIOS|Native|custom) [Cable] @@ -537,6 +502,7 @@ wpt.runTest(script, (err, data) => { - **minimumDuration**: _Number_, minimum test duration in seconds - **tester**: _String_, run the test on a specific PC (name must match exactly or the test will not run) - **emulateMobile**: _Boolean_, (experimental) emulate mobile browser: Chrome mobile user agent, 640x960 screen, 2x scaling and fixed viewport (Chrome only) +- **device**: _String_, device name from [mobile_devices.ini](https://github.com/WPO-Foundation/webpagetest/blob/master/www/settings/mobile_devices.ini) to use for mobile emulation (only when emulateMobile=true is specified to enable emulation and only for Chrome) - **timeline**: _Boolean_, capture Developer Tools Timeline (Chrome only) - **timelineCallStack**: _Boolean_, set between 1-5 to include the JS call stack. must be used in conjunction with timeline (increases overhead) (Chrome only) - **chromeTrace**: _Boolean_, capture chrome trace (about://tracing) (Chrome only) @@ -590,15 +556,15 @@ wpt.runTest(script, (err, data) => { - **lighthouse**: _Boolean_, perform lighthouse test (Chrome only, Linux agent only) - **throttleCPU**: _Number_, custom cpu throttling -#### API Key (works for `runTest`, `restartTest` and `cancelTest` methods) +#### API Key (works for `runTest`, `runTestAndWait`, `restartTest` and `cancelTest` methods) - **key**: _String_, API key (if assigned). Contact the WebPageTest server administrator for a key if required -#### Request (works for `getTestStatus` `getResults` `getLocations` `getTesters` and `runTest` methods) +#### Request (works for `getTestStatus` `getResults` `getLocations` `getTesters` `runTest` and `runTestAndWait` methods) - **requestId**: _String_, echo request ID, useful to track asynchronous requests -#### Results (works for `getResults` and `runTest` methods) +#### Results (works for `getResults` `runTest` and `runTestAndWait` methods) - **breakDown**: _Boolean_, include the breakdown of requests and bytes by mime type - **domains**: _Boolean_, include the breakdown of requests and bytes by domain @@ -751,7 +717,7 @@ WebPageTest API Wrapper comes with a handy RESTful API proxy ### Command Line ```bash -$ webpagetest listen 8080 --server wpt.foo.com +webpagetest listen 8080 --server wpt.foo.com ``` ```bash @@ -760,12 +726,12 @@ http://localhost:8080 ``` ```bash -$ curl http://localhost:8080/help -$ curl http://localhost:8080/test/webpagetest.org/?location=SanJose_IE9 +curl http://localhost:8080/help +curl http://localhost:8080/test/webpagetest.org/?location=SanJose_IE9 ``` ```bash -$ webpagetest listen 8443 --key key.pem --cert cert.pem --server wpt.foo.com +webpagetest listen 8443 --key key.pem --cert cert.pem --server wpt.foo.com ``` ```bash @@ -801,12 +767,12 @@ Batch command is available as command line only and loads a batch file containin By running ```bash -$ webpagetest batch commands.txt +webpagetest batch commands.txt ``` where `commands.txt` contains: -``` +```bash test https://docs.webpagetest.org/api/integrations/ --first --location foo test https://docs.webpagetest.org/api/integrations/ --first --location bar ``` @@ -835,7 +801,7 @@ It schedules the 2 tests above returning an array of size 2 in the same order as With exit status 0 in case none of commands returns an error: ```bash -$ echo $? +echo $? 0 ``` @@ -843,7 +809,7 @@ By running multiple sync tests, i.e. with either `--poll` or `--wait`, all tests `commands.txt`: -``` +```bash test https://docs.webpagetest.org/api/integrations/ --first --location foo --poll --timeout 60 test https://docs.webpagetest.org/api/integrations/ --first --location bar --poll --timeout 60 ``` @@ -857,7 +823,7 @@ WebPageTest API Wrapper provides a simple seamless way to integrate WebPageTest ## Tests ```bash -$ npm test +npm test ``` ## Issues diff --git a/node_modules/webpagetest/assets/images/recipe-banner.png b/node_modules/webpagetest/assets/images/recipe-banner.png new file mode 100644 index 0000000..ab5d500 Binary files /dev/null and b/node_modules/webpagetest/assets/images/recipe-banner.png differ diff --git a/node_modules/webpagetest/bin/webpagetest b/node_modules/webpagetest/bin/webpagetest old mode 100755 new mode 100644 index 7b32466..004078a --- a/node_modules/webpagetest/bin/webpagetest +++ b/node_modules/webpagetest/bin/webpagetest @@ -272,7 +272,7 @@ function cleanupProgram() { } function execCommand() { - var wpt = new WebPageTest(program.server || defaultServer); + var wpt = new WebPageTest(program.server || defaultServer, options.key); // options if (options) { diff --git a/node_modules/webpagetest/lib/helper.js b/node_modules/webpagetest/lib/helper.js index d876593..f9a67ce 100644 --- a/node_modules/webpagetest/lib/helper.js +++ b/node_modules/webpagetest/lib/helper.js @@ -109,7 +109,7 @@ function csvParser(data, callback) { var key, value; for (key in row) { value = row[key].replace(/|<\/b>/g, ''); - row[key] = entities.decode(value, 2); + row[key] = entities.decodeHTML(value, 2); } return row; }, callback.bind(this)); diff --git a/node_modules/webpagetest/lib/mapping.js b/node_modules/webpagetest/lib/mapping.js index d1087f2..52b6f46 100644 --- a/node_modules/webpagetest/lib/mapping.js +++ b/node_modules/webpagetest/lib/mapping.js @@ -552,6 +552,525 @@ var options = { info: "timeout for polling and waiting results [no timeout]", }, }, + testAndWait: { + location: { + name: "location", + key: "l", + api: "location", + param: "location", + info: "location to test from", + }, + + // Test Setting tab + connectivity: { + name: "connectivity", + key: "y", + api: "connectivity", + param: "profile", + info: "connectivity profile (Cable|DSL|3GSlow|3G|3GFast|4G|LTE|Edge|2G|Dial|FIOS|Native|custom) [Cable]", + }, + runs: { + name: "runs", + key: "r", + api: "runs", + param: "number", + info: "number of test runs [1]", + }, + first: { + name: "firstViewOnly", + key: "f", + api: "fvonly", + bool: true, + info: "skip the Repeat View test", + }, + video: { + name: "video", + key: "v", + api: "video", + bool: true, + info: "capture video", + }, + private: { + name: "private", + key: "p", + api: "private", + bool: true, + info: "keep the test hidden from the test log", + }, + label: { + name: "label", + key: "L", + api: "label", + param: "label", + info: "label for the test", + }, + + // Advanced tab + onload: { + name: "stopAtDocumentComplete", + key: "i", + api: "web10", + bool: true, + info: "stop test at document complete. typically, tests run until all activity stops", + }, + noscript: { + name: "disableJavaScript", + key: "S", + api: "noscript", + bool: true, + info: "disable JavaScript (IE, Chrome, Firefox)", + }, + clearcerts: { + name: "clearCerts", + key: "C", + api: "clearcerts", + bool: true, + info: "clear SSL certificate caches", + }, + ignoressl: { + name: "ignoreSSL", + key: "R", + api: "ignoreSSL", + bool: true, + info: "ignore SSL certificate errors, e.g. name mismatch, self-signed certificates, etc", + }, + standards: { + name: "disableCompatibilityView", + key: "T", + api: "standards", + bool: true, + info: "forces all pages to load in standards mode (IE only)", + }, + tcpdump: { + name: "tcpDump", + key: "u", + api: "tcpdump", + bool: true, + info: "capture network packet trace (tcpdump)", + }, + bodies: { + name: "saveResponseBodies", + key: "O", + api: "bodies", + bool: true, + info: "save response bodies for text resources", + }, + keepua: { + name: "keepOriginalUserAgent", + key: "K", + api: "keepua", + bool: true, + info: "do not add PTST to the original browser User Agent string", + }, + dom: { + name: "domElement", + key: "m", + api: "domelement", + param: "element", + info: "DOM element to record for sub-measurement", + }, + duration: { + name: "minimumDuration", + key: "N", + api: "time", + param: "seconds", + info: "minimum test duration in seconds", + }, + tester: { + name: "tester", + key: "E", + api: "tester", + param: "name", + info: "run the test on a specific PC (name must match exactly or the test will not run)", + }, + injectScript: { + name: "injectScript", + api: "injectScript", + param: "injectScript", + info: "JavaScript to run after the document has started loading", + }, + + // Chrome tab + mobile: { + name: "emulateMobile", + key: "W", + api: "mobile", + bool: true, + info: "(experimental) emulate mobile browser: Chrome mobile user agent, 640x960 screen, 2x scaling and fixed viewport (Chrome only)", + }, + device: { + name: "device", + api: "mobileDevice", + param: "string", + info: "device name from mobile_devices.ini to use for mobile emulation (only when mobile=1 is specified to enable emulation and only for Chrome)", + }, + timeline: { + name: "timeline", + key: "M", + api: "timeline", + bool: true, + info: "capture Developer Tools Timeline (Chrome only)", + }, + callstack: { + name: "timelineCallStack", + key: "J", + api: "timelineStack", + bool: true, + info: "set between 1-5 to include the JS call stack. must be used in conjunction with timeline (increases overhead) (Chrome only)", + valid: /[1-5]/, + }, + chrometrace: { + name: "chromeTrace", + key: "q", + api: "trace", + bool: true, + info: "capture chrome trace (about://tracing) (Chrome only)", + }, + tracecategories: { + name: "traceCategories", + api: "traceCategories", + param: "categories", + info: "trace categories (when chrometrace enabled) (Chrome only)", + }, + netlog: { + name: "netLog", + key: "G", + api: "netlog", + bool: true, + info: "capture Network Log (Chrome only)", + }, + datareduction: { + name: "dataReduction", + key: "Q", + api: "dataReduction", + bool: true, + info: "enable data reduction on Chrome 34+ Android (Chrome only)", + }, + useragent: { + name: "userAgent", + key: "x", + api: "uastring", + param: "string", + info: "custom user agent string (Chrome only)", + }, + cmdline: { + name: "commandLine", + key: "X", + api: "cmdline", + param: "switches", + info: "use a list of custom command line switches (Chrome only)", + }, + lighthouse: { + name: "lighthouse", + api: "lighthouse", + bool: true, + info: "perform lighthouse test (Chrome only, Linux agent only)", + }, + + //throttle_cpu param + throttleCPU: { + name: "throttleCPU", + key: "thc", + api: "throttle_cpu", + param: "number", + info: "custom cpu throttling", + }, + + // Auth tab + login: { + name: "login", + key: "g", + api: "login", + param: "username", + info: "username for authenticating tests (http authentication)", + }, + password: { + name: "password", + key: "w", + api: "password", + param: "password", + info: "password for authenticating tests (http authentication)", + }, + + // Script tab + sensitive: { + name: "sensitive", + key: "t", + api: "sensitive", + bool: true, + info: "discard script and http headers in the result", + }, + noheaders: { + name: "disableHTTPHeaders", + key: "H", + api: "noheaders", + bool: true, + info: "disable saving of the http headers (as well as browser status messages and CPU utilization)", + }, + + // Block tab + block: { + name: "block", + key: "b", + api: "block", + param: "urls", + array: true, + info: "space-delimited list of urls to block (substring match)", + }, + + // SPOF tab + spof: { + name: "spof", + key: "Z", + api: "spof", + param: "domains", + array: true, + info: "space-delimited list of domains to simulate failure by re-routing to blackhole.webpagetest.org to silently drop all requests", + }, + + // Custom tab + custom: { + name: "customMetrics", + key: "c", + api: "custom", + param: "script", + info: "execute arbitrary JavaScript at the end of a test to collect custom metrics", + }, + + // API only settings + authtype: { + name: "authenticationType", + key: "a", + api: "authType", + param: "type", + info: "type of authentication: 0 = Basic, 1 = SNS [0]", + }, + notify: { + name: "notifyEmail", + key: "n", + api: "notify", + param: "e-mail", + info: "e-mail address to notify with the test results", + }, + pingback: { + name: "pingback", + key: "B", + api: "pingback", + param: "url", + info: 'URL to ping when the test is complete (the test ID will be passed as an "id" parameter)', + }, + bwdown: { + name: "bandwidthDown", + key: "D", + api: "bwDown", + param: "bandwidth", + info: "download bandwidth in Kbps (used when specifying a custom connectivity profile)", + }, + bwup: { + name: "bandwidthUp", + key: "U", + api: "bwUp", + param: "bandwidth", + info: "upload bandwidth in Kbps (used when specifying a custom connectivity profile)", + }, + browserwidth: { + name: "browserwidth", + key: "bw", + api: "browser_width", + param: "pixels", + info: "Browser window width (in display pixels)", + }, + browserheight: { + name: "browserheight", + key: "bh", + api: "browser_height", + param: "pixels", + info: "Browser window height (in display pixels)", + }, + viewportheight: { + name: "viewportheight", + key: "vh", + api: "height", + param: "pixels", + info: "Viewport Height in css pixels", + }, + viewportwidth: { + name: "viewportwidth", + key: "vw", + api: "width", + param: "pixels", + info: "Viewport Width in css pixels", + }, + devicetopixelratio: { + name: "devicetopixelratio", + key: "dpr", + api: "dpr", + param: "ratio", + info: "Device To Pixel Ratio", + }, + appendua: { + name: "appendua", + key: "au", + api: "appendua", + param: "string", + info: "String to append to the user agent string. This is in addition to the default PTST/ver string", + }, + testtype: { + name: "testtype", + key: "tt", + api: "type", + param: "string", + info: "For running alternative test types, can specify traceroute or lighthouse", + }, + profiler: { + name: "profiler", + key: "pr", + api: "profiler", + param: "number", + info: "Set to 1 to enable the V8 sampling profiler (Chromium only)", + }, + disableAVIF: { + name: "disableAVIF", + key: "avif", + api: "disableAVIF", + param: "number", + info: "Set to 1 to disable AVIF support (Chromium 88+)", + }, + disableWEBP: { + name: "disableWEBP", + key: "webp", + api: "disableWEBP", + param: "number", + info: "Set to 1 to disable WEBP support (Chromium 88+)", + }, + disableJXL: { + name: "disableJXL", + key: "jxl", + api: "disableJXL", + param: "number", + info: "Set to 1 to disable JpegXL support (Chromium 88+)", + }, + dtShaper: { + name: "dtShaper", + key: "dts", + api: "dtShaper", + param: "number", + info: "Set to 1 to use Chrome's built-in traffic-shaping instead of the packet-level netem shaping usually used by the test agents", + }, + latency: { + name: "latency", + key: "Y", + api: "latency", + param: "time", + info: "first-hop Round Trip Time in ms (used when specifying a custom connectivity profile)", + }, + plr: { + name: "packetLossRate", + key: "P", + api: "plr", + param: "percentage", + info: "packet loss rate - percent of packets to drop (used when specifying a custom connectivity profile)", + }, + noopt: { + name: "disableOptimization", + key: "z", + api: "noopt", + bool: true, + info: "disable optimization checks (for faster testing)", + }, + noimages: { + name: "disableScreenshot", + key: "I", + api: "noimages", + bool: true, + info: "disable screen shot capturing", + }, + full: { + name: "fullResolutionScreenshot", + key: "F", + api: "pngss", + bool: true, + info: "save a full-resolution version of the fully loaded screen shot as a PNG", + }, + jpeg: { + name: "jpegQuality", + key: "j", + api: "iq", + param: "level", + info: "jpeg compression level (30-100) for the screen shots and video capture", + }, + medianvideo: { + name: "medianVideo", + key: "A", + api: "mv", + bool: true, + info: "store the video from the median run when capturing video is enabled", + }, + htmlbody: { + name: "htmlBody", + api: "htmlbody", + bool: true, + info: "save the content of only the base HTML response", + }, + tsview: { + name: "tsView", + api: "tsview_id", + param: "id", + info: "test name to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)", + }, + tsviewconfigs: { + name: "tsViewConfigs", + api: "tsview_configs", + param: "string", + info: "configs to use when submitting results to tsviewdb (for private instances that have integrated with tsviewdb)", + }, + affinity: { + name: "affinity", + api: "affinity", + param: "string", + info: "string to hash test to a specific test agent. tester will be picked by index among available testers", + }, + priority: { + name: "priority", + api: "priority", + param: "number", + info: "change test priority (0-9) [enforced by API key, otherwise 5]", + valid: /^\d$/, + }, + // Undocumented/experimental/transitent/deprecated + noads: { + name: "blockAds", + api: "blockads", + bool: true, + info: "block ads defined by adblockrules.org", + }, + continuous: { + name: "continuousVideoCapture", + api: "continuousVideo", + bool: true, + info: "capture video continuously (unstable/experimental, may cause tests to fail)", + }, + spdy3: { + name: "forceSpdy3", + api: "spdy3", + bool: true, + info: "force SPDY version 3 (Chrome only)", + }, + swrender: { + name: "forceSoftwareRendering", + api: "swrender", + bool: true, + info: "force software rendering, disable GPU acceleration (Chrome only)", + }, + + // Synchonous tests + results + wait: { + name: "waitResults", + param: "hostname:port", + optional: true, + info: "wait for test results informed by agent once complete listening on : [hostname:first port available above 8000]", + }, + }, request: { request: { name: "requestId", @@ -787,13 +1306,13 @@ var commands = { status: { name: "getTestStatus", param: "id", - options: [options.request], + options: [options.request, options.apikey], info: "check test status", }, results: { name: "getTestResults", param: "id", - options: [options.results, options.request], + options: [options.results, options.request, options.apikey], info: "get test results", }, locations: { @@ -808,7 +1327,7 @@ var commands = { }, testers: { name: "getTesters", - options: [options.request], + options: [options.request, options.apikey], info: "list testers status and details", }, test: { @@ -818,6 +1337,18 @@ var commands = { info: "run test", nokey: [options.results], }, + testAndWait: { + name: "runTestAndWait", + param: "url_or_script", + options: [ + options.apikey, + options.testAndWait, + options.request, + options.results, + ], + info: "run test and waits for the result", + nokey: [options.results], + }, restart: { name: "restartTest", param: "id", @@ -833,101 +1364,105 @@ var commands = { har: { name: "getHARData", param: "id", + options: [options.apikey], info: "get the HTTP Archive (HAR) from test", }, pagespeed: { name: "getPageSpeedData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the Google Page Speed results (if available) from test", }, utilization: { name: "getUtilizationData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the CPU, bandwidth and memory utilization data from test", }, request: { name: "getRequestData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the request data from test", }, timeline: { name: "getTimelineData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the Chrome Developer Tools Timeline data (if available) from test", }, netlog: { name: "getNetLogData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the Chrome Developer Tools Net log data (if available) from test", }, chrometrace: { name: "getChromeTraceData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the Chrome Trace data (if available) from test", }, console: { name: "getConsoleLogData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get the browser console log data (if available) from test", }, testinfo: { name: "getTestInfo", param: "id", + options: [options.apikey], info: "get test request info/details", }, history: { name: "getHistory", param: "days", optional: true, + options: [options.apikey], info: "get history of previously run tests", }, googlecsi: { name: "getGoogleCsiData", param: "id", - options: [options.run], + options: [options.run, options.apikey], info: "get Google CSI data (Client Side Instrumentation)", }, response: { name: "getResponseBody", param: "id", - options: [options.run, options.response], + options: [options.run, options.response, options.apikey], info: "get response body for text resources", }, waterfall: { name: "getWaterfallImage", param: "id", - options: [options.run, options.image, options.waterfall], + options: [options.run, options.image, options.waterfall, options.apikey], info: "get the waterfall PNG image", }, screenshot: { name: "getScreenshotImage", param: "id", - options: [options.run, options.image, options.screenshot], + options: [options.run, options.image, options.screenshot, options.apikey], info: "get the fully loaded page screenshot in JPG format (PNG if in full resolution)", }, video: { name: "createVideo", param: "tests", - options: [options.video], + options: [options.video, options.apikey], info: "create a video from (comma separated test ids)", }, player: { name: "getEmbedVideoPlayer", param: "id", + options: [options.apikey], info: "get a html5 player for a video ", }, listen: { name: "listen", param: "hostname:port", optional: true, - options: [options.listen], + options: [options.listen,options.apikey], info: "start webpagetest-api proxy server on : [hostname:%s]", }, }; diff --git a/node_modules/webpagetest/lib/webpagetest.js b/node_modules/webpagetest/lib/webpagetest.js index 0053987..c593336 100644 --- a/node_modules/webpagetest/lib/webpagetest.js +++ b/node_modules/webpagetest/lib/webpagetest.js @@ -91,9 +91,10 @@ function get(config, pathname, proxy, agent, callback, encoding) { }; } - if (encoding !== "binary") { - options.headers["accept-encoding"] = "gzip,deflate"; - } + // api key always required + options.headers["X-WPT-API-KEY"] = this.config.key; + options.headers["accept-encoding"] = "gzip,deflate"; + options.headers["User-Agent"] = "WebpagetestNodeWrapper/v0.7.4"; if (agent) { options.agent = agent; @@ -317,9 +318,6 @@ function getLocations(options, callback) { options = options === callback ? undefined : options; var query = helper.setQuery(mapping.commands.locations, options); - if (!query.k && this.config.key && !options.allLocations) { - query.k = this.config.key; - } return api.call(this, paths.locations, callback, query, options); } @@ -337,9 +335,10 @@ function getTestBalance(options, callback) { options = options === callback ? undefined : options; var query = helper.setQuery(mapping.commands.testBalance, options); - if (!query.k && this.config.key) { - query.k = this.config.key; - } + // API key (to pass with the parans) (depricated) + // if (!query.k && this.config.key) { + // query.k = this.config.key; + // } return api.call(this, paths.testBalance, callback, query, options); } @@ -365,10 +364,10 @@ function runTest(what, options, callback) { // json output format query.f = "json"; - // API key - if (!query.k && this.config.key) { - query.k = this.config.key; - } + // API key (to pass with the parans) (depricated) + // if (!query.k && this.config.key) { + // query.k = this.config.key; + // } // synchronous tests with results var testId, @@ -395,6 +394,11 @@ function runTest(what, options, callback) { (!data || (data && data.data && data.statusCode !== 200)) && !(typeof err === "number" && data === undefined) ) { + console.log( + data && data.data && data.data.statusText + ? data.data.statusText + : "Testing is in progress, please be patient" + ); polling = setTimeout( getTestResults.bind(this, testId, resultsOptions, poll.bind(this)), options.pollResults @@ -530,6 +534,17 @@ function runTest(what, options, callback) { return api.call(this, paths.test, callback, query, options); } +function runTestAndWait(what, options, callback) { + delete options.pollResults; + + options = Object.assign(options, { pollResults: 13 }); + + new Promise((resolve) => { + let test = runTest.bind(this, what, options, callback); + resolve(test()); + }); +} + function restartTest(id, options, callback) { var query = { resubmit: id }; @@ -932,6 +947,7 @@ WebPageTest.prototype = { getLocations: getLocations, getTesters: getTesters, runTest: runTest, + runTestAndWait: runTestAndWait, restartTest: restartTest, cancelTest: cancelTest, getPageSpeedData: getPageSpeedData, @@ -960,6 +976,7 @@ WebPageTest.prototype = { locations: getLocations, testers: getTesters, test: runTest, + testAndWait: runTestAndWait, cancel: cancelTest, pagespeed: getPageSpeedData, har: getHARData, diff --git a/node_modules/webpagetest/package.json b/node_modules/webpagetest/package.json index f71a77e..2775c28 100644 --- a/node_modules/webpagetest/package.json +++ b/node_modules/webpagetest/package.json @@ -1,6 +1,6 @@ { "name": "webpagetest", - "version": "0.6.0", + "version": "0.7.4", "description": "WebPageTest API wrapper for NodeJS", "author": "WebPageTest (http://github.com/WebPageTest)", "homepage": "http://github.com/WebPageTest/webpagetest-api", @@ -24,19 +24,19 @@ "webpagetest": "bin/webpagetest" }, "scripts": { - "test": "./node_modules/mocha/bin/mocha -R spec test/*-test.js" + "test": "mocha -R spec test/*-test.js" }, "engines": { "node": ">=10.18.1" }, "dependencies": { "commander": "^5.1.0", - "csv": "^5.3.2", - "entities": "^2.0.3", - "mocha": "^8.0.1", - "xml2js": "^0.4.23" + "csv": "^6.2.2", + "entities": "^4.4.0", + "mocha": "^10.1.0", + "xml2js": "^0.6.2" }, "devDependencies": { - "nock": "^12.0.3" + "nock": "^13.2.9" } -} +} \ No newline at end of file diff --git a/node_modules/webpagetest/test/command-line-test.js b/node_modules/webpagetest/test/command-line-test.js index ce274de..578796f 100644 --- a/node_modules/webpagetest/test/command-line-test.js +++ b/node_modules/webpagetest/test/command-line-test.js @@ -324,7 +324,7 @@ describe('WebPageTest Command Line', function() { // loop all commands help [ - '', 'status', 'results', 'locations', 'testers', 'test', 'restart', 'cancel', 'har', + '', 'status', 'results', 'locations', 'testers', 'test', 'testAndWait', 'restart', 'cancel', 'har', 'pagespeed', 'utilization', 'request', 'timeline', 'netlog', 'chrometrace', 'console', 'testinfo', 'history', 'googlecsi', 'response', 'waterfall', 'screenshot', 'video', 'player', 'listen', 'batch','testBalance' diff --git a/node_modules/webpagetest/test/fixtures/command-line/help-testAndWait.txt b/node_modules/webpagetest/test/fixtures/command-line/help-testAndWait.txt new file mode 100644 index 0000000..71249d6 --- /dev/null +++ b/node_modules/webpagetest/test/fixtures/command-line/help-testAndWait.txt @@ -0,0 +1,173 @@ +Usage: webpagetest testAndWait [options] + +run test and waits for the result + +Options: + -k, --key API key (if assigned). Contact the + WebPageTest server administrator for a + key if required + -l, --location location to test from + -y, --connectivity connectivity profile + (Cable|DSL|3GSlow|3G|3GFast|4G|LTE|Edge|2G|Dial|FIOS|Native|custom) + [Cable] + -r, --runs number of test runs [1] + -f, --first skip the Repeat View test + -v, --video capture video + -p, --private keep the test hidden from the test log + -L, --label